thread.cc revision 1f5393447b9f45be7918042d9ee7b521376de866
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>
212acf36d8cfeb5ddb293904148aa70f25ef6d8845Elliott Hughes#include <signal.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
31a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "class_linker.h"
32df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom#include "class_loader.h"
33474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers#include "cutils/atomic.h"
34474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers#include "cutils/atomic-inline.h"
3546e251bf7200cc06f5a9a82ee2030e650f5e1443Elliott Hughes#include "debugger.h"
360c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers#include "gc_map.h"
37408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers#include "heap.h"
38c5f7c91ab89055cffb573fff7e06dbdd860bccedElliott Hughes#include "jni_internal.h"
398e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes#include "monitor.h"
4081d425b0b232962441616f8b14f73620bffef5e5Ian Rogers#include "mutex.h"
4157b86d47b66322693a070185fadfb43cb9c12eabIan Rogers#include "oat/runtime/context.h"
42a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "object.h"
436d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers#include "object_utils.h"
449a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson#include "reflection.h"
45578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "runtime.h"
465433072f589b61413e042eddf76e8190a048f71dbuzbee#include "runtime_support.h"
4700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers#include "scoped_thread_state_change.h"
4846e251bf7200cc06f5a9a82ee2030e650f5e1443Elliott Hughes#include "ScopedLocalRef.h"
491f5393447b9f45be7918042d9ee7b521376de866Ian Rogers#include "sirt_ref.h"
5030fab40ee5a07af6b8c3b6b0e9438071695a57f4Ian Rogers#include "space.h"
5168e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack.h"
5268e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack_indirect_reference_table.h"
538daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes#include "thread_list.h"
54a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include "utils.h"
55eac766769e3114a078c188ea26776a81f0edb3cfElliott Hughes#include "well_known_classes.h"
56b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
57b557353b22c728eecbd1c68593b482622c7782a8Carl Shapironamespace art {
58b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
59b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiropthread_key_t Thread::pthread_key_self_;
6000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan RogersConditionVariable* Thread::resume_cond_;
61b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
627dc5166ea740359d381097a7ab382c1dd404055fElliott Hughesstatic const char* kThreadNameDuringStartup = "<native thread without managed peer>";
637dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes
645d76c435082332ef79a22962386fa92a0870e378Ian Rogersvoid Thread::InitCardTable() {
65b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes  card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
665d76c435082332ef79a22962386fa92a0870e378Ian Rogers}
675d76c435082332ef79a22962386fa92a0870e378Ian Rogers
6899250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#if !defined(__APPLE__)
693ea0f42467790809fcfc9fc861605d465808090fElliott Hughesstatic void UnimplementedEntryPoint() {
703ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  UNIMPLEMENTED(FATAL);
713ea0f42467790809fcfc9fc861605d465808090fElliott Hughes}
7299250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#endif
733ea0f42467790809fcfc9fc861605d465808090fElliott Hughes
743ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbeevoid Thread::InitFunctionPointers() {
7599250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
763ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
773ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
783ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
793ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  for (uintptr_t* it = begin; it != end; ++it) {
803ea0f42467790809fcfc9fc861605d465808090fElliott Hughes    *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
813ea0f42467790809fcfc9fc861605d465808090fElliott Hughes  }
8299250ba6a2cc72b8894dffa77c1fca5570087e3cElliott Hughes#endif
8357b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  InitEntryPoints(&entrypoints_);
84c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes}
85c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes
86c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughesvoid Thread::SetDebuggerUpdatesEnabled(bool enabled) {
87c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes  LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
88776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
8957b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  ChangeDebuggerEntryPoint(&entrypoints_, enabled);
90776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#else
91776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers  UNIMPLEMENTED(FATAL);
92776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
933ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee}
943ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee
95caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitTid() {
96caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  tid_ = ::art::GetTid();
97caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
98caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
99caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitAfterFork() {
1008029cbe626a467b344ff84d86170d757aa12ecd4Elliott Hughes  // One thread (us) survived the fork, but we have a new tid so we need to
1018029cbe626a467b344ff84d86170d757aa12ecd4Elliott Hughes  // update the value stashed in this Thread*.
102caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
103caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
104caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
10578128a63b2615744760b7f8ab83df9764a5d4a95Brian Carlstromvoid* Thread::CreateCallback(void* arg) {
10693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
107120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Runtime* runtime = Runtime::Current();
108120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (runtime == NULL) {
109120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
110120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    return NULL;
111120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  }
112120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  {
113120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    MutexLock mu(*Locks::runtime_shutdown_lock_);
114120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    // Check that if we got here we cannot be shutting down (as shutdown should never have started
115120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    // while threads are being born).
116120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    CHECK(!runtime->IsShuttingDown());
117120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
118120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    Runtime::Current()->EndThreadBirth();
119120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  }
12047179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  {
12100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    ScopedObjectAccess soa(self);
122365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    {
1231f5393447b9f45be7918042d9ee7b521376de866Ian Rogers      SirtRef<String> thread_name(self, self->GetThreadName(soa));
124365c10235438607541fa2259a5fec48061b90bd8Ian Rogers      self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
125365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    }
126365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    Dbg::PostThreadStart(self);
12793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
128365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    // Invoke the 'run' method of our java.lang.Thread.
129365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    CHECK(self->peer_ != NULL);
130dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    Object* receiver = soa.Decode<Object*>(self->peer_);
131365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    jmethodID mid = WellKnownClasses::java_lang_Thread_run;
13266f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
133365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    m->Invoke(self, receiver, NULL, NULL);
134365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  }
13500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Detach and delete self.
13600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Runtime::Current()->GetThreadList()->Unregister(self);
13793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
138b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  return NULL;
139b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
140b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
14100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan RogersThread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, Object* thread_peer) {
14200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
14300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetInt(thread_peer)));
14400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
14500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // to stop it from going away.
14681d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  if (kIsDebugBuild) {
14781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
14881d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    if (result != NULL && !result->IsSuspended()) {
14981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      Locks::thread_list_lock_->AssertHeld(soa.Self());
15081d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    }
15100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
15200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  return result;
153761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes}
154761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes
15500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan RogersThread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
15600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  return FromManagedThread(soa, soa.Decode<Object*>(java_thread));
15701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes}
15801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
159ab7b9dcbfc4264a0bc4889c3e463ff88a67f6a30Elliott Hughesstatic size_t FixStackSize(size_t stack_size) {
1607502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // A stack size of zero means "use the default".
161d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (stack_size == 0) {
162d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    stack_size = Runtime::Current()->GetDefaultStackSize();
163d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
16461e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
1656414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom  // Dalvik used the bionic pthread default stack size for native threads,
1666414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom  // so include that here to support apps that expect large native stacks.
1676414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom  stack_size += 1 * MB;
1686414a97a3c6dc101ae8ebc9480114d0c327e8e8dBrian Carlstrom
1697502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
1707502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  if (stack_size < PTHREAD_STACK_MIN) {
1717502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes    stack_size = PTHREAD_STACK_MIN;
1727502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  }
1737502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
1747502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's likely that callers are trying to ensure they have at least a certain amount of
1757502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // stack space, so we should add our reserved space on top of what they requested, rather
1767502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // than implicitly take it away from them.
1777502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size += Thread::kStackOverflowReservedBytes;
1787502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
1797502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // Some systems require the stack size to be a multiple of the system page size, so round up.
1807502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = RoundUp(stack_size, kPageSize);
1817502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
1827502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  return stack_size;
1837502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes}
1847502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
185d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughesstatic void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
186d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  if (sigaltstack(new_stack, old_stack) == -1) {
187d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes    PLOG(FATAL) << "sigaltstack failed";
188d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  }
189d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes}
190d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
191d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughesstatic void SetUpAlternateSignalStack() {
192d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Create and set an alternate signal stack.
193d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  stack_t ss;
194d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_sp = new uint8_t[SIGSTKSZ];
195d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_size = SIGSTKSZ;
196d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_flags = 0;
197d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  CHECK(ss.ss_sp != NULL);
198d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(&ss, NULL);
199d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
200d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Double-check that it worked.
201d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_sp = NULL;
202d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(NULL, &ss);
203d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
204d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes}
205d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
206d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughesstatic void TearDownAlternateSignalStack() {
207d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Get the pointer so we can free the memory.
208d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  stack_t ss;
209d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(NULL, &ss);
210d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
211d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
212d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Tell the kernel to stop using it.
213d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_sp = NULL;
214d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  ss.ss_flags = SS_DISABLE;
2154c5231d2cd83536584f7f1063d0afffa124fcec4Elliott Hughes  ss.ss_size = SIGSTKSZ; // Avoid ENOMEM failure with Mac OS' buggy libc.
216d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SigAltStack(&ss, NULL);
217d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
218d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  // Free it.
219d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  delete[] allocated_signal_stack;
220d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes}
221d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
222120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogersvoid Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
223dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  CHECK(java_peer != NULL);
224120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Thread* self = static_cast<JNIEnvExt*>(env)->self;
225120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Runtime* runtime = Runtime::Current();
226dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier
227120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
228120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  bool thread_start_during_shutdown = false;
229365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  {
230120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    MutexLock mu(self, *Locks::runtime_shutdown_lock_);
231120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    if (runtime->IsShuttingDown()) {
232120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      thread_start_during_shutdown = true;
233120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    } else {
234120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      runtime->StartThreadBirth();
235120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    }
23600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
237120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (thread_start_during_shutdown) {
238120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
239120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
240120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    return;
241120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  }
242120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers
243120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Thread* child_thread = new Thread(is_daemon);
244120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // Use global JNI ref to hold peer live while child thread starts.
245120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  child_thread->peer_ = env->NewGlobalRef(java_peer);
246120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  stack_size = FixStackSize(stack_size);
247120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers
248120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // Thread.start is synchronized, so we know that vmData is 0, and know that we're not racing to
249120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // assign it.
250120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  env->SetIntField(java_peer, WellKnownClasses::java_lang_Thread_vmData,
251120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                   reinterpret_cast<jint>(child_thread));
25200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
25300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  pthread_t new_pthread;
25400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  pthread_attr_t attr;
25500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
25600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
25700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
258120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, child_thread);
25900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
26000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
261120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (pthread_create_result != 0) {
26200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // pthread_create(3) failed, so clean up.
2639efc3e03982f042c3ce67cc2c64dbe0f0986119bBrian Carlstrom    {
264120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      MutexLock mu(self, *Locks::runtime_shutdown_lock_);
265120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      runtime->EndThreadBirth();
266120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    }
267120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    // Manually delete the global reference since Thread::Init will not have been run.
268120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    env->DeleteGlobalRef(child_thread->peer_);
269120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    child_thread->peer_ = NULL;
270120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    delete child_thread;
271120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    child_thread = NULL;
272120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    // TODO: remove from thread group?
273120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    env->SetIntField(java_peer, WellKnownClasses::java_lang_Thread_vmData, 0);
274120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    {
2759efc3e03982f042c3ce67cc2c64dbe0f0986119bBrian Carlstrom      std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
2769efc3e03982f042c3ce67cc2c64dbe0f0986119bBrian Carlstrom                                   PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
277120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      ScopedObjectAccess soa(env);
278120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      soa.Self()->ThrowOutOfMemoryError(msg.c_str());
2799efc3e03982f042c3ce67cc2c64dbe0f0986119bBrian Carlstrom    }
280365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  }
28193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
28261e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
283120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogersvoid Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm) {
284462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // This function does all the initialization that must be run by the native thread it applies to.
285462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
286462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // we can handshake with the corresponding native thread when it's ready.) Check this native
287462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  // thread hasn't been through here already...
288cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  CHECK(Thread::Current() == NULL);
289cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes
290d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  SetUpAlternateSignalStack();
29193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitCpu();
29293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitFunctionPointers();
29321d28f510eb590f52810c83f1f3f37fe5f4adf46Shih-wei Liao#ifdef ART_USE_GREENLAND_COMPILER
29421d28f510eb590f52810c83f1f3f37fe5f4adf46Shih-wei Liao  InitRuntimeEntryPoints(&runtime_entry_points_);
29521d28f510eb590f52810c83f1f3f37fe5f4adf46Shih-wei Liao#endif
2965d76c435082332ef79a22962386fa92a0870e378Ian Rogers  InitCardTable();
29701ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  InitTid();
29861e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
299120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
300120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
3010d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes  pthread_self_ = pthread_self();
3026a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes  CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
303120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  DCHECK_EQ(Thread::Current(), this);
304a5780dad67556297c8ca5f2608c53b193e6c4514Elliott Hughes
305120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  thin_lock_id_ = thread_list->AllocThreadId();
306120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  InitStackHwm();
3075fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
308120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  jni_env_ = new JNIEnvExt(this, java_vm);
309120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  thread_list->Register(this);
31093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
31193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
312365c10235438607541fa2259a5fec48061b90bd8Ian RogersThread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group) {
313120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Thread* self;
314120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Runtime* runtime = Runtime::Current();
315120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (runtime == NULL) {
316120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
317120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    return NULL;
318120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  }
319120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  {
320120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    MutexLock mu(NULL, *Locks::runtime_shutdown_lock_);
321120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    if (runtime->IsShuttingDown()) {
322120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
323120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      return NULL;
324120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    } else {
325120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      Runtime::Current()->StartThreadBirth();
326120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      self = new Thread(as_daemon);
327120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
328120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      Runtime::Current()->EndThreadBirth();
329120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    }
330120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  }
3315fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
332dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  CHECK_NE(self->GetState(), kRunnable);
333dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  self->SetState(kNative);
334726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
335cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  // If we're the main thread, ClassLinker won't be created until after we're attached,
336cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  // so that thread needs a two-stage attach. Regular threads don't need this hack.
337d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  // In the compiler, all threads need this hack, because no-one's going to be getting
338d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  // a native peer!
339d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
340462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes    self->CreatePeer(thread_name, as_daemon, thread_group);
34106e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  } else {
34206e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
34322869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes    if (thread_name != NULL) {
34422869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes      self->name_->assign(thread_name);
34522869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes      ::art::SetThreadName(thread_name);
34622869a9026a08b544eca4cefd67386d347e30d2cElliott Hughes    }
34736e0a955e48e9357bff1eab783e493107ebfff62Ian Rogers  }
348cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes
3495fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  return self;
3505fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes}
3515fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
352365c10235438607541fa2259a5fec48061b90bd8Ian Rogersvoid Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
353365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  Runtime* runtime = Runtime::Current();
354365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  CHECK(runtime->IsStarted());
3555fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  JNIEnv* env = jni_env_;
3565fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
357462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  if (thread_group == NULL) {
358365c10235438607541fa2259a5fec48061b90bd8Ian Rogers    thread_group = runtime->GetMainThreadGroup();
359462c94449720e0dc6b93d7138d835d345ccf67aeElliott Hughes  }
360726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
3618daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes  jint thread_priority = GetNativePriority();
3625fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  jboolean thread_is_daemon = as_daemon;
3635fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
364eac766769e3114a078c188ea26776a81f0edb3cfElliott Hughes  ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
365dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  if (peer.get() == NULL) {
366dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    CHECK(IsExceptionPending());
367dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    return;
3685d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  }
369dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  peer_ = env->NewGlobalRef(peer.get());
370eac766769e3114a078c188ea26776a81f0edb3cfElliott Hughes  env->CallNonvirtualVoidMethod(peer.get(),
371eac766769e3114a078c188ea26776a81f0edb3cfElliott Hughes                                WellKnownClasses::java_lang_Thread,
372eac766769e3114a078c188ea26776a81f0edb3cfElliott Hughes                                WellKnownClasses::java_lang_Thread_init,
373365c10235438607541fa2259a5fec48061b90bd8Ian Rogers                                thread_group, thread_name.get(), thread_priority, thread_is_daemon);
37400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  AssertNoPendingException();
375d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
376120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Thread* self = this;
377120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  DCHECK_EQ(self, Thread::Current());
378120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  jni_env_->SetIntField(peer.get(), WellKnownClasses::java_lang_Thread_vmData,
379120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                        reinterpret_cast<jint>(self));
380120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers
381120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  ScopedObjectAccess soa(self);
3821f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  SirtRef<String> peer_thread_name(soa.Self(), GetThreadName(soa));
38300fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  if (peer_thread_name.get() == NULL) {
384120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    Object* native_peer = soa.Decode<Object*>(peer.get());
38500fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // The Thread constructor should have set the Thread.name to a
38600fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // non-null value. However, because we can run without code
38700fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // available (in the compiler, in tests), we manually assign the
38800fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // fields the constructor should have set.
389dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
390dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier        SetBoolean(native_peer, thread_is_daemon);
391dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
392dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier        SetObject(native_peer, soa.Decode<Object*>(thread_group));
393dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
394dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier        SetObject(native_peer, soa.Decode<Object*>(thread_name.get()));
395dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
396dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier        SetInt(native_peer, thread_priority);
39700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    peer_thread_name.reset(GetThreadName(soa));
39800fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  }
399225f5a1df25241babd16cdba54056b9e2cd166a2Elliott Hughes  // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
40000fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  if (peer_thread_name.get() != NULL) {
401899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
40200fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  }
40361e019d291583029c01b61b93bea750f2b663c37Carl Shapiro}
40461e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
405899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughesvoid Thread::SetThreadName(const char* name) {
406899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  name_->assign(name);
407899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  ::art::SetThreadName(name);
408899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
409899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes}
410899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes
411be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::InitStackHwm() {
412e188419b971936086a188843378375f5ced13724Elliott Hughes  void* stack_base;
413e188419b971936086a188843378375f5ced13724Elliott Hughes  size_t stack_size;
414120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  GetThreadStack(pthread_self_, stack_base, stack_size);
41536ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes
41636ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes  // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
417e188419b971936086a188843378375f5ced13724Elliott Hughes  VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
418e188419b971936086a188843378375f5ced13724Elliott Hughes
419e188419b971936086a188843378375f5ced13724Elliott Hughes  stack_begin_ = reinterpret_cast<byte*>(stack_base);
420e188419b971936086a188843378375f5ced13724Elliott Hughes  stack_size_ = stack_size;
42136ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes
422932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  if (stack_size_ <= kStackOverflowReservedBytes) {
4233d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
424be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  }
425449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
426e188419b971936086a188843378375f5ced13724Elliott Hughes  // TODO: move this into the Linux GetThreadStack implementation.
427e188419b971936086a188843378375f5ced13724Elliott Hughes#if !defined(__APPLE__)
42836ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes  // If we're the main thread, check whether we were run with an unlimited stack. In that case,
42936ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes  // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
43036ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes  // will be broken because we'll die long before we get close to 2GB.
431120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  bool is_main_thread = (::art::GetTid() == getpid());
432120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (is_main_thread) {
43336ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes    rlimit stack_limit;
43436ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes    if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
43536ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
43636ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes    }
43736ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes    if (stack_limit.rlim_cur == RLIM_INFINITY) {
43836ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      // Find the default stack size for new threads...
43936ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      pthread_attr_t default_attributes;
44036ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      size_t default_stack_size;
44136ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
44236ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
44336ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes                         "default stack size query");
44436ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
44536ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes
44636ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      // ...and use that as our limit.
44736ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      size_t old_stack_size = stack_size_;
44836ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      stack_size_ = default_stack_size;
44936ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes      stack_begin_ += (old_stack_size - stack_size_);
450faf4ba01738400f418b45c4323aa9e8e6b6ba2a0Elliott Hughes      VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
451faf4ba01738400f418b45c4323aa9e8e6b6ba2a0Elliott Hughes                    << " to " << PrettySize(stack_size_)
452faf4ba01738400f418b45c4323aa9e8e6b6ba2a0Elliott Hughes                    << " with base " << reinterpret_cast<void*>(stack_begin_);
45336ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes    }
45436ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes  }
455e188419b971936086a188843378375f5ced13724Elliott Hughes#endif
45636ecb789775eb5bd284ce5dd35d2e31e42354f24Elliott Hughes
457932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  // Set stack_end_ to the bottom of the stack saving space of stack overflows
458932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  ResetDefaultStackEnd();
459449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
460449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  // Sanity check.
461449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  int stack_variable;
462398f64b5805246765b699839b439e18c0dfbf2eeElliott Hughes  CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
463be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes}
464be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
46500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::ShortDump(std::ostream& os) const {
46600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  os << "Thread[";
46700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  if (GetThinLockId() != 0) {
46800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // If we're in kStarting, we won't have a thin lock id or tid yet.
46900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    os << GetThinLockId()
47000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers             << ",tid=" << GetTid() << ',';
471e0918556e7551de638870dcad3f2023f94f85a50Elliott Hughes  }
472474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  os << GetState()
47300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers           << ",Thread*=" << this
47400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers           << ",peer=" << peer_
47500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers           << ",\"" << *name_ << "\""
47600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers           << "]";
477d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes}
478d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
47900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::Dump(std::ostream& os) const {
48000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  DumpState(os);
48100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  DumpStack(os);
48200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
48300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
48400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan RogersString* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
48500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
486dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  Object* native_peer = soa.Decode<Object*>(peer_);
487dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  return (peer_ != NULL) ? reinterpret_cast<String*>(f->GetObject(native_peer)) : NULL;
488fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
489fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
490ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughesvoid Thread::GetThreadName(std::string& name) const {
491ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  name.assign(*name_);
492ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
493ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes
494474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogersvoid Thread::AtomicSetFlag(ThreadFlag flag) {
49530e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  android_atomic_or(flag, &state_and_flags_.as_int);
496474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers}
497474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers
498474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogersvoid Thread::AtomicClearFlag(ThreadFlag flag) {
49930e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  android_atomic_and(-1 ^ flag, &state_and_flags_.as_int);
500474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers}
501474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers
502474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian RogersThreadState Thread::SetState(ThreadState new_state) {
503474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  // Cannot use this code to change into Runnable as changing to Runnable should fail if
504474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  // old_state_and_flags.suspend_request is true.
505474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  DCHECK_NE(new_state, kRunnable);
506474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  DCHECK_EQ(this, Thread::Current());
50730e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  union StateAndFlags old_state_and_flags = state_and_flags_;
50830e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  state_and_flags_.as_struct.state = new_state;
50930e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  return static_cast<ThreadState>(old_state_and_flags.as_struct.state);
510474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers}
511474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers
51201ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers// Attempt to rectify locks so that we dump thread list with required locks before exiting.
51301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogersstatic void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
514120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  LOG(ERROR) << *thread << " suspend count already zero.";
51501ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  Locks::thread_suspend_count_lock_->Unlock(self);
51601ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  if (!Locks::mutator_lock_->IsSharedHeld(self)) {
51701ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    Locks::mutator_lock_->SharedTryLock(self);
51801ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    if (!Locks::mutator_lock_->IsSharedHeld(self)) {
51901ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
52001ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    }
52101ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  }
52201ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
52301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    Locks::thread_list_lock_->TryLock(self);
52401ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
52501ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
52601ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    }
52701ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  }
52801ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  std::ostringstream ss;
52901ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  Runtime::Current()->GetThreadList()->DumpLocked(ss);
530120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  LOG(FATAL) << ss.str();
53101ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers}
53201ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers
53301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogersvoid Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
53400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
53500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      << delta << " " << debug_suspend_count_ << " " << this;
53600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
53701ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  Locks::thread_suspend_count_lock_->AssertHeld(self);
53800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
53901ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  if (UNLIKELY(delta < 0 && suspend_count_ <= 0)) {
54001ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    UnsafeLogFatalForSuspendCount(self, this);
54100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    return;
54200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
54301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers
54400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  suspend_count_ += delta;
54500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  if (for_debugger) {
54600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    debug_suspend_count_ += delta;
54700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
54801ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers
549474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  if (suspend_count_ == 0) {
550474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers    AtomicClearFlag(kSuspendRequest);
551474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  } else {
552474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers    AtomicSetFlag(kSuspendRequest);
553474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  }
55400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
55500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
55600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::FullSuspendCheck() {
55700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  VLOG(threads) << this << " self-suspending";
55800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Make thread appear suspended to other threads, release mutator_lock_.
55900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  TransitionFromRunnableToSuspended(kSuspended);
56000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
56100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  TransitionFromSuspendedToRunnable();
56200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  VLOG(threads) << this << " self-reviving";
56300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
56400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
56500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
56600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  AssertThreadSuspensionIsAllowable();
567474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  DCHECK_NE(new_state, kRunnable);
568474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  DCHECK_EQ(this, Thread::Current());
569c747cffa950b8398cb8844d47e2253214c855750Ian Rogers  // Change to non-runnable state, thereby appearing suspended to the system.
570474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  DCHECK_EQ(GetState(), kRunnable);
57130e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  state_and_flags_.as_struct.state = new_state;
57200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Release share on mutator_lock_.
57381d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  Locks::mutator_lock_->SharedUnlock(this);
57400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
57500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
57600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan RogersThreadState Thread::TransitionFromSuspendedToRunnable() {
57700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  bool done = false;
57801ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  union StateAndFlags old_state_and_flags = state_and_flags_;
57901ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  int16_t old_state = old_state_and_flags.as_struct.state;
58001ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  DCHECK_NE(static_cast<ThreadState>(old_state), kRunnable);
58100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  do {
58281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    Locks::mutator_lock_->AssertNotHeld(this);  // Otherwise we starve GC..
58301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    old_state_and_flags = state_and_flags_;
58401ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
58501ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    if ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
58600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // Wait while our suspend count is non-zero.
58781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      MutexLock mu(this, *Locks::thread_suspend_count_lock_);
58801ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      old_state_and_flags = state_and_flags_;
58901ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
59001ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      while ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
59100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // Re-check when Thread::resume_cond_ is notified.
59281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers        Thread::resume_cond_->Wait(this, *Locks::thread_suspend_count_lock_);
59301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers        old_state_and_flags = state_and_flags_;
59401ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers        DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
59500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
596474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers      DCHECK_EQ(GetSuspendCount(), 0);
59700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
59800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Re-acquire shared mutator_lock_ access.
59981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    Locks::mutator_lock_->SharedLock(this);
600474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers    // Atomically change from suspended to runnable if no suspend request pending.
60101ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    old_state_and_flags = state_and_flags_;
60201ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
60301ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers    if ((old_state_and_flags.as_struct.flags & kSuspendRequest) == 0) {
60401ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      union StateAndFlags new_state_and_flags = old_state_and_flags;
60501ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      new_state_and_flags.as_struct.state = kRunnable;
60601ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers      done = android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
60781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers                                    &state_and_flags_.as_int)
608474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers                                        == 0;
609474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers    }
610474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers    if (!done) {
611474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers      // Failed to transition to Runnable. Release shared mutator_lock_ access and try again.
61281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      Locks::mutator_lock_->SharedUnlock(this);
61300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
61400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  } while (!done);
61501ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers  return static_cast<ThreadState>(old_state);
61600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
61700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
61800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan RogersThread* Thread::SuspendForDebugger(jobject peer, bool request_suspension, bool* timeout) {
61900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
62000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  useconds_t total_delay_us = 0;
62100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  useconds_t delay_us = 0;
62200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  bool did_suspend_request = false;
62300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  *timeout = false;
62400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  while (true) {
62500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    Thread* thread;
62600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    {
62700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      ScopedObjectAccess soa(Thread::Current());
62881d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
62900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      thread = Thread::FromManagedThread(soa, peer);
63000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      if (thread == NULL) {
63100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        LOG(WARNING) << "No such thread for suspend: " << peer;
63200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        return NULL;
63300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
63400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      {
63581d425b0b232962441616f8b14f73620bffef5e5Ian Rogers        MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
63600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        if (request_suspension) {
63701ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers          thread->ModifySuspendCount(soa.Self(), +1, true /* for_debugger */);
63800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          request_suspension = false;
63900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          did_suspend_request = true;
64000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        }
64100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // IsSuspended on the current thread will fail as the current thread is changed into
64200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // Runnable above. As the suspend count is now raised if this is the current thread
64300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
64400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // to just explicitly handle the current thread in the callers to this code.
64500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
64600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
64700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // count, or else we've waited and it has self suspended) or is the current thread, we're
64800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        // done.
64900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        if (thread->IsSuspended()) {
65000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          return thread;
65100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        }
65200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        if (total_delay_us >= kTimeoutUs) {
65300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          LOG(ERROR) << "Thread suspension timed out: " << peer;
65400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          if (did_suspend_request) {
65501ae5808367e641a983e3f8bb82b3e0d364cd03eIan Rogers            thread->ModifySuspendCount(soa.Self(), -1, true /* for_debugger */);
65600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          }
65700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          *timeout = true;
65800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          return NULL;
65900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        }
66000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
66100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // Release locks and come out of runnable state.
66200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
66300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    for (int i = kMaxMutexLevel; i >= 0; --i) {
66481d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      BaseMutex* held_mutex = Thread::Current()->GetHeldMutex(static_cast<LockLevel>(i));
66500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      if (held_mutex != NULL) {
66600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        LOG(FATAL) << "Holding " << held_mutex->GetName()
66700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers            << " while sleeping for thread suspension";
66800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
66900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
67000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    {
67100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      useconds_t new_delay_us = delay_us * 2;
67200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      CHECK_GE(new_delay_us, delay_us);
67300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      if (new_delay_us < 500000) {  // Don't allow sleeping to be more than 0.5s.
67400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        delay_us = new_delay_us;
67500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
67600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
67700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    if (delay_us == 0) {
67800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      sched_yield();
67900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
68000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      delay_us = 500;
68100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    } else {
68200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      usleep(delay_us);
68300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      total_delay_us += delay_us;
68400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
68500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
68600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
68700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
688abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughesvoid Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
689d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::string group_name;
690d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  int priority;
691d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  bool is_daemon = false;
69281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  Thread* self = Thread::Current();
693d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
694abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  if (thread != NULL && thread->peer_ != NULL) {
69581d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    ScopedObjectAccess soa(self);
696dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    Object* native_peer = soa.Decode<Object*>(thread->peer_);
697dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(native_peer);
698dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(native_peer);
699d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
700120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    Object* thread_group =
701120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers        soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(native_peer);
702120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers
703d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    if (thread_group != NULL) {
70400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      Field* group_name_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
705af8d15a3267343dec135cc6df1db740c0a5c7b52Elliott Hughes      String* group_name_string = reinterpret_cast<String*>(group_name_field->GetObject(thread_group));
706d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes      group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
707d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
708d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  } else {
709d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    priority = GetNativePriority();
710dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes  }
711d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
712abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  std::string scheduler_group_name(GetSchedulerGroupName(tid));
7131bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes  if (scheduler_group_name.empty()) {
7141bac54ffa933fbe9b92b62437577f2f4583eff1aElliott Hughes    scheduler_group_name = "default";
715d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
716d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
717abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  if (thread != NULL) {
718abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes    os << '"' << *thread->name_ << '"';
719abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes    if (is_daemon) {
720abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes      os << " daemon";
721abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes    }
72281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
723abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes    os << " prio=" << priority
724abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " tid=" << thread->GetThinLockId()
725abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " " << thread->GetState() << "\n";
726abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  } else {
727289be85116aaf7c48413858b5d0448868b4e61f3Elliott Hughes    os << '"' << ::art::GetThreadName(tid) << '"'
728abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " prio=" << priority
729abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " (not attached)\n";
730abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  }
731abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes
732abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  if (thread != NULL) {
73381d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    MutexLock mu(self, *Locks::thread_suspend_count_lock_);
734abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes    os << "  | group=\"" << group_name << "\""
735abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " sCount=" << thread->suspend_count_
736abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " dsCount=" << thread->debug_suspend_count_
737abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " obj=" << reinterpret_cast<void*>(thread->peer_)
738abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " self=" << reinterpret_cast<const void*>(thread) << "\n";
739d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
7400d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes
741abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  os << "  | sysTid=" << tid
742abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes     << " nice=" << getpriority(PRIO_PROCESS, tid)
7430d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes     << " cgrp=" << scheduler_group_name;
7440d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes  if (thread != NULL) {
7450d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes    int policy;
7460d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes    sched_param sp;
7470d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes    CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
7480d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes    os << " sched=" << policy << "/" << sp.sched_priority
7490d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes       << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
7500d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes  }
7510d39c12238499ca9ccc34d1532c443335e7c1044Elliott Hughes  os << "\n";
752d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
753d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // Grab the scheduler stats for this thread.
754d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string scheduler_stats;
755abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
756d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
757d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  } else {
758d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats = "0 0 0";
759d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
760d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
761ba0b9c55adce3f533845ab1b25c552589e5b4118Elliott Hughes  char native_thread_state = '?';
762d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int utime = 0;
763d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int stime = 0;
764d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int task_cpu = 0;
765ba0b9c55adce3f533845ab1b25c552589e5b4118Elliott Hughes  GetTaskStats(tid, native_thread_state, utime, stime, task_cpu);
766d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
767ba0b9c55adce3f533845ab1b25c552589e5b4118Elliott Hughes  os << "  | state=" << native_thread_state
768ba0b9c55adce3f533845ab1b25c552589e5b4118Elliott Hughes     << " schedstat=( " << scheduler_stats << " )"
769d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " utm=" << utime
770d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " stm=" << stime
771abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes     << " core=" << task_cpu
772abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes     << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
773abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  if (thread != NULL) {
774abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes    os << "  | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
775abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes       << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
776abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  }
777abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes}
778abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes
779abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughesvoid Thread::DumpState(std::ostream& os) const {
780abbe07d095547ded03c2e9d0d53943d43471278dElliott Hughes  Thread::DumpState(os, this, GetTid());
781a09576416788b916095739e43a16917e7948f3a4Elliott Hughes}
782a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
7830399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersstruct StackDumpVisitor : public StackVisitor {
78408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  StackDumpVisitor(std::ostream& os, const Thread* thread, Context* context, bool can_allocate)
785b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
78608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes      : StackVisitor(thread->GetManagedStack(), thread->GetTraceStack(), context),
78708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        os(os), thread(thread), can_allocate(can_allocate),
78808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        last_method(NULL), last_line_number(0), repetition_count(0), frame_count(0) {
789d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
790d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
791bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual ~StackDumpVisitor() {
792e85d2e924953f1a13b7152edba1c13853e6f3a86Elliott Hughes    if (frame_count == 0) {
793e85d2e924953f1a13b7152edba1c13853e6f3a86Elliott Hughes      os << "  (no managed stack frames)\n";
794e85d2e924953f1a13b7152edba1c13853e6f3a86Elliott Hughes    }
795d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
796d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
797b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers  bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
79866f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* m = GetMethod();
7990399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (m->IsRuntimeMethod()) {
800530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;
8019086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    }
80228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    const int kMaxRepetition = 3;
803d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Class* c = m->GetDeclaringClass();
8048e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
805b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    const DexCache* dex_cache = c->GetDexCache();
806b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    int line_number = -1;
807b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    if (dex_cache != NULL) {  // be tolerant of bad input
808b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers      const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
8090399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
810b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    }
81128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    if (line_number == last_line_number && last_method == m) {
81228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      repetition_count++;
813d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    } else {
81428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      if (repetition_count >= kMaxRepetition) {
81528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        os << "  ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
81628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      }
81728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      repetition_count = 0;
81828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      last_line_number = line_number;
81928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      last_method = m;
82028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    }
82128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    if (repetition_count < kMaxRepetition) {
82228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      os << "  at " << PrettyMethod(m, false);
82328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      if (m->IsNative()) {
82428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        os << "(Native method)";
82528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      } else {
8266d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        mh.ChangeMethod(m);
8276d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        const char* source_file(mh.GetDeclaringClassSourceFile());
8286d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        os << "(" << (source_file != NULL ? source_file : "unavailable")
82928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers           << ":" << line_number << ")";
83028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      }
83128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      os << "\n";
83208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes      if (frame_count == 0) {
83308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        Monitor::DescribeWait(os, thread);
83408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes      }
83508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes      if (can_allocate) {
83608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        Monitor::DescribeLocks(os, this);
83708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes      }
838d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
8398e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
84008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    ++frame_count;
841530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
842d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
84308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  std::ostream& os;
84408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  const Thread* thread;
84508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  bool can_allocate;
8466d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
84766f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier  AbstractMethod* last_method;
84828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int last_line_number;
84928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int repetition_count;
8508e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int frame_count;
851d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes};
852d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
853d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpStack(std::ostream& os) const {
854ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  // If we're currently in native code, dump that stack before dumping the managed stack.
855dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  if (GetState() == kNative) {
85646e251bf7200cc06f5a9a82ee2030e650f5e1443Elliott Hughes    DumpKernelStack(os, GetTid(), "  kernel: ", false);
85746e251bf7200cc06f5a9a82ee2030e650f5e1443Elliott Hughes    DumpNativeStack(os, GetTid(), "  native: ", false);
858ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
85908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  UniquePtr<Context> context(Context::Create());
86008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  StackDumpVisitor dumper(os, this, context.get(), !throwing_OutOfMemoryError_);
8610399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  dumper.WalkStack();
862e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes}
863e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes
864be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::ThreadExitCallback(void* arg) {
865be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
8666a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes  if (self->thread_exit_check_count_ == 0) {
8676a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes    LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
8686a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes    CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
8696a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes    self->thread_exit_check_count_ = 1;
8706a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes  } else {
8716a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes    LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
8726a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes  }
873b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
874b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
875be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::Startup() {
87600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  {
877b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers    MutexLock mu(*Locks::thread_suspend_count_lock_);  // Keep GCC happy.
87800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    resume_cond_ = new ConditionVariable("Thread resumption condition variable");
87900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
88000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
881b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Allocate a TLS slot.
8828d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
883b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
884b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Double-check the TLS slot allocation.
885b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  if (pthread_getspecific(pthread_key_self_) != NULL) {
8863d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
887b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  }
888038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
889038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
890038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesvoid Thread::FinishStartup() {
891365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  Runtime* runtime = Runtime::Current();
892365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  CHECK(runtime->IsStarted());
893b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
89401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  // Finish attaching the main thread.
89500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ScopedObjectAccess soa(Thread::Current());
896365c10235438607541fa2259a5fec48061b90bd8Ian Rogers  Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
8979a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson
898af8d15a3267343dec135cc6df1db740c0a5c7b52Elliott Hughes  Runtime::Current()->GetClassLinker()->RunRootClinits();
899b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
900b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
901c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughesvoid Thread::Shutdown() {
9028d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
903c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
904c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
90552673ffae0025d86f4023735581f19ebcc477487Ian RogersThread::Thread(bool daemon)
9060399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    : suspend_count_(0),
9070399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      card_table_(NULL),
9080399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      exception_(NULL),
9090399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      stack_end_(NULL),
9100399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      managed_stack_(),
9110399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      jni_env_(NULL),
9120399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      self_(NULL),
91347179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      peer_(NULL),
9140399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      stack_begin_(NULL),
9150399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      stack_size_(0),
9160399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      thin_lock_id_(0),
9170399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      tid_(0),
918e62934d85fbc2d935afdad57eeade39ecbd7440aElliott Hughes      wait_mutex_(new Mutex("a thread wait mutex")),
919e62934d85fbc2d935afdad57eeade39ecbd7440aElliott Hughes      wait_cond_(new ConditionVariable("a thread wait condition variable")),
9208daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      wait_monitor_(NULL),
9218daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      interrupted_(false),
922dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      wait_next_(NULL),
9238e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      monitor_enter_object_(NULL),
924dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      top_sirt_(NULL),
925dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      runtime_(NULL),
92685d1545e985ac689db4bad7849880e843707c862Elliott Hughes      class_loader_override_(NULL),
927418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes      long_jump_context_(NULL),
928726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      throwing_OutOfMemoryError_(false),
9290399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      debug_suspend_count_(0),
930e343b76af81a005ef64f5e75a555389fd9147dabjeffhao      debug_invoke_req_(new DebugInvokeReq),
931899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      trace_stack_(new std::vector<TraceStackFrame>),
9320399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      name_(new std::string(kThreadNameDuringStartup)),
93352673ffae0025d86f4023735581f19ebcc477487Ian Rogers      daemon_(daemon),
93400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      pthread_self_(0),
93552673ffae0025d86f4023735581f19ebcc477487Ian Rogers      no_thread_suspension_(0),
9366a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes      last_no_thread_suspension_cause_(NULL),
9376a607ad0902f3b8478e95d0b6b3e63a538571a3fElliott Hughes      thread_exit_check_count_(0) {
938f5a7a476e7ea63e094ff0f011dccc170607e6f6bElliott Hughes  CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
93930e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  state_and_flags_.as_struct.flags = 0;
94030e173f6da202e4caa37ceb477e2fbbe09cec990Ian Rogers  state_and_flags_.as_struct.state = kNative;
941ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
942dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes}
943dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
9447dc5166ea740359d381097a7ab382c1dd404055fElliott Hughesbool Thread::IsStillStarting() const {
9457dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  // You might think you can check whether the state is kStarting, but for much of thread startup,
9467dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  // the thread might also be in kVmWait.
9477dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  // You might think you can check whether the peer is NULL, but the peer is actually created and
9487dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  // assigned fairly early on, and needs to be.
9497dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  // It turns out that the last thing to change is the thread name; that's a good proxy for "has
9507dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  // this thread _ever_ entered kRunnable".
9517dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes  return (*name_ == kThreadNameDuringStartup);
9527dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes}
9537dc5166ea740359d381097a7ab382c1dd404055fElliott Hughes
95400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::AssertNoPendingException() const {
95500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  if (UNLIKELY(IsExceptionPending())) {
95600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    ScopedObjectAccess soa(Thread::Current());
95700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    Throwable* exception = GetException();
95800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    LOG(FATAL) << "No pending exception expected: " << exception->Dump();
95900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
96000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
96100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
96200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersstatic void MonitorExitVisitor(const Object* object, void* arg) NO_THREAD_SAFETY_ANALYSIS {
96300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Thread* self = reinterpret_cast<Thread*>(arg);
96402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  Object* entered_monitor = const_cast<Object*>(object);
96500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  if (self->HoldsLock(entered_monitor)) {
96600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    LOG(WARNING) << "Calling MonitorExit on object "
96700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers                 << object << " (" << PrettyTypeOf(object) << ")"
96800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers                 << " left locked by native thread "
96900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers                 << *Thread::Current() << " which is detaching";
97000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    entered_monitor->MonitorExit(self);
97100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
97202b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes}
97302b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
974c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughesvoid Thread::Destroy() {
975120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  Thread* self = this;
976120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  DCHECK_EQ(self, Thread::Current());
97702b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
97829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  if (peer_ != NULL) {
979120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    // We may need to call user-supplied managed code, do this before final clean-up.
980120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    HandleUncaughtExceptions();
981120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    RemoveFromThreadGroup();
982534da072d3db3beecbd74e5aa23d630d73695f2cElliott Hughes
98329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // this.vmData = 0;
984120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    jni_env_->SetIntField(peer_, WellKnownClasses::java_lang_Thread_vmData, 0);
98502b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
986120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    {
987120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      ScopedObjectAccess soa(self);
988120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      Dbg::PostThreadDeath(self);
989120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    }
99002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
99129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // Thread.join() is implemented as an Object.wait() on the Thread.lock
99229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // object. Signal anyone who is waiting.
993120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    ScopedLocalRef<jobject> lock(jni_env_,
994120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                                 jni_env_->GetObjectField(peer_,
995120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                                                          WellKnownClasses::java_lang_Thread_lock));
996038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    // (This conditional is only needed for tests, where Thread.lock won't have been set.)
997120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    if (lock.get() != NULL) {
998120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      jni_env_->MonitorEnter(lock.get());
999120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      jni_env_->CallVoidMethod(lock.get(), WellKnownClasses::java_lang_Object_notify);
1000120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers      jni_env_->MonitorExit(lock.get());
10015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
10025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1003120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers
1004120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
1005120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (jni_env_ != NULL) {
1006120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    jni_env_->monitors.VisitRoots(MonitorExitVisitor, self);
1007120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  }
1008c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott Hughes}
100902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
1010c0f0933249cf516b37717faa766e1e9808f7c1f8Elliott HughesThread::~Thread() {
1011dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  if (jni_env_ != NULL && peer_ != NULL) {
1012dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    // If pthread_create fails we don't have a jni env here.
1013dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier    jni_env_->DeleteGlobalRef(peer_);
1014dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  }
1015dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  peer_ = NULL;
1016dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier
1017c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes  delete jni_env_;
101802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  jni_env_ = NULL;
101902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
1020dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  CHECK_NE(GetState(), kRunnable);
1021dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  // We may be deleting a still born thread.
1022dbe6f4613ae0161b169f4fca8a616b0b393370abMathieu Chartier  SetStateUnsafe(kTerminated);
102385d1545e985ac689db4bad7849880e843707c862Elliott Hughes
102485d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_cond_;
102585d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_mutex_;
102685d1545e985ac689db4bad7849880e843707c862Elliott Hughes
1027776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#if !defined(ART_USE_LLVM_COMPILER)
102885d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete long_jump_context_;
1029776ac1fa61237db645adb4370a4aab888530caf4Ian Rogers#endif
1030475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes
1031475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes  delete debug_invoke_req_;
1032e343b76af81a005ef64f5e75a555389fd9147dabjeffhao  delete trace_stack_;
1033899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  delete name_;
1034d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes
1035d8af1592a97f7447ecf93f85098cb36340ab0fe2Elliott Hughes  TearDownAlternateSignalStack();
1036c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
1037c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
1038120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogersvoid Thread::HandleUncaughtExceptions() {
1039accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (!IsExceptionPending()) {
1040accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    return;
1041accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
1042120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers
1043accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Get and clear the exception.
1044120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  ScopedLocalRef<jthrowable> exception(jni_env_, jni_env_->ExceptionOccurred());
1045120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  jni_env_->ExceptionClear();
1046accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1047accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the thread has its own handler, use that.
1048120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  ScopedLocalRef<jobject> handler(jni_env_,
1049120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                                  jni_env_->GetObjectField(peer_,
1050120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                                                           WellKnownClasses::java_lang_Thread_uncaughtHandler));
1051120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (handler.get() == NULL) {
1052accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    // Otherwise use the thread group's default handler.
1053120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    handler.reset(jni_env_->GetObjectField(peer_, WellKnownClasses::java_lang_Thread_group));
1054accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
1055accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1056accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Call the handler.
1057120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  jni_env_->CallVoidMethod(handler.get(),
1058120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                           WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException,
1059120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                           peer_, exception.get());
1060accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1061accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the handler threw, clear that exception too.
1062120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  jni_env_->ExceptionClear();
1063a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes}
1064a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes
1065120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogersvoid Thread::RemoveFromThreadGroup() {
10664514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // this.group.removeThread(this);
10674514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // group can be null if we're in the compiler or a test.
1068120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  ScopedLocalRef<jobject> group(jni_env_,
1069120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                                jni_env_->GetObjectField(peer_,
1070120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                                                         WellKnownClasses::java_lang_Thread_group));
1071120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers  if (group.get() != NULL) {
1072120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers    jni_env_->CallVoidMethod(group.get(), WellKnownClasses::java_lang_ThreadGroup_removeThread,
1073120f1c74a9768e958377b6c97897511b27ae58c8Ian Rogers                             peer_);
10744514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  }
10754514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom}
1076accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1077408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogerssize_t Thread::NumSirtReferences() {
1078a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  size_t count = 0;
107940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1080a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    count += cur->NumberOfReferences();
1081a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
1082a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return count;
1083a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
1084a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
1085408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogersbool Thread::SirtContains(jobject obj) {
1086408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object** sirt_entry = reinterpret_cast<Object**>(obj);
108740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
108840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (cur->Contains(sirt_entry)) {
1089a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers      return true;
1090a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    }
1091a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
10920399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // JNI code invoked from portable code uses shadow frames rather than the SIRT.
10930399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  return managed_stack_.ShadowFramesContain(sirt_entry);
109428f1a147d77ec772db98bed890b50a9ddcff2365TDYa}
109528f1a147d77ec772db98bed890b50a9ddcff2365TDYa
10968dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liaovoid Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
109740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
10988dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    size_t num_refs = cur->NumberOfReferences();
10998dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    for (size_t j = 0; j < num_refs; j++) {
110040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      Object* object = cur->GetReference(j);
11015e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      if (object != NULL) {
11025e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom        visitor(object, arg);
11035e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      }
11048dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    }
11058dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  }
11068dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao}
11078dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1108408f79aeb676251ba35667a64e86c20638d7cb0bIan RogersObject* Thread::DecodeJObject(jobject obj) {
110981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  Locks::mutator_lock_->AssertSharedHeld(this);
1110408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (obj == NULL) {
1111408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    return NULL;
1112408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1113408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1114408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRefKind kind = GetIndirectRefKind(ref);
1115408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object* result;
1116408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  switch (kind) {
1117408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kLocal:
1118408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
111969f5bc6759f256a146eefd8a7141d39fcc3b0421Elliott Hughes      IndirectReferenceTable& locals = jni_env_->locals;
1120cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(locals.Get(ref));
1121408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1122408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1123408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kGlobal:
1124408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1125408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1126408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& globals = vm->globals;
112781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      MutexLock mu(this, vm->globals_lock);
1128cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(globals.Get(ref));
1129408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1130408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1131408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kWeakGlobal:
1132408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1133408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1134408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& weak_globals = vm->weak_globals;
113581d425b0b232962441616f8b14f73620bffef5e5Ian Rogers      MutexLock mu(this, vm->weak_globals_lock);
1136cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(weak_globals.Get(ref));
1137408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      if (result == kClearedJniWeakGlobal) {
1138408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        // This is a special case where it's okay to return NULL.
1139408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        return NULL;
1140408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      }
1141408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1142408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1143408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kSirtOrInvalid:
1144408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  default:
1145408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // TODO: make stack indirect reference table lookup more efficient
1146408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // Check if this is a local reference in the SIRT
11470399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (SirtContains(obj)) {
11480cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers      result = *reinterpret_cast<Object**>(obj);  // Read from SIRT
1149c2dc62d1c9241dfe880a81698713c314b13aa63fElliott Hughes    } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
1150408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      // Assume an invalid local reference is actually a direct pointer.
1151408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      result = reinterpret_cast<Object*>(obj);
1152408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    } else {
1153a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes      result = kInvalidIndirectRefObject;
1154408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1155408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1156408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
1157408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (result == NULL) {
11583f6635a2c84d645002f651c312d53f8348646c1fElliott Hughes    JniAbortF(NULL, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
1159a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes  } else {
1160a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    if (result != kInvalidIndirectRefObject) {
1161b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes      Runtime::Current()->GetHeap()->VerifyObject(result);
1162a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    }
1163408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1164408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  return result;
1165408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers}
1166408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
116781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers// Implements java.lang.Thread.interrupted.
116881d425b0b232962441616f8b14f73620bffef5e5Ian Rogersbool Thread::Interrupted() {
116981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  MutexLock mu(*wait_mutex_);
117081d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  bool interrupted = interrupted_;
117181d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  interrupted_ = false;
117281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  return interrupted;
117381d425b0b232962441616f8b14f73620bffef5e5Ian Rogers}
117481d425b0b232962441616f8b14f73620bffef5e5Ian Rogers
117581d425b0b232962441616f8b14f73620bffef5e5Ian Rogers// Implements java.lang.Thread.isInterrupted.
117681d425b0b232962441616f8b14f73620bffef5e5Ian Rogersbool Thread::IsInterrupted() {
117781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  MutexLock mu(*wait_mutex_);
117881d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  return interrupted_;
117981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers}
118081d425b0b232962441616f8b14f73620bffef5e5Ian Rogers
118181d425b0b232962441616f8b14f73620bffef5e5Ian Rogersvoid Thread::Interrupt() {
118281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  MutexLock mu(*wait_mutex_);
118381d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  if (interrupted_) {
118481d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    return;
118581d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  }
118681d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  interrupted_ = true;
118781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  NotifyLocked();
118881d425b0b232962441616f8b14f73620bffef5e5Ian Rogers}
118981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers
119081d425b0b232962441616f8b14f73620bffef5e5Ian Rogersvoid Thread::Notify() {
119181d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  MutexLock mu(*wait_mutex_);
119281d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  NotifyLocked();
119381d425b0b232962441616f8b14f73620bffef5e5Ian Rogers}
119481d425b0b232962441616f8b14f73620bffef5e5Ian Rogers
119581d425b0b232962441616f8b14f73620bffef5e5Ian Rogersvoid Thread::NotifyLocked() {
119681d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  if (wait_monitor_ != NULL) {
119781d425b0b232962441616f8b14f73620bffef5e5Ian Rogers    wait_cond_->Signal();
119881d425b0b232962441616f8b14f73620bffef5e5Ian Rogers  }
119981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers}
120081d425b0b232962441616f8b14f73620bffef5e5Ian Rogers
12010399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersclass CountStackDepthVisitor : public StackVisitor {
12029b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
12030399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  CountStackDepthVisitor(const ManagedStack* stack,
1204ca190666fb11820153f74274c495ba1f913d8a69Ian Rogers                         const std::vector<TraceStackFrame>* trace_stack)
1205b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
120608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes      : StackVisitor(stack, trace_stack, NULL),
120708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        depth_(0), skip_depth_(0), skipping_(true) {}
1208d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
1209b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers  bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
121029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // We want to skip frames up to and including the exception's constructor.
12119086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // Note we also skip the frame if it doesn't have a method (namely the callee
12129086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // save frame)
121366f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* m = GetMethod();
12140399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (skipping_ && !m->IsRuntimeMethod() &&
12150399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        !Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
121629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skipping_ = false;
121729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
121829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (!skipping_) {
12190399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      if (!m->IsRuntimeMethod()) {  // Ignore runtime frames (in particular callee save).
12206b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers        ++depth_;
12216b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      }
122229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    } else {
122329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      ++skip_depth_;
122429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
1225530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
12269b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
12279b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
12289b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int GetDepth() const {
1229aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return depth_;
12309b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
12319b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
123229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int GetSkipDepth() const {
123329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    return skip_depth_;
123429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  }
123529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
12369b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
1237aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t depth_;
123829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  uint32_t skip_depth_;
123929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  bool skipping_;
12409b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
12419b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
12420399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersclass BuildInternalStackTraceVisitor : public StackVisitor {
12439b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
12441f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  explicit BuildInternalStackTraceVisitor(Thread* self, const ManagedStack* stack,
12450399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers                                          const std::vector<TraceStackFrame>* trace_stack,
1246ca190666fb11820153f74274c495ba1f913d8a69Ian Rogers                                          int skip_depth)
12471f5393447b9f45be7918042d9ee7b521376de866Ian Rogers      : StackVisitor(stack, trace_stack, NULL), self_(self),
124808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        skip_depth_(skip_depth), count_(0), dex_pc_trace_(NULL), method_trace_(NULL) {}
1249283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers
12501f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  bool Init(int depth)
1251b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1252aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate method trace with an extra slot that will hold the PC trace
12530399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    SirtRef<ObjectArray<Object> >
12541f5393447b9f45be7918042d9ee7b521376de866Ian Rogers        method_trace(self_,
12551f5393447b9f45be7918042d9ee7b521376de866Ian Rogers                     Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1));
12560399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (method_trace.get() == NULL) {
1257283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1258726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
12590399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    IntArray* dex_pc_trace = IntArray::Alloc(depth);
12600399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (dex_pc_trace == NULL) {
1261283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1262726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1263aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Save PC trace in last element of method trace, also places it into the
1264aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // object graph.
12650399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    method_trace->Set(depth, dex_pc_trace);
12660399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    // Set the Object*s and assert that no thread suspension is now possible.
126752673ffae0025d86f4023735581f19ebcc477487Ian Rogers    const char* last_no_suspend_cause =
12681f5393447b9f45be7918042d9ee7b521376de866Ian Rogers        self_->StartAssertNoThreadSuspension("Building internal stack trace");
126952673ffae0025d86f4023735581f19ebcc477487Ian Rogers    CHECK(last_no_suspend_cause == NULL) << last_no_suspend_cause;
12700399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    method_trace_ = method_trace.get();
12710399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    dex_pc_trace_ = dex_pc_trace;
1272283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return true;
12739b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
12749b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
12750399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  virtual ~BuildInternalStackTraceVisitor() {
127652673ffae0025d86f4023735581f19ebcc477487Ian Rogers    if (method_trace_ != NULL) {
12771f5393447b9f45be7918042d9ee7b521376de866Ian Rogers      self_->EndAssertNoThreadSuspension(NULL);
127852673ffae0025d86f4023735581f19ebcc477487Ian Rogers    }
12790399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  }
12809b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1281b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers  bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
12820399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (method_trace_ == NULL || dex_pc_trace_ == NULL) {
1283530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
1284726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
128529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (skip_depth_ > 0) {
128629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skip_depth_--;
1287530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;
128829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
128966f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* m = GetMethod();
12900399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (m->IsRuntimeMethod()) {
12910399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      return true;  // Ignore runtime frames (in particular callee save).
12926b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    }
12930399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    method_trace_->Set(count_, m);
12940399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    dex_pc_trace_->Set(count_, GetDexPc());
1295aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    ++count_;
1296530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
12979b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
12989b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
12990399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  ObjectArray<Object>* GetInternalStackTrace() const {
13000399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    return method_trace_;
13019b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
13029b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
13039b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
13041f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  Thread* const self_;
130529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  // How many more frames to skip.
130629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth_;
13070399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // Current position down stack trace.
1308aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t count_;
13090399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // Array of dex PC values.
13100399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  IntArray* dex_pc_trace_;
13110399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // An array of the methods on the stack, the last entry is a reference to the PC trace.
1312aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace_;
13139b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
13149b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
131500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersjobject Thread::CreateInternalStackTrace(const ScopedObjectAccess& soa) const {
1316aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Compute depth of stack
13170399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  CountStackDepthVisitor count_visitor(GetManagedStack(), GetTraceStack());
13180399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  count_visitor.WalkStack();
13199b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int32_t depth = count_visitor.GetDepth();
132029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth = count_visitor.GetSkipDepth();
13214417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
13221f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  // Build internal stack trace.
13231f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  BuildInternalStackTraceVisitor build_trace_visitor(soa.Self(), GetManagedStack(), GetTraceStack(),
13240399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers                                                     skip_depth);
13251f5393447b9f45be7918042d9ee7b521376de866Ian Rogers  if (!build_trace_visitor.Init(depth)) {
13261f5393447b9f45be7918042d9ee7b521376de866Ian Rogers    return NULL;  // Allocation failed.
1327283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
13280399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  build_trace_visitor.WalkStack();
132900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  return soa.AddLocalReference<jobjectArray>(build_trace_visitor.GetInternalStackTrace());
1330aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers}
1331aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
133201158d7a57c8321370667a6045220237d16e0da8Elliott HughesjobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
133301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    jobjectArray output_array, int* stack_depth) {
1334aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
133500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ScopedObjectAccess soa(env);
1336aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Decode the internal stack trace into the depth, method trace and PC trace
133700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ObjectArray<Object>* method_trace = soa.Decode<ObjectArray<Object>*>(internal);
13389074b99bfbd5419e340f138a018b673ce71f77e8Ian Rogers  int32_t depth = method_trace->GetLength() - 1;
1339aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1340aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1341aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1342aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
134301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  jobjectArray result;
134401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ObjectArray<StackTraceElement>* java_traces;
134501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (output_array != NULL) {
134601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Reuse the array we were given.
134701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = output_array;
134800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    java_traces = soa.Decode<ObjectArray<StackTraceElement>*>(output_array);
134901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // ...adjusting the number of frames we'll write to not exceed the array length.
135001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    depth = std::min(depth, java_traces->GetLength());
135101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  } else {
135201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Create java_trace array and place in local reference table
135301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = class_linker->AllocStackTraceElementArray(depth);
135430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (java_traces == NULL) {
135530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
135630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
135700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    result = soa.AddLocalReference<jobjectArray>(java_traces);
135801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
135901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
136001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (stack_depth != NULL) {
136101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    *stack_depth = depth;
136201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
136355df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
13646d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
13659b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  for (int32_t i = 0; i < depth; ++i) {
1366aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
136766f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* method = down_cast<AbstractMethod*>(method_trace->Get(i));
13686d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    mh.ChangeMethod(method);
13690399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    uint32_t dex_pc = pc_trace->Get(i);
13700399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    int32_t line_number = mh.GetLineNumFromDexPC(dex_pc);
1371aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate element, potentially triggering GC
137240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    // TODO: reuse class_name_object via Class::name_?
1373486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* descriptor = mh.GetDeclaringClassDescriptor();
1374486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(descriptor != NULL);
1375486013193c94b4321414c28ce9251911e14a0599Ian Rogers    std::string class_name(PrettyDescriptor(descriptor));
13761f5393447b9f45be7918042d9ee7b521376de866Ian Rogers    SirtRef<String> class_name_object(soa.Self(),
13771f5393447b9f45be7918042d9ee7b521376de866Ian Rogers                                      String::AllocFromModifiedUtf8(class_name.c_str()));
137840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (class_name_object.get() == NULL) {
137940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      return NULL;
138040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    }
1381486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* method_name = mh.GetName();
1382486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(method_name != NULL);
13831f5393447b9f45be7918042d9ee7b521376de866Ian Rogers    SirtRef<String> method_name_object(soa.Self(), String::AllocFromModifiedUtf8(method_name));
13846d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    if (method_name_object.get() == NULL) {
13856d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      return NULL;
13866d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    }
1387486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* source_file = mh.GetDeclaringClassSourceFile();
13881f5393447b9f45be7918042d9ee7b521376de866Ian Rogers    SirtRef<String> source_name_object(soa.Self(), String::AllocFromModifiedUtf8(source_file));
138940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
13906d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      method_name_object.get(),
13916d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      source_name_object.get(),
139240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      line_number);
139330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (obj == NULL) {
139430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
139530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
1396aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1397aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
139800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    java_traces = Decode<ObjectArray<Object>*>(soa.Env(), result);
139900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(soa.Env(), internal));
1400aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1401aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
140255df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao    java_traces->Set(i, obj);
140355df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
1404aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  return result;
140555df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
140655df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
14075cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1408a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_list args;
1409a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_start(args, fmt);
14104a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1411a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_end(args);
14124a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes}
14134a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes
14144a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughesvoid Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
14154a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  std::string msg;
14164a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  StringAppendV(&msg, fmt, ap);
14175cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes  ThrowNewException(exception_class_descriptor, msg.c_str());
14185cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes}
141937f7a40f6789bb287f287a9af00777af9d6428eeElliott Hughes
14205cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
142100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  AssertNoPendingException(); // Callers should either clear or call ThrowNewWrappedException.
1422a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes  ThrowNewWrappedException(exception_class_descriptor, msg);
1423a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes}
1424a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes
1425a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughesvoid Thread::ThrowNewWrappedException(const char* exception_class_descriptor, const char* msg) {
1426e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
14270cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ('L', exception_class_descriptor[0]);
1428e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  std::string descriptor(exception_class_descriptor + 1);
14290cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ(';', descriptor[descriptor.length() - 1]);
1430e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  descriptor.erase(descriptor.length() - 1);
1431e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes
1432e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  JNIEnv* env = GetJniEnv();
1433a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes  jobject cause = env->ExceptionOccurred();
1434a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes  env->ExceptionClear();
1435a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes
1436726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
143730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (exception_class.get() == NULL) {
143830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
143930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
144030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
144130646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    return;
144230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1443ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  if (!Runtime::Current()->IsStarted()) {
1444ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // Something is trying to throw an exception without a started
1445ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // runtime, which is the common case in the compiler. We won't be
1446ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // able to invoke the constructor of the exception, so use
1447ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // AllocObject which will not invoke a constructor.
1448ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    ScopedLocalRef<jthrowable> exception(
1449ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom        env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1450ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    if (exception.get() != NULL) {
145100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      ScopedObjectAccessUnchecked soa(env);
145200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      Throwable* t = reinterpret_cast<Throwable*>(soa.Self()->DecodeJObject(exception.get()));
145302fbef0e356ca43b2032044f870d59de4a4ae92aIan Rogers      t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
145400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      soa.Self()->SetException(t);
1455ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    } else {
1456ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1457ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom                 << PrettyTypeOf(GetException());
1458ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      CHECK(IsExceptionPending());
1459ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    }
1460ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    return;
1461ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  }
1462a4f94740f9d66b21f4bcd3a225c434aa29cfa323Elliott Hughes  int rc = ::art::ThrowNewException(env, exception_class.get(), msg, cause);
146330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (rc != JNI_OK) {
146430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
146530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
146630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
146730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1468a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes}
1469a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes
14702ced6a534157d5d963693346904389c19775d2daElliott Hughesvoid Thread::ThrowOutOfMemoryError(const char* msg) {
14712ced6a534157d5d963693346904389c19775d2daElliott Hughes  LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
14722ced6a534157d5d963693346904389c19775d2daElliott Hughes      msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
1473726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (!throwing_OutOfMemoryError_) {
1474726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    throwing_OutOfMemoryError_ = true;
147557aba86f29d7e795bf7e68c65cc464d2291b6af1Elliott Hughes    ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
1476418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  } else {
1477225f5a1df25241babd16cdba54056b9e2cd166a2Elliott Hughes    Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
1478225f5a1df25241babd16cdba54056b9e2cd166a2Elliott Hughes    SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
1479418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  }
1480726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  throwing_OutOfMemoryError_ = false;
148179082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes}
148279082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes
1483498508c1187dc07d3eae5476784cde20f5224d93Elliott HughesThread* Thread::CurrentFromGdb() {
1484accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  return Thread::Current();
1485accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1486accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1487accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::DumpFromGdb() const {
14886b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::ostringstream ss;
14896b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Dump(ss);
1490955724179c6c739524f610023287f56b24dc31deElliott Hughes  std::string str(ss.str());
14916b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to stderr for debugging command line processes
14926b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::cerr << str;
14936b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#ifdef HAVE_ANDROID_OS
14946b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to logcat for debugging frameworks processes
14956b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  LOG(INFO) << str;
14966b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#endif
1497accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1498accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
149998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughesstruct EntryPointInfo {
150098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  uint32_t offset;
150198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  const char* name;
150298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes};
150398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes#define ENTRY_POINT_INFO(x) { ENTRYPOINT_OFFSET(x), #x }
150498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughesstatic const EntryPointInfo gThreadEntryPointInfo[] = {
150598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pAllocArrayFromCode),
150698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pAllocArrayFromCodeWithAccessCheck),
150798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pAllocObjectFromCode),
150898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pAllocObjectFromCodeWithAccessCheck),
150998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCheckAndAllocArrayFromCode),
151098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCheckAndAllocArrayFromCodeWithAccessCheck),
151198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInstanceofNonTrivialFromCode),
151298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCanPutArrayElementFromCode),
151398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCheckCastFromCode),
151498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pDebugMe),
151598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pUpdateDebuggerFromCode),
151698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInitializeStaticStorage),
151798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccessFromCode),
151898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInitializeTypeFromCode),
151998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pResolveStringFromCode),
1520474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  ENTRY_POINT_INFO(pGetAndClearException),
152198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pSet32Instance),
152298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pSet32Static),
152398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pSet64Instance),
152498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pSet64Static),
152598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pSetObjInstance),
152698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pSetObjStatic),
152798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pGet32Instance),
152898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pGet32Static),
152998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pGet64Instance),
153098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pGet64Static),
153198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pGetObjInstance),
153298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pGetObjStatic),
153398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pHandleFillArrayDataFromCode),
153498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFindNativeMethod),
153500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ENTRY_POINT_INFO(pJniMethodStart),
153600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ENTRY_POINT_INFO(pJniMethodStartSynchronized),
153700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ENTRY_POINT_INFO(pJniMethodEnd),
153800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ENTRY_POINT_INFO(pJniMethodEndSynchronized),
153900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ENTRY_POINT_INFO(pJniMethodEndWithReference),
154000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
154198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pLockObjectFromCode),
154298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pUnlockObjectFromCode),
154398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCmpgDouble),
154498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCmpgFloat),
154598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCmplDouble),
154698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCmplFloat),
154798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pDadd),
154898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pDdiv),
154998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pDmul),
155098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pDsub),
155198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pF2d),
155298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFmod),
15530183dd7297709ef0beb31e120fc34fdd12f61915Ian Rogers  ENTRY_POINT_INFO(pSqrt),
155498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pI2d),
155598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pL2d),
155698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pD2f),
155798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFadd),
155898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFdiv),
155998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFmodf),
156098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFmul),
156198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pFsub),
156298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pI2f),
156398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pL2f),
156498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pD2iz),
156598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pF2iz),
156698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pIdivmod),
156798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pD2l),
156898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pF2l),
156998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pLdiv),
157098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pLdivmod),
157198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pLmul),
157298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pShlLong),
157398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pShrLong),
157498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pUshrLong),
157598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pIndexOf),
157698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pMemcmp16),
157798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pStringCompareTo),
157898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pMemcpy),
157998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pUnresolvedDirectMethodTrampolineFromCode),
158098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
158198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInvokeInterfaceTrampoline),
158298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
158398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
158498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
158598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
158698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pCheckSuspendFromCode),
158798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pTestSuspendFromCode),
158898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pDeliverException),
158998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pThrowAbstractMethodErrorFromCode),
159098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pThrowArrayBoundsFromCode),
159198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pThrowDivZeroFromCode),
159298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pThrowNoSuchMethodFromCode),
159398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pThrowNullPointerFromCode),
159498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  ENTRY_POINT_INFO(pThrowStackOverflowFromCode),
159598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes};
159698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes#undef ENTRY_POINT_INFO
159798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes
159828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughesvoid Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
159928fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes  CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
160098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes
160198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes#define DO_THREAD_OFFSET(x) if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { os << # x; return; }
1602474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers  DO_THREAD_OFFSET(state_and_flags_);
160398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(card_table_);
160498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(exception_);
160598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(jni_env_);
160698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(self_);
160798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(stack_end_);
160898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(suspend_count_);
160998e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(thin_lock_id_);
16100399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  //DO_THREAD_OFFSET(top_of_managed_stack_);
16110399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  //DO_THREAD_OFFSET(top_of_managed_stack_pc_);
161298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  DO_THREAD_OFFSET(top_sirt_);
161328fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes#undef DO_THREAD_OFFSET
161498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes
161598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  size_t entry_point_count = arraysize(gThreadEntryPointInfo);
161698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  CHECK_EQ(entry_point_count * size_of_pointers, sizeof(EntryPoints));
161798e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  uint32_t expected_offset = OFFSETOF_MEMBER(Thread, entrypoints_);
161898e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  for (size_t i = 0; i < entry_point_count; ++i) {
1619474b6da273c7ce6df50a4e51eb9929a77e1611c3Ian Rogers    CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset) << gThreadEntryPointInfo[i].name;
162098e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes    expected_offset += size_of_pointers;
162198e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes    if (gThreadEntryPointInfo[i].offset == offset) {
162298e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes      os << gThreadEntryPointInfo[i].name;
162398e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes      return;
162498e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes    }
162598e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  }
162698e2017cac7ca554602480fcefabbbe630a4a39bElliott Hughes  os << offset;
162728fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes}
162828fa76d17d741238da86dbdb47f721ae97c9eac8Elliott Hughes
16290399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersstatic const bool kDebugExceptionDelivery = false;
16300399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersclass CatchBlockStackVisitor : public StackVisitor {
1631bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers public:
16320399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  CatchBlockStackVisitor(Thread* self, Throwable* exception)
1633b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
16340399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      : StackVisitor(self->GetManagedStack(), self->GetTraceStack(), self->GetLongJumpContext()),
16350399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        self_(self), exception_(exception), to_find_(exception->GetClass()), throw_method_(NULL),
16360399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        throw_frame_id_(0), throw_dex_pc_(0), handler_quick_frame_(NULL),
16370399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        handler_quick_frame_pc_(0), handler_dex_pc_(0), native_method_count_(0),
163857b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
163952673ffae0025d86f4023735581f19ebcc477487Ian Rogers    // Exception not in root sets, can't allow GC.
164052673ffae0025d86f4023735581f19ebcc477487Ian Rogers    last_no_assert_suspension_cause_ = self->StartAssertNoThreadSuspension("Finding catch block");
164152673ffae0025d86f4023735581f19ebcc477487Ian Rogers  }
164252673ffae0025d86f4023735581f19ebcc477487Ian Rogers
164352673ffae0025d86f4023735581f19ebcc477487Ian Rogers  ~CatchBlockStackVisitor() {
164452673ffae0025d86f4023735581f19ebcc477487Ian Rogers    LOG(FATAL) << "UNREACHABLE";  // Expected to take long jump.
164567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  }
1646bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1647b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers  bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1648b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
164966f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* method = GetMethod();
1650530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (method == NULL) {
16510399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      // This is the upcall, we remember the frame and last pc so that we may long jump to them.
16520399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      handler_quick_frame_pc_ = GetCurrentQuickFramePc();
16530399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      handler_quick_frame_ = GetCurrentQuickFrame();
165457b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      return false;  // End stack walk.
1655530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
1656530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    uint32_t dex_pc = DexFile::kDexNoIndex;
165757b86d47b66322693a070185fadfb43cb9c12eabIan Rogers    if (method->IsRuntimeMethod()) {
1658530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // ignore callee save method
165957b86d47b66322693a070185fadfb43cb9c12eabIan Rogers      DCHECK(method->IsCalleeSaveMethod());
1660530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    } else {
16610399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      if (throw_method_ == NULL) {
16620399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        throw_method_ = method;
16630399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        throw_frame_id_ = GetFrameId();
16640399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        throw_dex_pc_ = GetDexPc();
16650399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      }
16660399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      if (method->IsNative()) {
16670399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        native_method_count_++;
16680399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      } else {
16690399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        // Unwind stack when an exception occurs during method tracing
16700399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        if (UNLIKELY(method_tracing_active_ && IsTraceExitPc(GetCurrentQuickFramePc()))) {
16718320f3867c02bae9bef6cdab267820cb7b412781buzbee          uintptr_t pc = TraceMethodUnwindFromCode(Thread::Current());
16720c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          dex_pc = method->ToDexPc(pc);
16730399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        } else {
16740399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers          dex_pc = GetDexPc();
1675530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        }
1676bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1677530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
1678530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (dex_pc != DexFile::kDexNoIndex) {
1679530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1680530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (found_dex_pc != DexFile::kDexNoIndex) {
16810399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        handler_dex_pc_ = found_dex_pc;
16820c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        handler_quick_frame_pc_ = method->ToNativePc(found_dex_pc);
16830399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        handler_quick_frame_ = GetCurrentQuickFrame();
168457b86d47b66322693a070185fadfb43cb9c12eabIan Rogers        return false;  // End stack walk.
1685bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
16861a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao    }
168757b86d47b66322693a070185fadfb43cb9c12eabIan Rogers    return true;  // Continue stack walk.
16881a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
16891a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1690b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers  void DoLongJump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
169166f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* catch_method = *handler_quick_frame_;
16926e9d22c78c1016e70f8c2a9e6bc66c94ec36f728Elliott Hughes    Dbg::PostException(self_, throw_frame_id_, throw_method_, throw_dex_pc_,
16930399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers                       catch_method, handler_dex_pc_, exception_);
16940399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (kDebugExceptionDelivery) {
16950399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      if (catch_method == NULL) {
16960399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        LOG(INFO) << "Handler is upcall";
16970399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      } else {
16980399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
16990399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        const DexFile& dex_file =
17000399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers            class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
17010399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        int line_number = dex_file.GetLineNumFromPC(catch_method, handler_dex_pc_);
17020399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
17030399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      }
17040399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    }
170552673ffae0025d86f4023735581f19ebcc477487Ian Rogers    self_->SetException(exception_);  // Exception back in root set.
170652673ffae0025d86f4023735581f19ebcc477487Ian Rogers    self_->EndAssertNoThreadSuspension(last_no_assert_suspension_cause_);
17070399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    // Place context back on thread so it will be available when we continue.
17080399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    self_->ReleaseLongJumpContext(context_);
17090399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
17100399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    CHECK_NE(handler_quick_frame_pc_, 0u);
17110399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    context_->SetPC(handler_quick_frame_pc_);
17120399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    context_->SmashCallerSaves();
17130399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    context_->DoLongJump();
17140399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  }
17150399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers
17160399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers private:
17170399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  Thread* self_;
17180399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  Throwable* exception_;
17190399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // The type of the exception catch block to find.
1720bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Class* to_find_;
172166f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier  AbstractMethod* throw_method_;
17220399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  JDWP::FrameId throw_frame_id_;
17230399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  uint32_t throw_dex_pc_;
17240399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // Quick frame with found handler or last frame if no handler found.
172566f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier  AbstractMethod** handler_quick_frame_;
17260399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // PC to branch to for the handler.
17270399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  uintptr_t handler_quick_frame_pc_;
17280399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  // Associated dex PC.
17290399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  uint32_t handler_dex_pc_;
173067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // Number of native methods passed in crawl (equates to number of SIRTs to pop)
173167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uint32_t native_method_count_;
173257b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  // Is method tracing active?
173357b86d47b66322693a070185fadfb43cb9c12eabIan Rogers  const bool method_tracing_active_;
173452673ffae0025d86f4023735581f19ebcc477487Ian Rogers  // Support for nesting no thread suspension checks.
173552673ffae0025d86f4023735581f19ebcc477487Ian Rogers  const char* last_no_assert_suspension_cause_;
1736bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers};
1737bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1738ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogersvoid Thread::DeliverException() {
1739d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Throwable* exception = GetException();  // Get exception from thread
1740ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  CHECK(exception != NULL);
174128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  // Don't leave exception visible while we try to find the handler, which may cause class
1742d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  // resolution.
174328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  ClearException();
174428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1745a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    String* msg = exception->GetDetailMessage();
1746a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1747a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1748c073b075241640c94c27e661ed6f29ff5fcee5d8Elliott Hughes                        << ": " << str_msg << "\n");
174928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
17500399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  CatchBlockStackVisitor catch_finder(this, exception);
17510399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  catch_finder.WalkStack(true);
17520399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  catch_finder.DoLongJump();
17539a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  LOG(FATAL) << "UNREACHABLE";
1754bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1755bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1756bdb0391258abc54bf77c676e36847d28a783bfe5Ian RogersContext* Thread::GetLongJumpContext() {
175785d1545e985ac689db4bad7849880e843707c862Elliott Hughes  Context* result = long_jump_context_;
1758bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (result == NULL) {
1759bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    result = Context::Create();
17600399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  } else {
17610399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    long_jump_context_ = NULL;  // Avoid context being shared.
17621a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
1763bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  return result;
17641a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao}
17651a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
176666f19258f9728d4ffe026074d8fd429d639802faMathieu ChartierAbstractMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, size_t* frame_id) const {
17670399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  struct CurrentMethodVisitor : public StackVisitor {
17680399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    CurrentMethodVisitor(const ManagedStack* stack,
1769ca190666fb11820153f74274c495ba1f913d8a69Ian Rogers                         const std::vector<TraceStackFrame>* trace_stack)
1770b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
177108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes        : StackVisitor(stack, trace_stack, NULL), method_(NULL), dex_pc_(0), frame_id_(0) {}
17728be2d40d42223b515de12629216151a558895969Elliott Hughes
1773b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers    virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
177466f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier      AbstractMethod* m = GetMethod();
17750399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      if (m->IsRuntimeMethod()) {
17760399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        // Continue if this is a runtime method.
17770399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        return true;
17780399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      }
17790399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      method_ = m;
17800399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      dex_pc_ = GetDexPc();
17810399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      frame_id_ = GetFrameId();
17820399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      return false;
17830399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    }
178466f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier    AbstractMethod* method_;
17850399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    uint32_t dex_pc_;
17860399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    size_t frame_id_;
17870399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  };
17880399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers
17890399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  CurrentMethodVisitor visitor(GetManagedStack(), GetTraceStack());
17900399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  visitor.WalkStack(false);
17910399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  if (dex_pc != NULL) {
17920399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    *dex_pc = visitor.dex_pc_;
1793d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  }
17940399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  if (frame_id != NULL) {
17950399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    *frame_id = visitor.frame_id_;
1796ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa  }
17970399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  return visitor.method_;
1798ee0d3fb2fbd736484fe8c3177a4e965ea86d1c65TDYa}
179933dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
18005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesbool Thread::HoldsLock(Object* object) {
18015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (object == NULL) {
18025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
18035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
180424a3c2e9924e8765c4a9b4d383cb8f3b922f9c9fBrian Carlstrom  return object->GetThinLockId() == thin_lock_id_;
18055f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
18065f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
18070399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersclass ReferenceMapVisitor : public StackVisitor {
1808d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers public:
18090399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  ReferenceMapVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
1810ca190666fb11820153f74274c495ba1f913d8a69Ian Rogers                      Context* context, Heap::RootVisitor* root_visitor, void* arg)
1811b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1812ca190666fb11820153f74274c495ba1f913d8a69Ian Rogers      : StackVisitor(stack, trace_stack, context), root_visitor_(root_visitor), arg_(arg) {}
1813d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1814b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers  bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
18156a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    if (false) {
18160399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
18170399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers          << StringPrintf("@ PC:%04x", GetDexPc());
18186a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    }
18190399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    ShadowFrame* shadow_frame = GetCurrentShadowFrame();
18200399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    if (shadow_frame != NULL) {
18210399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      shadow_frame->VisitRoots(root_visitor_, arg_);
18220399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers    } else {
182366f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier      AbstractMethod* m = GetMethod();
18240399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      // Process register map (which native and runtime methods don't have)
1825640495bd1aebcd0b429d59f62b57d0c984b2d8c6Ian Rogers      if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
18260c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        const uint8_t* native_gc_map = m->GetNativeGcMap();
18270c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        CHECK(native_gc_map != NULL) << PrettyMethod(m);
18280c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        mh_.ChangeMethod(m);
18290c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        const DexFile::CodeItem* code_item = mh_.GetCodeItem();
1830caf7654a0e6c76c7489970b1a246fccf220f9982Elliott Hughes        DCHECK(code_item != NULL) << PrettyMethod(m); // Can't be NULL or how would we compile its instructions?
18310c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        NativePcOffsetToReferenceMap map(native_gc_map);
18320399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers        size_t num_regs = std::min(map.RegWidth() * 8,
18330399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers                                   static_cast<size_t>(code_item->registers_size_));
18340c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers        if (num_regs > 0) {
18350c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
18360c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          DCHECK(reg_bitmap != NULL);
18370c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          const VmapTable vmap_table(m->GetVmapTableRaw());
18380c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          uint32_t core_spills = m->GetCoreSpillMask();
18390c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          uint32_t fp_spills = m->GetFpSpillMask();
18400c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          size_t frame_size = m->GetFrameSizeInBytes();
18410c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          // For all dex registers in the bitmap
184266f19258f9728d4ffe026074d8fd429d639802faMathieu Chartier          AbstractMethod** cur_quick_frame = GetCurrentQuickFrame();
18430c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          DCHECK(cur_quick_frame != NULL);
18440c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers          for (size_t reg = 0; reg < num_regs; ++reg) {
18450c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers            // Does this register hold a reference?
18460c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers            if (TestBitmap(reg, reg_bitmap)) {
18470c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers              uint32_t vmap_offset;
18480c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers              Object* ref;
18490c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers              if (vmap_table.IsInContext(reg, vmap_offset)) {
18500c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                // Compute the register we need to load from the context
18510c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                uint32_t spill_mask = core_spills;
18520c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
18530c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                uint32_t matches = 0;
18540c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                uint32_t spill_shifts = 0;
18550c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                while (matches != (vmap_offset + 1)) {
18560c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                  DCHECK_NE(spill_mask, 0u);
18570c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                  matches += spill_mask & 1;  // Add 1 if the low bit is set
18580c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                  spill_mask >>= 1;
18590c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                  spill_shifts++;
18600c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                }
18610c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                spill_shifts--;  // wind back one as we want the last match
18620c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                ref = reinterpret_cast<Object*>(GetGPR(spill_shifts));
18630c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers              } else {
18640c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                ref = reinterpret_cast<Object*>(GetVReg(cur_quick_frame, code_item, core_spills,
18650c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                                                        fp_spills, frame_size, reg));
18660c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers              }
18670c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers              if (ref != NULL) {
18680c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers                root_visitor_(ref, arg_);
18690399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers              }
1870d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            }
18714f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          }
1872d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        }
1873d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      }
1874d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    }
1875530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
1876d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1877d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1878d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers private:
1879d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  bool TestBitmap(int reg, const uint8_t* reg_vector) {
1880d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1881d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1882d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
18830c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers  // Call-back when we visit a root.
1884d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Heap::RootVisitor* root_visitor_;
18850c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers  // Argument to call-back.
1886d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void* arg_;
18870c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers  // A method helper we keep around to avoid dex file/cache re-computations.
18880c7abda482f53db3d153c073d1c7a145f84e0626Ian Rogers  MethodHelper mh_;
1889d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers};
1890d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1891d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersvoid Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
1892d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (exception_ != NULL) {
1893d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(exception_, arg);
1894d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
189540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  if (class_loader_override_ != NULL) {
189640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    visitor(class_loader_override_, arg);
189740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  }
1898410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->locals.VisitRoots(visitor, arg);
1899410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->monitors.VisitRoots(visitor, arg);
19008dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
19018dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  SirtVisitRoots(visitor, arg);
19028dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1903d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Visit roots on this thread's stack
19040399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  Context* context = GetLongJumpContext();
19050399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context, visitor, arg);
19060399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  mapper.WalkStack();
19070399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  ReleaseLongJumpContext(context);
1908410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes}
1909410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes
1910250455229aa0cc07bbd18174efe510bd52631a99jeffhao#if VERIFY_OBJECT_ENABLED
19110399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogersstatic void VerifyObject(const Object* obj, void* arg) {
19120399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  Heap* heap = reinterpret_cast<Heap*>(arg);
19130399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  heap->VerifyObject(obj);
1914250455229aa0cc07bbd18174efe510bd52631a99jeffhao}
1915250455229aa0cc07bbd18174efe510bd52631a99jeffhao
1916250455229aa0cc07bbd18174efe510bd52631a99jeffhaovoid Thread::VerifyStack() {
1917e66ac79b90a12b01b9d67ee9f7f586e638e67fabjeffhao  UniquePtr<Context> context(Context::Create());
191867054b57d056a2c3892a69efbde28a4189bc17b4Ian Rogers  ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context.get(), VerifyObject,
19190399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers                             Runtime::Current()->GetHeap());
19200399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  mapper.WalkStack();
1921250455229aa0cc07bbd18174efe510bd52631a99jeffhao}
1922250455229aa0cc07bbd18174efe510bd52631a99jeffhao#endif
1923250455229aa0cc07bbd18174efe510bd52631a99jeffhao
192400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers// Set the stack end to that to be used during a stack overflow
192500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::SetStackEndForStackOverflow() {
192600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // During stack overflow we allow use of the full stack
192700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  if (stack_end_ == stack_begin_) {
192800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    DumpStack(std::cerr);
192900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    LOG(FATAL) << "Need to increase kStackOverflowReservedBytes (currently "
193000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers               << kStackOverflowReservedBytes << ")";
193100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
193200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
193300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  stack_end_ = stack_begin_;
193400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers}
193500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
1936330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughesstd::ostream& operator<<(std::ostream& os, const Thread& thread) {
193700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  thread.ShortDump(os);
1938330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes  return os;
1939330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes}
1940330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes
194100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers#ifndef NDEBUG
194200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersvoid Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
194300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  CHECK_EQ(0u, no_thread_suspension_) << last_no_thread_suspension_cause_;
194400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  if (check_locks) {
194500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    bool bad_mutexes_held = false;
194600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    for (int i = kMaxMutexLevel; i >= 0; --i) {
194700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // We expect no locks except the mutator_lock_.
194800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      if (i != kMutatorLock) {
194981d425b0b232962441616f8b14f73620bffef5e5Ian Rogers        BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
195000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers        if (held_mutex != NULL) {
195100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers          LOG(ERROR) << "holding \"" << held_mutex->GetName()
195200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers                  << "\" at point where thread suspension is expected";
1953ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          bad_mutexes_held = true;
1954ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        }
1955ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      }
1956ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    }
195700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    CHECK(!bad_mutexes_held);
1958ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
1959ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
196000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers#endif
1961a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
19628daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes}  // namespace art
1963