thread.cc revision d8af1592a97f7447ecf93f85098cb36340ab0fe2
18d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes/*
28d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * Copyright (C) 2011 The Android Open Source Project
38d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *
48d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * Licensed under the Apache License, Version 2.0 (the "License");
58d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * you may not use this file except in compliance with the License.
68d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * You may obtain a copy of the License at
78d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *
88d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *      http://www.apache.org/licenses/LICENSE-2.0
98d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *
108d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * Unless required by applicable law or agreed to in writing, software
118d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * distributed under the License is distributed on an "AS IS" BASIS,
128d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * See the License for the specific language governing permissions and
148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * limitations under the License.
158d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes */
16b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
17578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "thread.h"
18b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
198d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes#include <dynamic_annotations.h>
20b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers#include <pthread.h>
21b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers#include <sys/mman.h>
22dbf05b722af99ba2fd2f4c4fc7eb6c3e9880e5d1Brian Carlstrom#include <sys/resource.h>
23dbf05b722af99ba2fd2f4c4fc7eb6c3e9880e5d1Brian Carlstrom#include <sys/time.h>
24a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
25b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro#include <algorithm>
26dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes#include <bitset>
27eb4f614f2eb53b92ebd416fa418f550861655887Elliott Hughes#include <cerrno>
28a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include <iostream>
29b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro#include <list>
30b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
31872d4ec7225444d9400d30f9027247deb91012fdElliott Hughes#include "debugger.h"
32a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "class_linker.h"
33df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom#include "class_loader.h"
34408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers#include "heap.h"
35c5f7c91ab89055cffb573fff7e06dbdd860bccedElliott Hughes#include "jni_internal.h"
368e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes#include "monitor.h"
3757b86d47b66322693a070185fadfb43cb9c12eabIan Rogers#include "oat/runtime/context.h"
38a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "object.h"
396d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers#include "object_utils.h"
409a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson#include "reflection.h"
41578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "runtime.h"
425433072f589b61413e042eddf76e8190a048f71dbuzbee#include "runtime_support.h"
43726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes#include "ScopedLocalRef.h"
44aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#include "scoped_jni_thread_state.h"
45f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien#include "shadow_frame.h"
4630fab40ee5a07af6b8c3b6b0e9438071695a57f4Ian Rogers#include "space.h"
4768e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack.h"
4868e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack_indirect_reference_table.h"
498daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes#include "thread_list.h"
50a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include "utils.h"
51776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#include "verifier/gc_map.h"
52b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
53b557353b22c728eecbd1c68593b482622c7782a8Carl Shapironamespace art {
54b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
55b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiropthread_key_t Thread::pthread_key_self_;
56b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
57462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughesstatic Class* gThreadGroup = NULL;
588e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesstatic Class* gThreadLock = NULL;
59038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_daemon = NULL;
60038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_group = NULL;
61038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_lock = NULL;
62038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_name = NULL;
63038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_priority = NULL;
6429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Field* gThread_uncaughtHandler = NULL;
65038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_vmData = NULL;
66462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughesstatic Field* gThreadGroup_mMain = NULL;
67462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughesstatic Field* gThreadGroup_mSystem = NULL;
68038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThreadGroup_name = NULL;
698e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesstatic Field* gThreadLock_thread = NULL;
70038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Method* gThread_run = NULL;
7129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Method* gThreadGroup_removeThread = NULL;
7229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Method* gUncaughtExceptionHandler_uncaughtException = NULL;
73038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
745d76c435082332ef79a22962386fa92a0870e378Ian Rogersvoid Thread::InitCardTable() {
75b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes  card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
765d76c435082332ef79a22962386fa92a0870e378Ian Rogers}
775d76c435082332ef79a22962386fa92a0870e378Ian Rogers
7899250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#if !defined(__APPLE__)
793ea0f42467790809fcfc9fc861605d465808090fElliott Hughesstatic void UnimplementedEntryPoint() {
803ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  UNIMPLEMENTED(FATAL);
813ea0f42467790809fcfc9fc861605d465808090fElliott Hughes}
8299250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#endif
833ea0f42467790809fcfc9fc861605d465808090fElliott Hughes
843ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbeevoid Thread::InitFunctionPointers() {
8599250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
863ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
873ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
883ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
893ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  for (uintptr_t* it = begin; it != end; ++it) {
903ea0f42467790809fcfc9fc861605d465808090fElliott Hughes    *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
913ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  }
9299250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#endif
9357b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  InitEntryPoints(&entrypoints_);
94c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes}
95c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes
96c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughesvoid Thread::SetDebuggerUpdatesEnabled(bool enabled) {
97c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes  LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
98776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
9957b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  ChangeDebuggerEntryPoint(&entrypoints_, enabled);
100776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#else
101776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers  UNIMPLEMENTED(FATAL);
102776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
1033ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee}
1043ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee
105caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitTid() {
106caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  tid_ = ::art::GetTid();
107caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
108caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
109caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitAfterFork() {
110caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
1113147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes#if defined(__BIONIC__)
1123147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  // Work around a bionic bug.
1133147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  struct bionic_pthread_internal_t {
1143147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    void*  next;
1153147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    void** pref;
1163147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    pthread_attr_t attr;
1173147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    pid_t kernel_id;
1183147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    // et cetera. we just need 'kernel_id' so we can stop here.
1193147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  };
1203147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
1213147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes#endif
122caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
123caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
12478128a63b2615744760b7f8ab83df9764a5d4a95Brian Carlstromvoid* Thread::CreateCallback(void* arg) {
12593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
126462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  self->Init();
12793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
12893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Wait until it's safe to start running code. (There may have been a suspend-all
12993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // in progress while we were starting up.)
130462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  Runtime* runtime = Runtime::Current();
13193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  runtime->GetThreadList()->WaitForGo();
13293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
13347179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  {
13434e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes    CHECK_EQ(self->GetState(), kRunnable);
135899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    SirtRef<String> thread_name(self->GetThreadName());
136899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
13747179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  }
13847179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes
139872d4ec7225444d9400d30f9027247deb91012fdElliott Hughes  Dbg::PostThreadStart(self);
14093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
14193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Invoke the 'run' method of our java.lang.Thread.
14293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  CHECK(self->peer_ != NULL);
14393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Object* receiver = self->peer_;
144038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
14593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  m->Invoke(self, receiver, NULL, NULL);
14693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
14793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Detach.
14893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  runtime->GetThreadList()->Unregister();
14993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
150b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  return NULL;
151b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
152b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
153ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic void SetVmData(Object* managed_thread, Thread* native_thread) {
154038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
15593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
15693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
157761928d24e4e7ed7776b52243eaf9095ad35f448Elliott HughesThread* Thread::FromManagedThread(Object* thread_peer) {
158761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes  return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread_peer)));
159761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes}
160761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes
16101158d7a57c8321370667a6045220237d16e0da8Elliott HughesThread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
162761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes  return FromManagedThread(Decode<Object*>(env, java_thread));
16301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes}
16401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
165ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic size_t FixStackSize(size_t stack_size) {
1667502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // A stack size of zero means "use the default".
167d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (stack_size == 0) {
168d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    stack_size = Runtime::Current()->GetDefaultStackSize();
169d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
17061e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
1716414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom  // Dalvik used the bionic pthread default stack size for native threads,
1726414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom  // so include that here to support apps that expect large native stacks.
1736414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom  stack_size += 1 * MB;
1746414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom
1756414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom
1767502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
1777502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  if (stack_size < PTHREAD_STACK_MIN) {
1787502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes    stack_size = PTHREAD_STACK_MIN;
1797502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  }
1807502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
1817502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's likely that callers are trying to ensure they have at least a certain amount of
1827502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // stack space, so we should add our reserved space on top of what they requested, rather
1837502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // than implicitly take it away from them.
1847502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size += Thread::kStackOverflowReservedBytes;
1857502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
1867502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // Some systems require the stack size to be a multiple of the system page size, so round up.
1877502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = RoundUp(stack_size, kPageSize);
1887502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
1897502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  return stack_size;
1907502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes}
1917502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
192d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughesstatic void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
193d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  if (sigaltstack(new_stack, old_stack) == -1) {
194d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes    PLOG(FATAL) << "sigaltstack failed";
195d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  }
196d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes}
197d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
198d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughesstatic void SetUpAlternateSignalStack() {
199d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Create and set an alternate signal stack.
200d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  stack_t ss;
201d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_sp = new uint8_t[SIGSTKSZ];
202d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_size = SIGSTKSZ;
203d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_flags = 0;
204d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  CHECK(ss.ss_sp != NULL);
205d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(&ss, NULL);
206d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
207d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Double-check that it worked.
208d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_sp = NULL;
209d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(NULL, &ss);
210d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
211d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes}
212d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
213d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughesstatic void TearDownAlternateSignalStack() {
214d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Get the pointer so we can free the memory.
215d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  stack_t ss;
216d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(NULL, &ss);
217d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
218d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
219d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Tell the kernel to stop using it.
220d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_sp = NULL;
221d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_flags = SS_DISABLE;
222d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_size = 0;
223d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(&ss, NULL);
224d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
225d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Free it.
226d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  delete[] allocated_signal_stack;
227d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes}
228d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
2297502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughesvoid Thread::Create(Object* peer, size_t stack_size) {
2307502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  CHECK(peer != NULL);
2317502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2327502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = FixStackSize(stack_size);
2337502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
23493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* native_thread = new Thread;
23593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  native_thread->peer_ = peer;
23693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
23793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Thread.start is synchronized, so we know that vmData is 0,
23893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // and know that we're not racing to assign it.
23993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  SetVmData(peer, native_thread);
24061e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
24147179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  {
24234e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes    ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
24347179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    pthread_t new_pthread;
24447179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    pthread_attr_t attr;
24547179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
24647179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
24747179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
24847179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
24947179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
25047179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  }
25161e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
25293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Let the child know when it's safe to start running.
25393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Runtime::Current()->GetThreadList()->SignalGo(native_thread);
25493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
25561e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
256462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughesvoid Thread::Init() {
257462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // This function does all the initialization that must be run by the native thread it applies to.
258462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
259462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // we can handshake with the corresponding native thread when it's ready.) Check this native
260462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // thread hasn't been through here already...
261cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  CHECK(Thread::Current() == NULL);
262cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes
263d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SetUpAlternateSignalStack();
26493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitCpu();
26593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitFunctionPointers();
2665d76c435082332ef79a22962386fa92a0870e378Ian Rogers  InitCardTable();
26761e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
268462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  Runtime* runtime = Runtime::Current();
269462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  CHECK(runtime != NULL);
270462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes
271462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
272be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
273caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
27493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitStackHwm();
275dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
2763147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
277a5780dad67556297c8ca5f2608c53b193e6c4514Elliott Hughes
27893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
2795fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
2807a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  runtime->GetThreadList()->Register();
28193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
28293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
283462c94449720e0dc6b93d7138d835d345ccf67aeElliott HughesThread* Thread::Attach(const char* thread_name, bool as_daemon, Object* thread_group) {
284cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  Thread* self = new Thread;
285462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  self->Init();
2865fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
28734e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  self->SetState(kNative);
288726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
289cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  // If we're the main thread, ClassLinker won't be created until after we're attached,
290cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  // so that thread needs a two-stage attach. Regular threads don't need this hack.
291d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  // In the compiler, all threads need this hack, because no-one's going to be getting
292d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  // a native peer!
293d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
294462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes    self->CreatePeer(thread_name, as_daemon, thread_group);
29506e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  } else {
29606e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
29722869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes    if (thread_name != NULL) {
29822869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes      self->name_->assign(thread_name);
29922869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes      ::art::SetThreadName(thread_name);
30022869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes    }
30136e0a955e48e9357bff1eab783e493107ebfff62Ian Rogers  }
302cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes
303cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  self->GetJniEnv()->locals.AssertEmpty();
3045fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  return self;
3055fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes}
3065fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
307462c94449720e0dc6b93d7138d835d345ccf67aeElliott HughesObject* Thread::GetMainThreadGroup() {
3080045a290e6b79a274250e3112880c04bde437d4aIan Rogers  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
309462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes    return NULL;
310462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  }
311462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  return gThreadGroup_mMain->GetObject(NULL);
312d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes}
313d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
314462c94449720e0dc6b93d7138d835d345ccf67aeElliott HughesObject* Thread::GetSystemThreadGroup() {
3150045a290e6b79a274250e3112880c04bde437d4aIan Rogers  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
316462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes    return NULL;
317462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  }
318462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  return gThreadGroup_mSystem->GetObject(NULL);
319462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes}
320462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes
321462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughesvoid Thread::CreatePeer(const char* name, bool as_daemon, Object* thread_group) {
3229a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(Runtime::Current()->IsStarted());
3235fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  JNIEnv* env = jni_env_;
3245fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
325462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  if (thread_group == NULL) {
326462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes    thread_group = Thread::GetMainThreadGroup();
327462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  }
328462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  ScopedLocalRef<jobject> java_thread_group(env, AddLocalReference<jobject>(env, thread_group));
329726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
3308daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes  jint thread_priority = GetNativePriority();
3315fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  jboolean thread_is_daemon = as_daemon;
3325fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
333726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
3345d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  ScopedLocalRef<jobject> peer(env, env->AllocObject(c.get()));
335726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  peer_ = DecodeJObject(peer.get());
3365d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  if (peer_ == NULL) {
3375d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers    CHECK(IsExceptionPending());
3385d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers    return;
3395d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  }
3405d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
341462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  env->CallNonvirtualVoidMethod(peer.get(), c.get(), mid, java_thread_group.get(), thread_name.get(), thread_priority, thread_is_daemon);
3429a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(!IsExceptionPending()) << " " << PrettyTypeOf(GetException());
3437a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  SetVmData(peer_, Thread::Current());
344d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
345899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  SirtRef<String> peer_thread_name(GetThreadName());
34600fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  if (peer_thread_name.get() == NULL) {
34700fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // The Thread constructor should have set the Thread.name to a
34800fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // non-null value. However, because we can run without code
34900fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // available (in the compiler, in tests), we manually assign the
35000fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // fields the constructor should have set.
35100fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_daemon->SetBoolean(peer_, thread_is_daemon);
352462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes    gThread_group->SetObject(peer_, thread_group);
35300fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
35400fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_priority->SetInt(peer_, thread_priority);
355899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    peer_thread_name.reset(GetThreadName());
35600fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  }
35700fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  // thread_name may have been null, so don't trust this to be non-null
35800fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  if (peer_thread_name.get() != NULL) {
359899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
36000fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  }
361726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
362726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  // Pre-allocate an OutOfMemoryError for the double-OOME case.
363726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ThrowNewException("Ljava/lang/OutOfMemoryError;",
364726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
365726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
366726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  env->ExceptionClear();
367726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
36861e019d291583029c01b61b93bea750f2b663c37Carl Shapiro}
36961e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
370899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughesvoid Thread::SetThreadName(const char* name) {
371899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  name_->assign(name);
372899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  ::art::SetThreadName(name);
373899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
374899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes}
375899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes
376be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::InitStackHwm() {
377215f3144be114ac27002059330d903bf1ff5a592Elliott Hughes#if defined(__APPLE__)
3786cc332ef80edf56221676e33ea16bb4022130344Elliott Hughes  // Only needed to run code. Try implementing this with pthread_get_stacksize_np and pthread_get_stackaddr_np.
3796cc332ef80edf56221676e33ea16bb4022130344Elliott Hughes  UNIMPLEMENTED(WARNING);
380215f3144be114ac27002059330d903bf1ff5a592Elliott Hughes#else
381be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  pthread_attr_t attributes;
3823147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
383be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
384932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  void* temp_stack_base;
385932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
386932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers                     __FUNCTION__);
38730fab40ee5a07af6b8c3b6b0e9438071695a57f4Ian Rogers  stack_begin_ = reinterpret_cast<byte*>(temp_stack_base);
388be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
389932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  if (stack_size_ <= kStackOverflowReservedBytes) {
3903d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
391be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  }
392449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
393932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  // Set stack_end_ to the bottom of the stack saving space of stack overflows
394932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  ResetDefaultStackEnd();
395449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
396449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  // Sanity check.
397449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  int stack_variable;
398398f64b5805246765b699839b439e18c0dfbf2eeElliott Hughes  CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
399be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
4008d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
401215f3144be114ac27002059330d903bf1ff5a592Elliott Hughes#endif
402be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes}
403be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
404899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughesvoid Thread::Dump(std::ostream& os, bool full) const {
405899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  if (full) {
406899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    DumpState(os);
407899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    DumpStack(os);
408899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  } else {
409899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    os << "Thread[";
410899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    if (GetThinLockId() != 0) {
411899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      // If we're in kStarting, we won't have a thin lock id or tid yet.
412899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      os << GetThinLockId()
413899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes         << ",tid=" << GetTid() << ',';
414899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    }
415899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    os << GetState()
416899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes       << ",Thread*=" << this
417ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes       << ",peer=" << peer_
418899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes       << ",\"" << *name_ << "\""
419899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes       << "]";
420e0918556e7551de638870dcad3f2023f94f85a50Elliott Hughes  }
421d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes}
422d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
423899e789bd4741c0172268f7838ce8ab220a5f916Elliott HughesString* Thread::GetThreadName() const {
424fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
425fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
426fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
427ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughesvoid Thread::GetThreadName(std::string& name) const {
428ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  name.assign(*name_);
429ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
430ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes
431d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpState(std::ostream& os) const {
432d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::string group_name;
433d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  int priority;
434d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  bool is_daemon = false;
435d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
436d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
437038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    priority = gThread_priority->GetInt(peer_);
438038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    is_daemon = gThread_daemon->GetBoolean(peer_);
439d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
440a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes    Object* thread_group = GetThreadGroup();
441d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    if (thread_group != NULL) {
442038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes      String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
443d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes      group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
444d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
445d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  } else {
446d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    priority = GetNativePriority();
447dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes  }
448d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
449d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int policy;
450d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  sched_param sp;
4513147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
452d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
4531bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes  std::string scheduler_group_name(GetSchedulerGroupName(GetTid()));
4541bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes  if (scheduler_group_name.empty()) {
4551bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes    scheduler_group_name = "default";
456d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
457d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
458899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  os << '"' << *name_ << '"';
459d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (is_daemon) {
460d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    os << " daemon";
461d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
462d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << " prio=" << priority
463dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << " tid=" << GetThinLockId()
46493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes     << " " << GetState() << "\n";
465d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
466d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | group=\"" << group_name << "\""
4678d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     << " sCount=" << suspend_count_
468234ab15b00f8120282d1833e5d7480eca2e35a29Elliott Hughes     << " dsCount=" << debug_suspend_count_
469dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << " obj=" << reinterpret_cast<void*>(peer_)
470d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " self=" << reinterpret_cast<const void*>(this) << "\n";
471d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | sysTid=" << GetTid()
472d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " nice=" << getpriority(PRIO_PROCESS, GetTid())
473d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " sched=" << policy << "/" << sp.sched_priority
4741bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes     << " cgrp=" << scheduler_group_name
4753147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes     << " handle=" << pthread_self() << "\n";
476d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
477d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // Grab the scheduler stats for this thread.
478d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string scheduler_stats;
479d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
480d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
481d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  } else {
482d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats = "0 0 0";
483d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
484d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
485d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int utime = 0;
486d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int stime = 0;
487d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int task_cpu = 0;
488bfe487be25652c5456236661b9d9c3579d2296c1Elliott Hughes  GetTaskStats(GetTid(), utime, stime, task_cpu);
489d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
490d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | schedstat=( " << scheduler_stats << " )"
491d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " utm=" << utime
492d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " stm=" << stime
493d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " core=" << task_cpu
494d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
495a09576416788b916095739e43a16917e7948f3a4Elliott Hughes}
496a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
497ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#if !defined(ART_USE_LLVM_COMPILER)
498b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogersvoid Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
499b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  Method **sp = top_of_managed_stack_.GetSP();
500b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers#ifndef NDEBUG
501b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  if (sp != NULL) {
502b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    Method* m = *sp;
503b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes    Runtime::Current()->GetHeap()->VerifyObject(m);
504b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    DCHECK((m == NULL) || m->IsMethod());
505b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  }
506b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers#endif
507b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
508b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
509b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->link_ = native_to_managed_record_;
510b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  native_to_managed_record_ = record;
511b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_.SetSP(NULL);
512b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers}
513ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#else
514ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYavoid Thread::PushNativeToManagedRecord(NativeToManagedRecord*) {
515ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa  LOG(FATAL) << "Called non-LLVM method with LLVM";
516ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa}
517ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#endif
518b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers
519ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#if !defined(ART_USE_LLVM_COMPILER)
520b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogersvoid Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
521b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  native_to_managed_record_ = record.link_;
522b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
523b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
524b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers}
525ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#else
526ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYavoid Thread::PopNativeToManagedRecord(const NativeToManagedRecord&) {
527ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa  LOG(FATAL) << "Called non-LLVM method with LLVM";
528ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa}
529ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#endif
530b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers
531d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughesstruct StackDumpVisitor : public Thread::StackVisitor {
5328e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor(std::ostream& os, const Thread* thread)
53328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
53428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        frame_count(0) {
535d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
536d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
537bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual ~StackDumpVisitor() {
538d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
539d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
540530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
5419086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    if (!frame.HasMethod()) {
542530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;
5439086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    }
54428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    const int kMaxRepetition = 3;
545d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Method* m = frame.GetMethod();
546540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#if !defined(ART_USE_LLVM_COMPILER)
547d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Class* c = m->GetDeclaringClass();
5488e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
549b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    const DexCache* dex_cache = c->GetDexCache();
550b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    int line_number = -1;
551b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    if (dex_cache != NULL) {  // be tolerant of bad input
552b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers      const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
553b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers      line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
554b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    }
555540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#else
556540a5b768bf5f76bd71ebf66612fb2298899480fTDYa    // Compiler_LLVM stores line_number in the ShadowFrame, and passes it to visitor.
557540a5b768bf5f76bd71ebf66612fb2298899480fTDYa    int line_number = static_cast<int>(pc);
558540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#endif
55928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    if (line_number == last_line_number && last_method == m) {
56028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      repetition_count++;
561d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    } else {
56228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      if (repetition_count >= kMaxRepetition) {
56328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        os << "  ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
56428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      }
56528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      repetition_count = 0;
56628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      last_line_number = line_number;
56728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      last_method = m;
56828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    }
56928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    if (repetition_count < kMaxRepetition) {
57028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      os << "  at " << PrettyMethod(m, false);
57128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      if (m->IsNative()) {
57228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        os << "(Native method)";
57328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      } else {
5746d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        mh.ChangeMethod(m);
5756d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        const char* source_file(mh.GetDeclaringClassSourceFile());
5766d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        os << "(" << (source_file != NULL ? source_file : "unavailable")
57728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers           << ":" << line_number << ")";
57828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      }
57928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      os << "\n";
580d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
5818e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
5828e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    if (frame_count++ == 0) {
5838e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      Monitor::DescribeWait(os, thread);
5848e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
585530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
586d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
5876d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
58828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  Method* last_method;
58928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int last_line_number;
59028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int repetition_count;
591d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::ostream& os;
5928e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  const Thread* thread;
5938e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int frame_count;
594d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes};
595d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
596d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpStack(std::ostream& os) const {
597ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  // If we're currently in native code, dump that stack before dumping the managed stack.
59834e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  if (GetState() == kNative || GetState() == kVmWait) {
599ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    DumpNativeStack(os);
600ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
6018e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor dumper(os, this);
602d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  WalkStack(&dumper);
603e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes}
604e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes
60534e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughesvoid Thread::SetStateWithoutSuspendCheck(ThreadState new_state) {
606a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
607a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
608a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  android_atomic_release_store(new_state, addr);
609a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes}
610a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
61134e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott HughesThreadState Thread::SetState(ThreadState new_state) {
61234e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  ThreadState old_state = state_;
6138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (old_state == new_state) {
6148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    return old_state;
6158d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
6168d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6178d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
6188d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
6198d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
62034e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  if (new_state == kRunnable) {
6218d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
62234e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes     * Change our status to kRunnable.  The transition requires
62381ff3184e7eb8de4605c7646674ea4f9fa29b5f3Elliott Hughes     * that we check for pending suspension, because the runtime considers
6248d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * us to be "asleep" in all other states, and another thread could
6258d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * be performing a GC now.
6268d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6278d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * The order of operations is very significant here.  One way to
6288d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * do this wrong is:
6298d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6308d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   GCing thread                   Our thread (in kNative)
6318d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   ------------                   ----------------------
6328d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  check suspend count (== 0)
6338d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   SuspendAllThreads()
6348d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   grab suspend-count lock
6358d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   increment all suspend counts
6368d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   release suspend-count lock
6378d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   check thread state (== kNative)
6388d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   all are suspended, begin GC
6398d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  set state to kRunnable
6408d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  (continue executing)
6418d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6428d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can correct this by grabbing the suspend-count lock and
6438d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * performing both of our operations (check suspend count, set
6448d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * state) while holding it, now we need to grab a mutex on every
6458d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * transition to kRunnable.
6468d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6478d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * What we do instead is change the order of operations so that
6488d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the transition to kRunnable happens first.  If we then detect
6498d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the suspend count is nonzero, we switch to kSuspended.
6508d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6518d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Appropriate compiler and memory barriers are required to ensure
6528d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the operations are observed in the expected order.
6538d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6548d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * This does create a small window of opportunity where a GC in
6558d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * progress could observe what appears to be a running thread (if
6568d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * it happens to look between when we set to kRunnable and when we
6578d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * switch to kSuspended).  At worst this only affects assertions
6588d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * and thread logging.  (We could work around it with some sort
6598d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * of intermediate "pre-running" state that is generally treated
6608d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * as equivalent to running, but that doesn't seem worthwhile.)
6618d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6628d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can also solve this by combining the "status" and "suspend
6638d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * count" fields into a single 32-bit value.  This trades the
6648d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * store/load barrier on transition to kRunnable for an atomic RMW
6658d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * op on all transitions and all suspend count updates (also, all
6668d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * accesses to status or the thread count require bit-fiddling).
6678d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * It also eliminates the brief transition through kRunnable when
6688d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the thread is supposed to be suspended.  This is possibly faster
6698d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * on SMP and slightly more correct, but less convenient.
6708d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
6718d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_acquire_store(new_state, addr);
67206e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ANNOTATE_IGNORE_READS_BEGIN();
67306e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    int suspend_count = suspend_count_;
67406e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ANNOTATE_IGNORE_READS_END();
67506e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    if (suspend_count != 0) {
6768d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
6778d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
6788d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  } else {
6798d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
68034e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes     * Not changing to kRunnable. No additional work required.
6818d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6828d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We use a releasing store to ensure that, if we were runnable,
6838d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * any updates we previously made to objects on the managed heap
6848d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * will be observed before the state change.
6858d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
6868d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_release_store(new_state, addr);
6878d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
6888d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6898d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  return old_state;
6908d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
6918d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
692761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughesbool Thread::IsSuspended() {
69306e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  ANNOTATE_IGNORE_READS_BEGIN();
69406e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  int suspend_count = suspend_count_;
69506e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  ANNOTATE_IGNORE_READS_END();
69634e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  return suspend_count != 0 && GetState() != kRunnable;
697761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes}
698761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes
699ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughesstatic void ReportThreadSuspendTimeout(Thread* waiting_thread) {
700ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  Runtime* runtime = Runtime::Current();
701ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  std::ostringstream ss;
702ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
703ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  runtime->DumpLockHolders(ss);
704ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  ss << "\n";
705ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  runtime->GetThreadList()->DumpLocked(ss);
706ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  LOG(FATAL) << ss.str();
707ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes}
708ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes
7098d768a954b101a9532f980253ac46be2c53aba11Elliott Hughesvoid Thread::WaitUntilSuspended() {
71021a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes  static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
71121a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes
71221a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes  useconds_t total_delay = 0;
7138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  useconds_t delay = 0;
71434e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  while (GetState() == kRunnable) {
71521a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes    if (total_delay >= kTimeoutUs) {
716ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes      ReportThreadSuspendTimeout(this);
71721a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes    }
7188d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    useconds_t new_delay = delay * 2;
7198d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    CHECK_GE(new_delay, delay);
7208d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    delay = new_delay;
7218d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    if (delay == 0) {
7228d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      sched_yield();
7238d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      delay = 10000;
7248d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    } else {
7258d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      usleep(delay);
72621a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes      total_delay += delay;
7278d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
7288d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
7298d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
7308d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
731be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::ThreadExitCallback(void* arg) {
732be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
733be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
734b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
735b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
736be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::Startup() {
737b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Allocate a TLS slot.
7388d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
739b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
740b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Double-check the TLS slot allocation.
741b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  if (pthread_getspecific(pthread_key_self_) != NULL) {
7423d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
743b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  }
744038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
745038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
7468e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
747ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
7488e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindSystemClass(descriptor);
7498e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
7508e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
7518e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7528e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7538e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
754ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic Field* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
7556b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Field* f = c->FindDeclaredInstanceField(name, descriptor);
7566b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
7578e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return f;
7588e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7598e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7608e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
761ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
7628e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Method* m = c->FindVirtualMethod(name, signature);
7638e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
7648e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return m;
7658e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7668e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
767462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes// TODO: make more accessible?
768ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic Field* FindStaticFieldOrDie(Class* c, const char* name, const char* descriptor) {
769462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  Field* f = c->FindDeclaredStaticField(name, descriptor);
770462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
771462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  return f;
772462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes}
773462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes
774038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesvoid Thread::FinishStartup() {
7759a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(Runtime::Current()->IsStarted());
776b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  Thread* self = Thread::Current();
777b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
778b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  // Need to be kRunnable for FindClass
77934e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  ScopedThreadStateChange tsc(self, kRunnable);
780b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
781038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
782038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
7838e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7848e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
7858e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
786462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  gThreadGroup = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
7878e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
7888e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7896b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
7906b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
7916b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
7926b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
7936b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
7946b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
7956b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
796462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  gThreadGroup_name = FindFieldOrDie(gThreadGroup, "name", "Ljava/lang/String;");
797462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  gThreadGroup_mMain = FindStaticFieldOrDie(gThreadGroup, "mMain", "Ljava/lang/ThreadGroup;");
798462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  gThreadGroup_mSystem = FindStaticFieldOrDie(gThreadGroup, "mSystem", "Ljava/lang/ThreadGroup;");
7996b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
8008e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8018e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
802462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  gThreadGroup_removeThread = FindMethodOrDie(gThreadGroup, "removeThread", "(Ljava/lang/Thread;)V");
8038e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
8048e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
80501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
80601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  // Finish attaching the main thread.
807462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  Thread::Current()->CreatePeer("main", false, Thread::GetMainThreadGroup());
8089a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson
8099a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  InitBoxingMethods();
8109a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  class_linker->RunRootClinits();
811b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
812b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
813c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughesvoid Thread::Shutdown() {
8148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
815c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
816c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
8178e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesuint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
8188e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
8198e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8208e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8218e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
8228e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (managed_thread == NULL) {
8238e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8248e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8258e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
8268e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Thread* thread = reinterpret_cast<Thread*>(vmData);
8278e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread == NULL) {
8288e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8298e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8308e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return thread->GetThinLockId();
8318e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
8328e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
833dcc247493fd8fb243e335c3ec08e5e625896a47cElliott HughesThread::Thread()
83447179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    : thin_lock_id_(0),
83547179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      tid_(0),
83647179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      peer_(NULL),
8378e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_(),
8388e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_pc_(0),
839e62934d85fbc2d935afdad57eeade39ecbd7440aElliott Hughes      wait_mutex_(new Mutex("a thread wait mutex")),
840e62934d85fbc2d935afdad57eeade39ecbd7440aElliott Hughes      wait_cond_(new ConditionVariable("a thread wait condition variable")),
8418daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      wait_monitor_(NULL),
8428daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      interrupted_(false),
843dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      wait_next_(NULL),
8448e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      monitor_enter_object_(NULL),
845dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      card_table_(0),
8468daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      stack_end_(NULL),
847dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      native_to_managed_record_(NULL),
848dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      top_sirt_(NULL),
849f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien      top_shadow_frame_(NULL),
850dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      jni_env_(NULL),
85134e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes      state_(kNative),
852dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      self_(NULL),
853dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      runtime_(NULL),
854dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      exception_(NULL),
855dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      suspend_count_(0),
856234ab15b00f8120282d1833e5d7480eca2e35a29Elliott Hughes      debug_suspend_count_(0),
85785d1545e985ac689db4bad7849880e843707c862Elliott Hughes      class_loader_override_(NULL),
858418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes      long_jump_context_(NULL),
859726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      throwing_OutOfMemoryError_(false),
860475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes      pre_allocated_OutOfMemoryError_(NULL),
861e343b76af81a005ef64f5e75a555389fd9147dabjeffhao      debug_invoke_req_(new DebugInvokeReq),
862899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      trace_stack_(new std::vector<TraceStackFrame>),
863899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      name_(new std::string("<native thread without managed peer>")) {
864f5a7a476e7ea63e094ff0f011dccc170607e6f6bElliott Hughes  CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
865ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
866dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes}
867dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
868ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic void MonitorExitVisitor(const Object* object, void*) {
86902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  Object* entered_monitor = const_cast<Object*>(object);
870ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughes  LOG(WARNING) << "Calling MonitorExit on object " << object << " (" << PrettyTypeOf(object) << ")"
871ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughes               << " left locked by native thread " << *Thread::Current() << " which is detaching";
8725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  entered_monitor->MonitorExit(Thread::Current());
87302b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes}
87402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
875c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughesvoid Thread::Destroy() {
87602b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
87793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (jni_env_ != NULL) {
87893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
87993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  }
88002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
88129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  if (peer_ != NULL) {
882c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes    Thread* self = this;
88329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
884534da072d3db3beecbd74e5aa23d630d73695f2cElliott Hughes    // We may need to call user-supplied managed code.
88534e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes    SetState(kRunnable);
886534da072d3db3beecbd74e5aa23d630d73695f2cElliott Hughes
887534da072d3db3beecbd74e5aa23d630d73695f2cElliott Hughes    HandleUncaughtExceptions();
888534da072d3db3beecbd74e5aa23d630d73695f2cElliott Hughes    RemoveFromThreadGroup();
889534da072d3db3beecbd74e5aa23d630d73695f2cElliott Hughes
89029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // this.vmData = 0;
89193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    SetVmData(peer_, NULL);
89202b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
893c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes    Dbg::PostThreadDeath(self);
89402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
89529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // Thread.join() is implemented as an Object.wait() on the Thread.lock
89629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // object. Signal anyone who is waiting.
897038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    Object* lock = gThread_lock->GetObject(peer_);
898038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    // (This conditional is only needed for tests, where Thread.lock won't have been set.)
8995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock != NULL) {
9005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorEnter(self);
9015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->NotifyAll();
9025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorExit(self);
9035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
9045f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
905c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes}
90602b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
907c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott HughesThread::~Thread() {
908c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes  delete jni_env_;
90902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  jni_env_ = NULL;
91002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
91134e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  SetState(kTerminated);
91285d1545e985ac689db4bad7849880e843707c862Elliott Hughes
91385d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_cond_;
91485d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_mutex_;
91585d1545e985ac689db4bad7849880e843707c862Elliott Hughes
916776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
91785d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete long_jump_context_;
918776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
919475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes
920475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes  delete debug_invoke_req_;
921e343b76af81a005ef64f5e75a555389fd9147dabjeffhao  delete trace_stack_;
922899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  delete name_;
923d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
924d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  TearDownAlternateSignalStack();
925c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
926c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
927accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::HandleUncaughtExceptions() {
928accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (!IsExceptionPending()) {
929accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    return;
930accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
931accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
932accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Get and clear the exception.
933accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* exception = GetException();
934accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
935accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
936accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the thread has its own handler, use that.
937accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* handler = gThread_uncaughtHandler->GetObject(peer_);
938accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (handler == NULL) {
939accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    // Otherwise use the thread group's default handler.
940a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes    handler = GetThreadGroup();
941accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
942accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
943accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Call the handler.
944accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
94577405796564c6c1353807cda18b28678a719bd68Elliott Hughes  JValue args[2];
946f24d3cedd395690f6904aaac80f84a100420f7a3Elliott Hughes  args[0].SetL(peer_);
947f24d3cedd395690f6904aaac80f84a100420f7a3Elliott Hughes  args[1].SetL(exception);
94877405796564c6c1353807cda18b28678a719bd68Elliott Hughes  m->Invoke(this, handler, args, NULL);
949accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
950accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the handler threw, clear that exception too.
951accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
952accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
9534514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom
954a215526d5c789cbef0f81a1f9aba22541a841ccaElliott HughesObject* Thread::GetThreadGroup() const {
955a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes  return gThread_group->GetObject(peer_);
956a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes}
957a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes
9584514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstromvoid Thread::RemoveFromThreadGroup() {
9594514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // this.group.removeThread(this);
9604514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // group can be null if we're in the compiler or a test.
961a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes  Object* group = GetThreadGroup();
9624514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  if (group != NULL) {
9634514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
96477405796564c6c1353807cda18b28678a719bd68Elliott Hughes    JValue args[1];
965f24d3cedd395690f6904aaac80f84a100420f7a3Elliott Hughes    args[0].SetL(peer_);
96677405796564c6c1353807cda18b28678a719bd68Elliott Hughes    m->Invoke(this, group, args, NULL);
9674514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  }
9684514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom}
969accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
970408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogerssize_t Thread::NumSirtReferences() {
971a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  size_t count = 0;
97240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
973a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    count += cur->NumberOfReferences();
974a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
975a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return count;
976a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
977a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
97828f1a147d77ec772db98bed890b50a9ddcff2365TDYasize_t Thread::NumShadowFrameReferences() {
97928f1a147d77ec772db98bed890b50a9ddcff2365TDYa  size_t count = 0;
98028f1a147d77ec772db98bed890b50a9ddcff2365TDYa  for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
98128f1a147d77ec772db98bed890b50a9ddcff2365TDYa    count += cur->NumberOfReferences();
98228f1a147d77ec772db98bed890b50a9ddcff2365TDYa  }
98328f1a147d77ec772db98bed890b50a9ddcff2365TDYa  return count;
98428f1a147d77ec772db98bed890b50a9ddcff2365TDYa}
98528f1a147d77ec772db98bed890b50a9ddcff2365TDYa
986408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogersbool Thread::SirtContains(jobject obj) {
987408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object** sirt_entry = reinterpret_cast<Object**>(obj);
98840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
98940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (cur->Contains(sirt_entry)) {
990a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers      return true;
991a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    }
992a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
993a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return false;
994a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
995a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
99628f1a147d77ec772db98bed890b50a9ddcff2365TDYabool Thread::ShadowFrameContains(jobject obj) {
99728f1a147d77ec772db98bed890b50a9ddcff2365TDYa  Object** shadow_frame_entry = reinterpret_cast<Object**>(obj);
99828f1a147d77ec772db98bed890b50a9ddcff2365TDYa  for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
99928f1a147d77ec772db98bed890b50a9ddcff2365TDYa    if (cur->Contains(shadow_frame_entry)) {
100028f1a147d77ec772db98bed890b50a9ddcff2365TDYa      return true;
100128f1a147d77ec772db98bed890b50a9ddcff2365TDYa    }
100228f1a147d77ec772db98bed890b50a9ddcff2365TDYa  }
100328f1a147d77ec772db98bed890b50a9ddcff2365TDYa  return false;
100428f1a147d77ec772db98bed890b50a9ddcff2365TDYa}
100528f1a147d77ec772db98bed890b50a9ddcff2365TDYa
100628f1a147d77ec772db98bed890b50a9ddcff2365TDYabool Thread::StackReferencesContain(jobject obj) {
100728f1a147d77ec772db98bed890b50a9ddcff2365TDYa  return SirtContains(obj) || ShadowFrameContains(obj);
100828f1a147d77ec772db98bed890b50a9ddcff2365TDYa}
100928f1a147d77ec772db98bed890b50a9ddcff2365TDYa
10108dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liaovoid Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
101140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
10128dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    size_t num_refs = cur->NumberOfReferences();
10138dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    for (size_t j = 0; j < num_refs; j++) {
101440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      Object* object = cur->GetReference(j);
10155e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      if (object != NULL) {
10165e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom        visitor(object, arg);
10175e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      }
10188dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    }
10198dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  }
10208dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao}
10218dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1022f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chienvoid Thread::ShadowFrameVisitRoots(Heap::RootVisitor* visitor, void* arg) {
1023f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1024f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien    size_t num_refs = cur->NumberOfReferences();
1025f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien    for (size_t j = 0; j < num_refs; j++) {
1026f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien      Object* object = cur->GetReference(j);
1027f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien      if (object != NULL) {
1028f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien        visitor(object, arg);
1029f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien      }
1030f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien    }
1031f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  }
1032f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien}
1033f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien
1034408f79aeb676251ba35667a64e86c20638d7cb0bIan RogersObject* Thread::DecodeJObject(jobject obj) {
10350cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  DCHECK(CanAccessDirectReferences());
1036408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (obj == NULL) {
1037408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    return NULL;
1038408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1039408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1040408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRefKind kind = GetIndirectRefKind(ref);
1041408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object* result;
1042408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  switch (kind) {
1043408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kLocal:
1044408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
104569f5bc6759f256a146eefd8a7141d39fcc3b0421Elliott Hughes      IndirectReferenceTable& locals = jni_env_->locals;
1046cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(locals.Get(ref));
1047408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1048408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1049408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kGlobal:
1050408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1051408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1052408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& globals = vm->globals;
1053408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->globals_lock);
1054cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(globals.Get(ref));
1055408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1056408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1057408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kWeakGlobal:
1058408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1059408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1060408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& weak_globals = vm->weak_globals;
1061408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->weak_globals_lock);
1062cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(weak_globals.Get(ref));
1063408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      if (result == kClearedJniWeakGlobal) {
1064408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        // This is a special case where it's okay to return NULL.
1065408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        return NULL;
1066408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      }
1067408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1068408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1069408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kSirtOrInvalid:
1070408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  default:
1071408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // TODO: make stack indirect reference table lookup more efficient
1072408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // Check if this is a local reference in the SIRT
107328f1a147d77ec772db98bed890b50a9ddcff2365TDYa    if (StackReferencesContain(obj)) {
10740cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers      result = *reinterpret_cast<Object**>(obj);  // Read from SIRT
1075c2dc62d1c9241dfe880a81698713c314b13aa63fElliott Hughes    } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
1076408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      // Assume an invalid local reference is actually a direct pointer.
1077408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      result = reinterpret_cast<Object*>(obj);
1078408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    } else {
1079a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes      result = kInvalidIndirectRefObject;
1080408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1081408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1082408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
1083408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (result == NULL) {
1084a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1085a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    JniAbort(NULL);
1086a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes  } else {
1087a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    if (result != kInvalidIndirectRefObject) {
1088b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes      Runtime::Current()->GetHeap()->VerifyObject(result);
1089a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    }
1090408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1091408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  return result;
1092408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers}
1093408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
10949b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liaoclass CountStackDepthVisitor : public Thread::StackVisitor {
10959b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
109629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
1097d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
10981bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t /*pc*/) {
109929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // We want to skip frames up to and including the exception's constructor.
11009086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // Note we also skip the frame if it doesn't have a method (namely the callee
11019086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // save frame)
11025167c97a4f672ba821453418e3943988fabbfc43Ian Rogers    if (skipping_ && frame.HasMethod() &&
11035167c97a4f672ba821453418e3943988fabbfc43Ian Rogers        !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
110429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skipping_ = false;
110529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
110629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (!skipping_) {
11076b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      if (frame.HasMethod()) {  // ignore callee save frames
11086b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers        ++depth_;
11096b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      }
111029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    } else {
111129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      ++skip_depth_;
111229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
1113530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
11149b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11159b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
11169b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int GetDepth() const {
1117aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return depth_;
11189b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11199b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
112029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int GetSkipDepth() const {
112129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    return skip_depth_;
112229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  }
112329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
11249b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
1125aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t depth_;
112629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  uint32_t skip_depth_;
112729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  bool skipping_;
11289b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
11299b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1130aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogersclass BuildInternalStackTraceVisitor : public Thread::StackVisitor {
11319b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
1132283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  explicit BuildInternalStackTraceVisitor(int skip_depth)
1133726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
1134283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
1135283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers
1136283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  bool Init(int depth, ScopedJniThreadState& ts) {
1137aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate method trace with an extra slot that will hold the PC trace
113801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
1139726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL) {
1140283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1141726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1142aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Register a local reference as IntArray::Alloc may trigger GC
1143aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1144aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace_ = IntArray::Alloc(depth);
1145726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (pc_trace_ == NULL) {
1146283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1147726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1148aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1149aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1150267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom    method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1151aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
1152aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Save PC trace in last element of method trace, also places it into the
1153aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // object graph.
1154aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(depth, pc_trace_);
1155283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return true;
11569b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11579b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1158aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  virtual ~BuildInternalStackTraceVisitor() {}
11599b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1160530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
1161726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL || pc_trace_ == NULL) {
1162530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
1163726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
116429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (skip_depth_ > 0) {
116529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skip_depth_--;
1166530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;
116729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
11686b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    if (!frame.HasMethod()) {
1169530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;  // ignore callee save frames
11706b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    }
1171aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(count_, frame.GetMethod());
1172bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    pc_trace_->Set(count_, pc);
1173aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    ++count_;
1174530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
11759b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11769b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1177aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject GetInternalStackTrace() const {
1178aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return local_ref_;
11799b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11809b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
11819b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
118229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  // How many more frames to skip.
118329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth_;
1184aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Current position down stack trace
1185aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t count_;
1186aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Array of return PC values
1187aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace_;
1188aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // An array of the methods on the stack, the last entry is a reference to the
1189aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // PC trace
1190aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace_;
1191aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Local indirect reference table entry for method trace
1192aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject local_ref_;
11939b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
11949b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1195776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
1196a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1197ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic uintptr_t ManglePc(uintptr_t pc) {
1198a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Move the PC back 2 bytes as a call will frequently terminate the
1199a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // decoding of a particular instruction and we want to make sure we
1200a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // get the Dex PC of the instruction with the call and not the
1201a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // instruction following.
1202a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  if (pc > 0) { pc -= 2; }
1203a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  return pc;
1204a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1205776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
1206a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes
1207a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1208ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic uintptr_t DemanglePc(uintptr_t pc) {
1209a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Revert mangling for the case where we need the PC to return to the upcall
12109a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  if (pc > 0) { pc +=  2; }
12119a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  return pc;
1212a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1213f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers
1214f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chienvoid Thread::PushShadowFrame(ShadowFrame* frame) {
1215f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  frame->SetLink(top_shadow_frame_);
1216f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  top_shadow_frame_ = frame;
1217f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien}
1218f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien
1219f7ad17e108b9357d7c94c6218a8521140a667f3dLogan ChienShadowFrame* Thread::PopShadowFrame() {
1220f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  CHECK(top_shadow_frame_ != NULL);
1221f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  ShadowFrame* frame = top_shadow_frame_;
1222f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  top_shadow_frame_ = frame->GetLink();
1223f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  return frame;
1224f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien}
1225f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien
122640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstromvoid Thread::PushSirt(StackIndirectReferenceTable* sirt) {
122740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  sirt->SetLink(top_sirt_);
122840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = sirt;
122940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
123040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
123140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian CarlstromStackIndirectReferenceTable* Thread::PopSirt() {
123240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  CHECK(top_sirt_ != NULL);
123340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  StackIndirectReferenceTable* sirt = top_sirt_;
123440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = top_sirt_->GetLink();
123540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  return sirt;
123640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
123740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
12389b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa#if !defined(ART_USE_LLVM_COMPILER) // LLVM use ShadowFrame
12399b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa
1240530fa005e2944d3b12712f80d974f0e753f568efElliott Hughesvoid Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
1241d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  Frame frame = GetTopOfStack();
1242a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1243a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao  uint32_t trace_stack_depth = 0;
12449b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
12459b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // CHECK(native_to_managed_record_ != NULL);
12469b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  NativeToManagedRecord* record = native_to_managed_record_;
124757b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  bool method_tracing_active = Runtime::Current()->IsMethodTracingActive();
1248530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  while (frame.GetSP() != NULL) {
1249530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    for ( ; frame.GetMethod() != NULL; frame.Next()) {
1250f8bbb8448c733e9e3ad43aad69774c37888329b1Brian Carlstrom      frame.GetMethod()->AssertPcIsWithinCode(pc);
1251530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      bool should_continue = visitor->VisitFrame(frame, pc);
125257b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      if (UNLIKELY(!should_continue)) {
1253530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        return;
1254530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      }
125557b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      uintptr_t return_pc = frame.GetReturnPC();
125657b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      if (LIKELY(!method_tracing_active)) {
125757b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        pc = ManglePc(return_pc);
125857b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      } else {
12590791adc2249366c50684935a4c42ba5e58bc3746jeffhao        // While profiling, the return pc is restored from the side stack, except when walking
12600791adc2249366c50684935a4c42ba5e58bc3746jeffhao        // the stack for an exception where the side stack will be unwound in VisitFrame.
12610791adc2249366c50684935a4c42ba5e58bc3746jeffhao        if (IsTraceExitPc(return_pc) && !include_upcalls) {
1262a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao          TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
126326c0a1a376d8cd639fe6b16594fcb55a723450c0jeffhao          CHECK(trace_frame.method_ == frame.GetMethod());
1264a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao          pc = ManglePc(trace_frame.return_pc_);
126557b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        } else {
126657b86d47b66322693a070185fadfb43cb9c12eabIan Rogers          pc = ManglePc(return_pc);
1267a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        }
1268a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao      }
12699b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
1270530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (include_upcalls) {
1271530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      bool should_continue = visitor->VisitFrame(frame, pc);
1272530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (!should_continue) {
1273530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        return;
1274530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      }
1275530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
12769b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    if (record == NULL) {
1277530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return;
12789b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
1279bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    // last_tos should return Frame instead of sp?
1280ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers    frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
1281a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes    pc = ManglePc(record->last_top_of_managed_stack_pc_);
1282bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    record = record->link_;
1283bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  }
1284bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1285bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
12869b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa#else // defined(ART_USE_LLVM_COMPILER) // LLVM uses ShadowFrame
12879b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa
12889b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYavoid Thread::WalkStack(StackVisitor* visitor, bool /*include_upcalls*/) const {
12899b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa  for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
12909b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa    Frame frame;
12919b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa    frame.SetSP(reinterpret_cast<Method**>(reinterpret_cast<byte*>(cur) +
12929b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa                                           ShadowFrame::MethodOffset()));
129302f01fedc5180d1d5a795674f8c5bd0a3ce974d2Shih-wei Liao    bool should_continue = visitor->VisitFrame(frame, cur->GetLineNumber());
12949b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa    if (!should_continue) {
12959b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa      return;
12969b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa    }
12979b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa  }
12989b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa}
12999b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa
13009b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa/*
13019b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |                        |
13029b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |                        |
13039b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |                        |
13049b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13059b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13069b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13079b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13089b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                | Method*                |
13099b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13109b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 | <-- top_shadow_frame_   (ShadowFrame*)
13119b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                              / +------------------------+
13129b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                              ->|      .                 |
13139b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                              . |      .                 |
13149b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                              . |      .                 |
13159b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                               /+------------------------+
13169b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                              / |      .                 |
13179b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                             /  |      .                 |
13189b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *     ---                     |  |      .                 |
13199b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *      |                      |  |      .                 |
13209b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                             |  | Method*                | <-- frame.GetSP() (Method**)
13219b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *  ShadowFrame                \  |      .                 |
13229b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *      |                       ->|      .                 | <-- cur           (ShadowFrame*)
13239b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *     ---                       /+------------------------+
13249b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                              / |      .                 |
13259b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                             /  |      .                 |
13269b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *     ---                     |  |      .                 |
13279b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *      |       cur->GetLink() |  |      .                 |
13289b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                             |  | Method*                |
13299b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *   ShadowFrame               \  |      .                 |
13309b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *      |                       ->|      .                 |
13319b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *     ---                        +------------------------+
13329b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13339b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13349b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                |      .                 |
13359b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa *                                +========================+
13369b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa */
13379b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa
13389b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa#endif
13399b2ba2ee9fafe46a08473657a2387fd20ab49a35TDYa
134001158d7a57c8321370667a6045220237d16e0da8Elliott Hughesjobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
1341aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Compute depth of stack
13429b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  CountStackDepthVisitor count_visitor;
13439b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  WalkStack(&count_visitor);
13449b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int32_t depth = count_visitor.GetDepth();
134529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth = count_visitor.GetSkipDepth();
13464417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1347aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
134801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ScopedJniThreadState ts(env);
1349aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1350aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Build internal stack trace
135177f74c1455bd8d29deb8a9367cea35deb930ed10Ian Rogers  BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
135277f74c1455bd8d29deb8a9367cea35deb930ed10Ian Rogers  if (!build_trace_visitor.Init(depth, ts)) {
1353283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return NULL;  // Allocation failed
1354283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
1355267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom  WalkStack(&build_trace_visitor);
1356267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom  return build_trace_visitor.GetInternalStackTrace();
1357aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers}
1358aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
135901158d7a57c8321370667a6045220237d16e0da8Elliott HughesjobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
136001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    jobjectArray output_array, int* stack_depth) {
1361aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
1362aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ScopedJniThreadState ts(env);
1363aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Decode the internal stack trace into the depth, method trace and PC trace
1364aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace =
1365aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers      down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
13669074b99bfbd5419e340f138a018b673ce71f77e8Ian Rogers  int32_t depth = method_trace->GetLength() - 1;
1367aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1368aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1369aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1370aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
137101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  jobjectArray result;
137201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ObjectArray<StackTraceElement>* java_traces;
137301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (output_array != NULL) {
137401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Reuse the array we were given.
137501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = output_array;
137601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
137701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes        output_array));
137801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // ...adjusting the number of frames we'll write to not exceed the array length.
137901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    depth = std::min(depth, java_traces->GetLength());
138001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  } else {
138101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Create java_trace array and place in local reference table
138201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = class_linker->AllocStackTraceElementArray(depth);
138330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (java_traces == NULL) {
138430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
138530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
138601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
138701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
138801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
138901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (stack_depth != NULL) {
139001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    *stack_depth = depth;
139101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
139255df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
13936d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
13949b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  for (int32_t i = 0; i < depth; ++i) {
1395aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1396aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    Method* method = down_cast<Method*>(method_trace->Get(i));
13976d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    mh.ChangeMethod(method);
1398aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    uint32_t native_pc = pc_trace->Get(i);
139902f01fedc5180d1d5a795674f8c5bd0a3ce974d2Shih-wei Liao#if !defined(ART_USE_LLVM_COMPILER)
14006d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
140102f01fedc5180d1d5a795674f8c5bd0a3ce974d2Shih-wei Liao#else
140202f01fedc5180d1d5a795674f8c5bd0a3ce974d2Shih-wei Liao    int32_t line_number = native_pc; // LLVM stored line_number in the ShadowFrame
140302f01fedc5180d1d5a795674f8c5bd0a3ce974d2Shih-wei Liao#endif
1404aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate element, potentially triggering GC
140540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    // TODO: reuse class_name_object via Class::name_?
1406486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* descriptor = mh.GetDeclaringClassDescriptor();
1407486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(descriptor != NULL);
1408486013193c94b4321414c28ce9251911e14a0599Ian Rogers    std::string class_name(PrettyDescriptor(descriptor));
140940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
141040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (class_name_object.get() == NULL) {
141140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      return NULL;
141240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    }
1413486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* method_name = mh.GetName();
1414486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(method_name != NULL);
1415486013193c94b4321414c28ce9251911e14a0599Ian Rogers    SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
14166d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    if (method_name_object.get() == NULL) {
14176d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      return NULL;
14186d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    }
1419486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* source_file = mh.GetDeclaringClassSourceFile();
1420486013193c94b4321414c28ce9251911e14a0599Ian Rogers    SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
142140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
14226d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      method_name_object.get(),
14236d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      source_name_object.get(),
142440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      line_number);
142530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (obj == NULL) {
142630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
142730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
1428aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1429aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1430aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1431aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1432aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1433aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
143455df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao    java_traces->Set(i, obj);
143555df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
1436aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  return result;
143755df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
143855df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
14395cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1440a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_list args;
1441a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_start(args, fmt);
14424a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1443a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_end(args);
14444a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes}
14454a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes
14464a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughesvoid Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
14474a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  std::string msg;
14484a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  StringAppendV(&msg, fmt, ap);
14495cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes  ThrowNewException(exception_class_descriptor, msg.c_str());
14505cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes}
145137f7a40f6789bb287f287a9af00777af9d6428eeElliott Hughes
14525cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
1453e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
14540cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ('L', exception_class_descriptor[0]);
1455e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  std::string descriptor(exception_class_descriptor + 1);
14560cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ(';', descriptor[descriptor.length() - 1]);
1457e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  descriptor.erase(descriptor.length() - 1);
1458e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes
1459e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  JNIEnv* env = GetJniEnv();
1460726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
146130646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (exception_class.get() == NULL) {
146230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
146330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
146430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
146530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    return;
146630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1467ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  if (!Runtime::Current()->IsStarted()) {
1468ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // Something is trying to throw an exception without a started
1469ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // runtime, which is the common case in the compiler. We won't be
1470ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // able to invoke the constructor of the exception, so use
1471ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // AllocObject which will not invoke a constructor.
1472ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    ScopedLocalRef<jthrowable> exception(
1473ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom        env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1474ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    if (exception.get() != NULL) {
1475ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      ScopedJniThreadState ts(env);
1476ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
147702fbef0e356ca43b2032044f870d59de4a4ae92aIan Rogers      t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
1478ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      ts.Self()->SetException(t);
1479ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    } else {
1480ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1481ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom                 << PrettyTypeOf(GetException());
1482ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      CHECK(IsExceptionPending());
1483ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    }
1484ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    return;
1485ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  }
1486726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  int rc = env->ThrowNew(exception_class.get(), msg);
148730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (rc != JNI_OK) {
148830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
148930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
149030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
149130646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1492a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes}
1493a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes
14942ced6a534157d5d963693346904389c19775d2daElliott Hughesvoid Thread::ThrowOutOfMemoryError(const char* msg) {
14952ced6a534157d5d963693346904389c19775d2daElliott Hughes  LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
14962ced6a534157d5d963693346904389c19775d2daElliott Hughes      msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
1497726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (!throwing_OutOfMemoryError_) {
1498726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    throwing_OutOfMemoryError_ = true;
1499accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
1500418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  } else {
1501726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    SetException(pre_allocated_OutOfMemoryError_);
1502418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  }
1503726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  throwing_OutOfMemoryError_ = false;
150479082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes}
150579082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes
1506accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1507498508c1187dc07d3eae5476784cde20f5224d93Elliott HughesThread* Thread::CurrentFromGdb() {
1508accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  return Thread::Current();
1509accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1510accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1511accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::DumpFromGdb() const {
15126b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::ostringstream ss;
15136b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Dump(ss);
1514955724179c6c739524f610023287f56b24dc31deElliott Hughes  std::string str(ss.str());
15156b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to stderr for debugging command line processes
15166b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::cerr << str;
15176b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#ifdef HAVE_ANDROID_OS
15186b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to logcat for debugging frameworks processes
15196b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  LOG(INFO) << str;
15206b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#endif
1521accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1522accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
152328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughesvoid Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
152428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
15253d71d0799748aac23ce5935d61b909bec6e96461Elliott Hughes#define DO_THREAD_OFFSET(x) if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { os << # x; } else
152628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes#define DO_THREAD_ENTRY_POINT_OFFSET(x) if (offset == ENTRYPOINT_OFFSET(x)) { os << # x; } else
152728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(card_table_)
152828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(exception_)
152928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(jni_env_)
153028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(self_)
153128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(stack_end_)
15323d71d0799748aac23ce5935d61b909bec6e96461Elliott Hughes  DO_THREAD_OFFSET(state_)
153328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(suspend_count_)
153428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(thin_lock_id_)
153528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(top_of_managed_stack_)
153628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(top_of_managed_stack_pc_)
153728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_OFFSET(top_sirt_)
153828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pAllocArrayFromCode)
153928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pAllocArrayFromCodeWithAccessCheck)
154028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pAllocObjectFromCode)
154128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pAllocObjectFromCodeWithAccessCheck)
154228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCheckAndAllocArrayFromCode)
154328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCheckAndAllocArrayFromCodeWithAccessCheck)
154428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInstanceofNonTrivialFromCode)
154528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCanPutArrayElementFromCode)
154628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCheckCastFromCode)
154728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDebugMe)
154828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pUpdateDebuggerFromCode)
154928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInitializeStaticStorage)
155028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInitializeTypeAndVerifyAccessFromCode)
155128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInitializeTypeFromCode)
155228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pResolveStringFromCode)
155328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pSet32Instance)
155428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pSet32Static)
155528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pSet64Instance)
155628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pSet64Static)
155728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pSetObjInstance)
155828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pSetObjStatic)
155928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pGet32Instance)
156028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pGet32Static)
156128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pGet64Instance)
156228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pGet64Static)
156328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pGetObjInstance)
156428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pGetObjStatic)
156528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pHandleFillArrayDataFromCode)
156628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDecodeJObjectInThread)
156728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFindNativeMethod)
156828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pLockObjectFromCode)
156928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pUnlockObjectFromCode)
157028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCmpgDouble)
157128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCmpgFloat)
157228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCmplDouble)
157328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCmplFloat)
157428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDadd)
157528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDdiv)
157628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDmul)
157728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDsub)
157828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pF2d)
157928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFmod)
158028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pI2d)
158128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pL2d)
158228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pD2f)
158328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFadd)
158428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFdiv)
158528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFmodf)
158628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFmul)
158728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFsub)
158828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pI2f)
158928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pL2f)
159028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pD2iz)
159128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pF2iz)
159228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pIdiv)
159328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pIdivmod)
159428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pD2l)
159528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pF2l)
159628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pLdiv)
159728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pLdivmod)
159828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pLmul)
159928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pShlLong)
160028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pShrLong)
160128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pUshrLong)
160228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pIndexOf)
160328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pMemcmp16)
160428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pStringCompareTo)
160528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pMemcpy)
160628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pFindInterfaceMethodInCache)
160728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pUnresolvedDirectMethodTrampolineFromCode)
160828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInvokeDirectTrampolineWithAccessCheck)
160928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInvokeInterfaceTrampoline)
161028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInvokeInterfaceTrampolineWithAccessCheck)
161128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInvokeStaticTrampolineWithAccessCheck)
161228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInvokeSuperTrampolineWithAccessCheck)
161328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pInvokeVirtualTrampolineWithAccessCheck)
161428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pCheckSuspendFromCode)
161528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pTestSuspendFromCode)
161628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pDeliverException)
161728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowAbstractMethodErrorFromCode)
161828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowArrayBoundsFromCode)
161928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowDivZeroFromCode)
162028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowNoSuchMethodFromCode)
162128fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowNullPointerFromCode)
162228fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowStackOverflowFromCode)
162328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  DO_THREAD_ENTRY_POINT_OFFSET(pThrowVerificationErrorFromCode)
162428fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  {
162528fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes    os << offset;
162628fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  }
162728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes#undef DO_THREAD_OFFSET
162828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes#undef DO_THREAD_ENTRY_POINT_OFFSET
162928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes}
163028fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes
1631bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogersclass CatchBlockStackVisitor : public Thread::StackVisitor {
1632bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers public:
1633bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor(Class* to_find, Context* ljc)
163457b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0),
163557b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
163667375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#ifndef NDEBUG
163767375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_pc_ = 0xEBADC0DE;
163867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
163967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#endif
164067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  }
1641bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1642530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& fr, uintptr_t pc) {
1643530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    Method* method = fr.GetMethod();
1644530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (method == NULL) {
1645530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // This is the upcall, we remember the frame and last_pc so that we may
1646530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // long jump to them
1647530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      handler_pc_ = DemanglePc(pc);
1648530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      handler_frame_ = fr;
164957b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      return false;  // End stack walk.
1650530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
1651530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    uint32_t dex_pc = DexFile::kDexNoIndex;
165257b86d47b66322693a070185fadfb43cb9c12eabIan Rogers    if (method->IsRuntimeMethod()) {
1653530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // ignore callee save method
165457b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      DCHECK(method->IsCalleeSaveMethod());
1655530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    } else if (method->IsNative()) {
1656530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      native_method_count_++;
1657530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    } else {
16580791adc2249366c50684935a4c42ba5e58bc3746jeffhao      // Unwind stack when an exception occurs during method tracing
165957b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      if (UNLIKELY(method_tracing_active_)) {
1660776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
166157b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        if (IsTraceExitPc(DemanglePc(pc))) {
1662530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes          pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1663530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        }
1664776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#else
1665776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers        UNIMPLEMENTED(FATAL);
1666776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
1667bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1668530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      dex_pc = method->ToDexPC(pc);
1669530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
1670530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (dex_pc != DexFile::kDexNoIndex) {
1671530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1672530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (found_dex_pc != DexFile::kDexNoIndex) {
1673530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        handler_pc_ = method->ToNativePC(found_dex_pc);
1674530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        handler_frame_ = fr;
167557b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        return false;  // End stack walk.
1676bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
16771a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao    }
1678776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
1679530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    // Caller may be handler, fill in callee saves in context
1680530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    long_jump_context_->FillCalleeSaves(fr);
1681776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
168257b86d47b66322693a070185fadfb43cb9c12eabIan Rogers    return true;  // Continue stack walk.
16831a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
16841a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1685bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // The type of the exception catch block to find
1686bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Class* to_find_;
1687bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Frame with found handler or last frame if no handler found
1688bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Frame handler_frame_;
168967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // PC to branch to for the handler
169067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uintptr_t handler_pc_;
1691bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Context that will be the target of the long jump
1692bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context_;
169367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // Number of native methods passed in crawl (equates to number of SIRTs to pop)
169467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uint32_t native_method_count_;
169557b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  // Is method tracing active?
169657b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  const bool method_tracing_active_;
1697bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers};
1698bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1699ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogersvoid Thread::DeliverException() {
1700776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
170128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  const bool kDebugExceptionDelivery = false;
1702d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Throwable* exception = GetException();  // Get exception from thread
1703ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  CHECK(exception != NULL);
170428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  // Don't leave exception visible while we try to find the handler, which may cause class
1705d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  // resolution.
170628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  ClearException();
170728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1708a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    String* msg = exception->GetDetailMessage();
1709a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1710a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1711a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers                        << ": " << str_msg << std::endl);
171228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
1713bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1714bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context = GetLongJumpContext();
1715bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
1716530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  WalkStack(&catch_finder, true);
1717bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1718d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method** sp;
1719d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  uintptr_t throw_native_pc;
1720d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1721d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  uintptr_t catch_native_pc = catch_finder.handler_pc_;
1722d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* catch_method = catch_finder.handler_frame_.GetMethod();
1723d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1724d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes
172528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1726d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes    if (catch_method == NULL) {
172728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      LOG(INFO) << "Handler is upcall";
172828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    } else {
172928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
173028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      const DexFile& dex_file =
1731d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes          class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1732d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes      int line_number = dex_file.GetLineNumFromPC(catch_method,
1733d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes          catch_method->ToDexPC(catch_finder.handler_pc_));
1734d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes      LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
173528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    }
173628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
173728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  SetException(exception);
17389a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  CHECK_NE(catch_native_pc, 0u);
1739d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
17409a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  long_jump_context->SetPC(catch_native_pc);
17419c750f9b6283f62b3e6a93c0c6b2838abde5000eElliott Hughes  long_jump_context->SmashCallerSaves();
1742bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  long_jump_context->DoLongJump();
1743776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
17449a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  LOG(FATAL) << "UNREACHABLE";
1745bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1746bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1747bdb0391258abc54bf77c676e36847d28a783bfe5Ian RogersContext* Thread::GetLongJumpContext() {
174885d1545e985ac689db4bad7849880e843707c862Elliott Hughes  Context* result = long_jump_context_;
1749776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
1750bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (result == NULL) {
1751bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    result = Context::Create();
175285d1545e985ac689db4bad7849880e843707c862Elliott Hughes    long_jump_context_ = result;
17531a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
1754776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
1755bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  return result;
17561a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao}
17571a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1758ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#if !defined(ART_USE_LLVM_COMPILER)
1759d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott HughesMethod* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1760d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Frame f = top_of_managed_stack_;
1761d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* m = f.GetMethod();
17628be2d40d42223b515de12629216151a558895969Elliott Hughes  uintptr_t native_pc = top_of_managed_stack_pc_;
17638be2d40d42223b515de12629216151a558895969Elliott Hughes
17649fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // We use JNI internally for exception throwing, so it's possible to arrive
17659fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // here via a "FromCode" function, in which case there's a synthetic
17669fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // callee-save method at the top of the stack. These shouldn't be user-visible,
17679fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // so if we find one, skip it and return the compiled method underneath.
176833dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  if (m != NULL && m->IsCalleeSaveMethod()) {
17698be2d40d42223b515de12629216151a558895969Elliott Hughes    native_pc = f.GetReturnPC();
17709fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    f.Next();
17719fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    m = f.GetMethod();
17729fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  }
1773d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  if (pc != NULL) {
17748be2d40d42223b515de12629216151a558895969Elliott Hughes    *pc = (m != NULL) ? ManglePc(native_pc) : 0;
177533dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  }
1776d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  if (sp != NULL) {
1777d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes    *sp = f.GetSP();
1778d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  }
1779d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  return m;
178033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao}
1781ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#else
1782ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYaMethod* Thread::GetCurrentMethod(uintptr_t*, Method***) const {
1783ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa  ShadowFrame* frame = top_shadow_frame_;
178420efe54063f2740d16f01190b280cdba384c869bTDYa  if (frame == NULL) {
178520efe54063f2740d16f01190b280cdba384c869bTDYa    return NULL;
1786ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa  }
1787ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa  return frame->GetMethod();
1788ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa}
1789ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa#endif
179033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
17915f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesbool Thread::HoldsLock(Object* object) {
17925f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (object == NULL) {
17935f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
17945f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
179524a3c2e9924e8765c4a9b4d383cb8f3b922f9c9fBrian Carlstrom  return object->GetThinLockId() == thin_lock_id_;
17965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
17975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1798038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesbool Thread::IsDaemon() {
1799038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  return gThread_daemon->GetBoolean(peer_);
1800038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
1801038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
1802776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
1803d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersclass ReferenceMapVisitor : public Thread::StackVisitor {
1804d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers public:
1805d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1806d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_(context), root_visitor_(root_visitor), arg_(arg) {
1807d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1808d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1809530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
1810d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    Method* m = frame.GetMethod();
18116a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    if (false) {
1812250455229aa0cc07bbd18174efe510bd52631a99jeffhao      LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m)
18130dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom                << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
18146a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    }
1815d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    // Process register map (which native and callee save methods don't have)
18163891c775503b1113a918180d9ecdaa79e92c69c6Ian Rogers    if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
1817e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1818e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1819e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
1820d81871cbbaa34c649e488f94f61a981db33123e5Ian Rogers      const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
1821d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      CHECK(reg_bitmap != NULL);
182268fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes      const VmapTable vmap_table(m->GetVmapTableRaw());
182311d1b0c31ddd710d26068da8e0e4621002205b4bElliott Hughes      const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
18246d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      DCHECK(code_item != NULL);  // can't be NULL or how would we compile its instructions?
18256d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      uint32_t core_spills = m->GetCoreSpillMask();
18266d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      uint32_t fp_spills = m->GetFpSpillMask();
18276d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      size_t frame_size = m->GetFrameSizeInBytes();
18280dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom      // For all dex registers in the bitmap
18296d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      size_t num_regs = std::min(map.RegWidth() * 8,
18306d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                 static_cast<size_t>(code_item->registers_size_));
18310dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom      for (size_t reg = 0; reg < num_regs; ++reg) {
1832d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        // Does this register hold a reference?
1833d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        if (TestBitmap(reg, reg_bitmap)) {
183468fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes          uint32_t vmap_offset;
1835d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          Object* ref;
183668fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes          if (vmap_table.IsInContext(reg, vmap_offset)) {
1837d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            // Compute the register we need to load from the context
1838d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            uint32_t spill_mask = m->GetCoreSpillMask();
18390dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom            CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1840f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t matches = 0;
1841f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t spill_shifts = 0;
1842f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            while (matches != (vmap_offset + 1)) {
18430dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom              DCHECK_NE(spill_mask, 0u);
1844f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              matches += spill_mask & 1;  // Add 1 if the low bit is set
1845f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_mask >>= 1;
1846f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_shifts++;
1847d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            }
1848f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            spill_shifts--;  // wind back one as we want the last match
1849f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
1850d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          } else {
18516d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers            ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
18526d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                          frame_size, reg));
1853d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          }
18544f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          if (ref != NULL) {
18554f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao            root_visitor_(ref, arg_);
18564f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          }
1857d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        }
1858d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      }
1859d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    }
1860d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_->FillCalleeSaves(frame);
1861530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
1862d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1863d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1864d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers private:
1865d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  bool TestBitmap(int reg, const uint8_t* reg_vector) {
1866d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1867d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1868d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1869d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Context used to build up picture of callee saves
1870d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context_;
1871d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Call-back when we visit a root
1872d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Heap::RootVisitor* root_visitor_;
1873d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Argument to call-back
1874d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void* arg_;
1875d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers};
1876776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
1877d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1878d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersvoid Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
1879d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (exception_ != NULL) {
1880d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(exception_, arg);
1881d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1882d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
1883d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(peer_, arg);
1884d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1885726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (pre_allocated_OutOfMemoryError_ != NULL) {
1886726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    visitor(pre_allocated_OutOfMemoryError_, arg);
1887726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  }
188840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  if (class_loader_override_ != NULL) {
188940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    visitor(class_loader_override_, arg);
189040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  }
1891410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->locals.VisitRoots(visitor, arg);
1892410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->monitors.VisitRoots(visitor, arg);
18938dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
18948dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  SirtVisitRoots(visitor, arg);
1895f7ad17e108b9357d7c94c6218a8521140a667f3dLogan Chien  ShadowFrameVisitRoots(visitor, arg);
18968dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1897540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#if !defined(ART_USE_LLVM_COMPILER)
1898d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1899d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // delivery.
1900d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context = GetLongJumpContext();
1901d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Visit roots on this thread's stack
1902d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor mapper(context, visitor, arg);
1903d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  WalkStack(&mapper);
1904540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#endif
1905410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes}
1906410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes
1907250455229aa0cc07bbd18174efe510bd52631a99jeffhao#if VERIFY_OBJECT_ENABLED
1908ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic void VerifyObject(const Object* obj, void*) {
1909250455229aa0cc07bbd18174efe510bd52631a99jeffhao  Runtime::Current()->GetHeap()->VerifyObject(obj);
1910250455229aa0cc07bbd18174efe510bd52631a99jeffhao}
1911250455229aa0cc07bbd18174efe510bd52631a99jeffhao
1912250455229aa0cc07bbd18174efe510bd52631a99jeffhaovoid Thread::VerifyStack() {
1913540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#if !defined(ART_USE_LLVM_COMPILER)
1914e66ac79b90a12b01b9d67ee9f7f586e638e67fabjeffhao  UniquePtr<Context> context(Context::Create());
1915e66ac79b90a12b01b9d67ee9f7f586e638e67fabjeffhao  ReferenceMapVisitor mapper(context.get(), VerifyObject, NULL);
1916250455229aa0cc07bbd18174efe510bd52631a99jeffhao  WalkStack(&mapper);
1917540a5b768bf5f76bd71ebf66612fb2298899480fTDYa#endif
1918250455229aa0cc07bbd18174efe510bd52631a99jeffhao}
1919250455229aa0cc07bbd18174efe510bd52631a99jeffhao#endif
1920250455229aa0cc07bbd18174efe510bd52631a99jeffhao
1921330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughesstd::ostream& operator<<(std::ostream& os, const Thread& thread) {
1922899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  thread.Dump(os, false);
1923330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes  return os;
1924330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes}
1925330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes
1926a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
192717057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes  if (this == NULL) {
192817057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes    CHECK(Runtime::Current()->IsShuttingDown());
192917057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes    return;
193017057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes  }
1931ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  if (is_locking) {
1932ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    if (held_mutexes_[rank] == 0) {
1933ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      bool bad_mutexes_held = false;
1934ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      for (int i = kMaxMutexRank; i > rank; --i) {
1935ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        if (held_mutexes_[i] != 0) {
1936ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1937ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          bad_mutexes_held = true;
1938ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        }
1939ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      }
1940b5db3bb5b17f2bb42f3c62408938f4bf939f8a39Elliott Hughes      CHECK(!bad_mutexes_held) << rank;
1941ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    }
1942ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    ++held_mutexes_[rank];
1943ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  } else {
1944b5db3bb5b17f2bb42f3c62408938f4bf939f8a39Elliott Hughes    CHECK_GT(held_mutexes_[rank], 0U) << rank;
1945ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    --held_mutexes_[rank];
1946ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
1947ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
1948ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes
1949a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::CheckSafeToWait(MutexRank rank) {
195017057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes  if (this == NULL) {
195117057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes    CHECK(Runtime::Current()->IsShuttingDown());
195217057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes    return;
195317057b15cb8d8da97b2bc28fd38bdcc7a34e846eElliott Hughes  }
1954a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  bool bad_mutexes_held = false;
1955a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  for (int i = kMaxMutexRank; i >= 0; --i) {
1956a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    if (i != rank && held_mutexes_[i] != 0) {
1957a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes      LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1958a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes      bad_mutexes_held = true;
1959a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    }
1960a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  }
1961a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  if (held_mutexes_[rank] == 0) {
1962a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1963a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    bad_mutexes_held = true;
1964a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  }
1965a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  CHECK(!bad_mutexes_held);
1966a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes}
1967a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
19688daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes}  // namespace art
1969