blob: c51d45f814ad627611ba40c8793110d55e2beb37 [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
Elliott Hughes2acf36d2012-04-17 13:30:13 -070021#include <signal.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/resource.h>
23#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070024
Carl Shapirob5573532011-07-12 18:22:59 -070025#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070026#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070027#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070028#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070029#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070030
Elliott Hughesa5b897e2011-08-16 11:33:06 -070031#include "class_linker.h"
Brian Carlstromdf143242011-10-10 18:05:34 -070032#include "class_loader.h"
Ian Rogers474b6da2012-09-25 00:20:38 -070033#include "cutils/atomic.h"
34#include "cutils/atomic-inline.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070035#include "debugger.h"
Ian Rogers0c7abda2012-09-19 13:33:42 -070036#include "gc_map.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070037#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070038#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070039#include "monitor.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070040#include "mutex.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070041#include "oat/runtime/context.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070042#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080043#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050044#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070045#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070046#include "runtime_support.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070047#include "scoped_thread_state_change.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070048#include "ScopedLocalRef.h"
Ian Rogers1f539342012-10-03 21:09:42 -070049#include "sirt_ref.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070050#include "gc/space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070051#include "stack.h"
52#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070053#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070054#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070056
57namespace art {
58
59pthread_key_t Thread::pthread_key_self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070060ConditionVariable* Thread::resume_cond_;
Carl Shapirob5573532011-07-12 18:22:59 -070061
Elliott Hughes7dc51662012-05-16 14:48:43 -070062static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
63
Ian Rogers5d76c432011-10-31 21:42:49 -070064void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080065 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070066}
67
Elliott Hughes99250ba2012-04-17 11:09:17 -070068#if !defined(__APPLE__)
Elliott Hughes3ea0f422012-04-16 17:01:43 -070069static void UnimplementedEntryPoint() {
70 UNIMPLEMENTED(FATAL);
71}
Elliott Hughes99250ba2012-04-17 11:09:17 -070072#endif
Elliott Hughes3ea0f422012-04-16 17:01:43 -070073
buzbee3ea4ec52011-08-22 17:37:19 -070074void Thread::InitFunctionPointers() {
Elliott Hughes99250ba2012-04-17 11:09:17 -070075#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
Elliott Hughes3ea0f422012-04-16 17:01:43 -070076 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
77 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
78 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
79 for (uintptr_t* it = begin; it != end; ++it) {
80 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
81 }
Elliott Hughes99250ba2012-04-17 11:09:17 -070082#endif
Ian Rogers57b86d42012-03-27 16:05:41 -070083 InitEntryPoints(&entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -070084}
85
86void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
87 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers776ac1f2012-04-13 23:36:36 -070088#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070089 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
Ian Rogers776ac1f2012-04-13 23:36:36 -070090#else
91 UNIMPLEMENTED(FATAL);
92#endif
buzbee3ea4ec52011-08-22 17:37:19 -070093}
94
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070095void Thread::InitTid() {
96 tid_ = ::art::GetTid();
97}
98
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070099void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -0700100 // One thread (us) survived the fork, but we have a new tid so we need to
101 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700102 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700103}
104
Brian Carlstrom78128a62011-09-15 17:21:19 -0700105void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700106 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogers120f1c72012-09-28 17:17:10 -0700107 Runtime* runtime = Runtime::Current();
108 if (runtime == NULL) {
109 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
110 return NULL;
111 }
112 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700113 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
114 // after self->Init().
115 MutexLock mu(NULL, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700116 // Check that if we got here we cannot be shutting down (as shutdown should never have started
117 // while threads are being born).
118 CHECK(!runtime->IsShuttingDown());
119 self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
120 Runtime::Current()->EndThreadBirth();
121 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700122 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700123 ScopedObjectAccess soa(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700124 {
Ian Rogers1f539342012-10-03 21:09:42 -0700125 SirtRef<String> thread_name(self, self->GetThreadName(soa));
Ian Rogers365c1022012-06-22 15:05:28 -0700126 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
127 }
Ian Rogers365c1022012-06-22 15:05:28 -0700128 Dbg::PostThreadStart(self);
129
130 // Invoke the 'run' method of our java.lang.Thread.
131 CHECK(self->peer_ != NULL);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700132 Object* receiver = soa.Decode<Object*>(self->peer_);
Ian Rogers365c1022012-06-22 15:05:28 -0700133 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700134 AbstractMethod* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Ian Rogers365c1022012-06-22 15:05:28 -0700135 m->Invoke(self, receiver, NULL, NULL);
Elliott Hughes47179f72011-10-27 16:44:39 -0700136 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 // Detach and delete self.
138 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700139
Carl Shapirob5573532011-07-12 18:22:59 -0700140 return NULL;
141}
142
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, Object* thread_peer) {
144 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
145 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetInt(thread_peer)));
146 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
147 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700148 if (kIsDebugBuild) {
149 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
150 if (result != NULL && !result->IsSuspended()) {
151 Locks::thread_list_lock_->AssertHeld(soa.Self());
152 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153 }
154 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800155}
156
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
158 return FromManagedThread(soa, soa.Decode<Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700159}
160
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700161static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700162 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700163 if (stack_size == 0) {
164 stack_size = Runtime::Current()->GetDefaultStackSize();
165 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700166
Brian Carlstrom6414a972012-04-14 14:20:04 -0700167 // Dalvik used the bionic pthread default stack size for native threads,
168 // so include that here to support apps that expect large native stacks.
169 stack_size += 1 * MB;
170
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700171 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
172 if (stack_size < PTHREAD_STACK_MIN) {
173 stack_size = PTHREAD_STACK_MIN;
174 }
175
176 // It's likely that callers are trying to ensure they have at least a certain amount of
177 // stack space, so we should add our reserved space on top of what they requested, rather
178 // than implicitly take it away from them.
179 stack_size += Thread::kStackOverflowReservedBytes;
180
181 // Some systems require the stack size to be a multiple of the system page size, so round up.
182 stack_size = RoundUp(stack_size, kPageSize);
183
184 return stack_size;
185}
186
Elliott Hughesd8af1592012-04-16 20:40:15 -0700187static void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
188 if (sigaltstack(new_stack, old_stack) == -1) {
189 PLOG(FATAL) << "sigaltstack failed";
190 }
191}
192
193static void SetUpAlternateSignalStack() {
194 // Create and set an alternate signal stack.
195 stack_t ss;
196 ss.ss_sp = new uint8_t[SIGSTKSZ];
197 ss.ss_size = SIGSTKSZ;
198 ss.ss_flags = 0;
199 CHECK(ss.ss_sp != NULL);
200 SigAltStack(&ss, NULL);
201
202 // Double-check that it worked.
203 ss.ss_sp = NULL;
204 SigAltStack(NULL, &ss);
205 VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
206}
207
208static void TearDownAlternateSignalStack() {
209 // Get the pointer so we can free the memory.
210 stack_t ss;
211 SigAltStack(NULL, &ss);
212 uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
213
214 // Tell the kernel to stop using it.
215 ss.ss_sp = NULL;
216 ss.ss_flags = SS_DISABLE;
Elliott Hughes4c5231d2012-04-18 16:54:31 -0700217 ss.ss_size = SIGSTKSZ; // Avoid ENOMEM failure with Mac OS' buggy libc.
Elliott Hughesd8af1592012-04-16 20:40:15 -0700218 SigAltStack(&ss, NULL);
219
220 // Free it.
221 delete[] allocated_signal_stack;
222}
223
Ian Rogers120f1c72012-09-28 17:17:10 -0700224void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700225 CHECK(java_peer != NULL);
Ian Rogers120f1c72012-09-28 17:17:10 -0700226 Thread* self = static_cast<JNIEnvExt*>(env)->self;
227 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700228
Ian Rogers120f1c72012-09-28 17:17:10 -0700229 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
230 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700231 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700232 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
233 if (runtime->IsShuttingDown()) {
234 thread_start_during_shutdown = true;
235 } else {
236 runtime->StartThreadBirth();
237 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700238 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700239 if (thread_start_during_shutdown) {
240 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
241 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
242 return;
243 }
244
245 Thread* child_thread = new Thread(is_daemon);
246 // Use global JNI ref to hold peer live while child thread starts.
247 child_thread->peer_ = env->NewGlobalRef(java_peer);
248 stack_size = FixStackSize(stack_size);
249
250 // Thread.start is synchronized, so we know that vmData is 0, and know that we're not racing to
251 // assign it.
252 env->SetIntField(java_peer, WellKnownClasses::java_lang_Thread_vmData,
253 reinterpret_cast<jint>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700254
255 pthread_t new_pthread;
256 pthread_attr_t attr;
257 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
258 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
259 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
Ian Rogers120f1c72012-09-28 17:17:10 -0700260 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, child_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700261 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
262
Ian Rogers120f1c72012-09-28 17:17:10 -0700263 if (pthread_create_result != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700264 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700265 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700266 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
267 runtime->EndThreadBirth();
268 }
269 // Manually delete the global reference since Thread::Init will not have been run.
270 env->DeleteGlobalRef(child_thread->peer_);
271 child_thread->peer_ = NULL;
272 delete child_thread;
273 child_thread = NULL;
274 // TODO: remove from thread group?
275 env->SetIntField(java_peer, WellKnownClasses::java_lang_Thread_vmData, 0);
276 {
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700277 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
278 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
Ian Rogers120f1c72012-09-28 17:17:10 -0700279 ScopedObjectAccess soa(env);
280 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700281 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700282 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700283}
284
Ian Rogers120f1c72012-09-28 17:17:10 -0700285void Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700286 // This function does all the initialization that must be run by the native thread it applies to.
287 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
288 // we can handshake with the corresponding native thread when it's ready.) Check this native
289 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700290 CHECK(Thread::Current() == NULL);
Elliott Hughesd8af1592012-04-16 20:40:15 -0700291 SetUpAlternateSignalStack();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700292 InitCpu();
293 InitFunctionPointers();
Ian Rogers5d76c432011-10-31 21:42:49 -0700294 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700295 InitTid();
Ian Rogers50ffee22012-11-20 11:47:44 -0800296 if (Runtime::Current()->InterpreterOnly()) {
297 AtomicSetFlag(kEnterInterpreter);
298 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700299 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
300 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
Elliott Hughes0d39c122012-06-06 16:41:17 -0700301 pthread_self_ = pthread_self();
Ian Rogers120f1c72012-09-28 17:17:10 -0700302 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
303 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700304
Ian Rogers120f1c72012-09-28 17:17:10 -0700305 thin_lock_id_ = thread_list->AllocThreadId();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700306 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700307
Ian Rogers120f1c72012-09-28 17:17:10 -0700308 jni_env_ = new JNIEnvExt(this, java_vm);
309 thread_list->Register(this);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700310}
311
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800312Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group,
313 bool create_peer) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700314 Thread* self;
315 Runtime* runtime = Runtime::Current();
316 if (runtime == NULL) {
317 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
318 return NULL;
319 }
320 {
321 MutexLock mu(NULL, *Locks::runtime_shutdown_lock_);
322 if (runtime->IsShuttingDown()) {
323 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
324 return NULL;
325 } else {
326 Runtime::Current()->StartThreadBirth();
327 self = new Thread(as_daemon);
328 self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
329 Runtime::Current()->EndThreadBirth();
330 }
331 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700332
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700333 CHECK_NE(self->GetState(), kRunnable);
334 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700335
Elliott Hughescac6cc72011-11-03 20:31:21 -0700336 // If we're the main thread, ClassLinker won't be created until after we're attached,
337 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800338 // In the compiler, all threads need this hack, because no-one's going to be getting
339 // a native peer!
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800340 if (create_peer) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700341 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800342 } else {
343 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700344 if (thread_name != NULL) {
345 self->name_->assign(thread_name);
346 ::art::SetThreadName(thread_name);
347 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700348 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700349
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700350 return self;
351}
352
Ian Rogers365c1022012-06-22 15:05:28 -0700353void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
354 Runtime* runtime = Runtime::Current();
355 CHECK(runtime->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700356 JNIEnv* env = jni_env_;
357
Elliott Hughes462c9442012-03-23 18:47:50 -0700358 if (thread_group == NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -0700359 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700360 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700361 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700362 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700363 jboolean thread_is_daemon = as_daemon;
364
Elliott Hugheseac76672012-05-24 21:56:51 -0700365 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700366 if (peer.get() == NULL) {
367 CHECK(IsExceptionPending());
368 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700369 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700370 peer_ = env->NewGlobalRef(peer.get());
Elliott Hugheseac76672012-05-24 21:56:51 -0700371 env->CallNonvirtualVoidMethod(peer.get(),
372 WellKnownClasses::java_lang_Thread,
373 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700374 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700375 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700376
Ian Rogers120f1c72012-09-28 17:17:10 -0700377 Thread* self = this;
378 DCHECK_EQ(self, Thread::Current());
379 jni_env_->SetIntField(peer.get(), WellKnownClasses::java_lang_Thread_vmData,
380 reinterpret_cast<jint>(self));
381
382 ScopedObjectAccess soa(self);
Ian Rogers1f539342012-10-03 21:09:42 -0700383 SirtRef<String> peer_thread_name(soa.Self(), GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700384 if (peer_thread_name.get() == NULL) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700385 Object* native_peer = soa.Decode<Object*>(peer.get());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700386 // The Thread constructor should have set the Thread.name to a
387 // non-null value. However, because we can run without code
388 // available (in the compiler, in tests), we manually assign the
389 // fields the constructor should have set.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700390 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
391 SetBoolean(native_peer, thread_is_daemon);
392 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
393 SetObject(native_peer, soa.Decode<Object*>(thread_group));
394 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
395 SetObject(native_peer, soa.Decode<Object*>(thread_name.get()));
396 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
397 SetInt(native_peer, thread_priority);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700398 peer_thread_name.reset(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700399 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700400 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Brian Carlstrom00fae582011-10-28 01:16:28 -0700401 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800402 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700403 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700404}
405
Elliott Hughes899e7892012-01-24 14:57:32 -0800406void Thread::SetThreadName(const char* name) {
407 name_->assign(name);
408 ::art::SetThreadName(name);
409 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
410}
411
Elliott Hughesbe759c62011-09-08 19:38:21 -0700412void Thread::InitStackHwm() {
Elliott Hughese1884192012-04-23 12:38:15 -0700413 void* stack_base;
414 size_t stack_size;
Ian Rogers120f1c72012-09-28 17:17:10 -0700415 GetThreadStack(pthread_self_, stack_base, stack_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700416
417 // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
Elliott Hughese1884192012-04-23 12:38:15 -0700418 VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
419
420 stack_begin_ = reinterpret_cast<byte*>(stack_base);
421 stack_size_ = stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700422
Ian Rogers932746a2011-09-22 18:57:50 -0700423 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800424 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700425 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700426
Elliott Hughese1884192012-04-23 12:38:15 -0700427 // TODO: move this into the Linux GetThreadStack implementation.
428#if !defined(__APPLE__)
Elliott Hughes36ecb782012-04-17 16:55:45 -0700429 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
430 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
431 // will be broken because we'll die long before we get close to 2GB.
Ian Rogers120f1c72012-09-28 17:17:10 -0700432 bool is_main_thread = (::art::GetTid() == getpid());
433 if (is_main_thread) {
Elliott Hughes36ecb782012-04-17 16:55:45 -0700434 rlimit stack_limit;
435 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
436 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
437 }
438 if (stack_limit.rlim_cur == RLIM_INFINITY) {
439 // Find the default stack size for new threads...
440 pthread_attr_t default_attributes;
441 size_t default_stack_size;
442 CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
443 CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
444 "default stack size query");
445 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
446
447 // ...and use that as our limit.
448 size_t old_stack_size = stack_size_;
449 stack_size_ = default_stack_size;
450 stack_begin_ += (old_stack_size - stack_size_);
Elliott Hughesfaf4ba02012-05-02 16:12:19 -0700451 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
452 << " to " << PrettySize(stack_size_)
453 << " with base " << reinterpret_cast<void*>(stack_begin_);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700454 }
455 }
Elliott Hughese1884192012-04-23 12:38:15 -0700456#endif
Elliott Hughes36ecb782012-04-17 16:55:45 -0700457
Ian Rogers932746a2011-09-22 18:57:50 -0700458 // Set stack_end_ to the bottom of the stack saving space of stack overflows
459 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700460
461 // Sanity check.
462 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700463 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700464}
465
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466void Thread::ShortDump(std::ostream& os) const {
467 os << "Thread[";
468 if (GetThinLockId() != 0) {
469 // If we're in kStarting, we won't have a thin lock id or tid yet.
470 os << GetThinLockId()
471 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700472 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700473 os << GetState()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474 << ",Thread*=" << this
475 << ",peer=" << peer_
476 << ",\"" << *name_ << "\""
477 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700478}
479
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480void Thread::Dump(std::ostream& os) const {
481 DumpState(os);
482 DumpStack(os);
483}
484
485String* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
486 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700487 Object* native_peer = soa.Decode<Object*>(peer_);
488 return (peer_ != NULL) ? reinterpret_cast<String*>(f->GetObject(native_peer)) : NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700489}
490
Elliott Hughesffb465f2012-03-01 18:46:05 -0800491void Thread::GetThreadName(std::string& name) const {
492 name.assign(*name_);
493}
494
Ian Rogers474b6da2012-09-25 00:20:38 -0700495void Thread::AtomicSetFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700496 android_atomic_or(flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700497}
498
499void Thread::AtomicClearFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700500 android_atomic_and(-1 ^ flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700501}
502
503ThreadState Thread::SetState(ThreadState new_state) {
504 // Cannot use this code to change into Runnable as changing to Runnable should fail if
505 // old_state_and_flags.suspend_request is true.
506 DCHECK_NE(new_state, kRunnable);
507 DCHECK_EQ(this, Thread::Current());
Ian Rogers30e173f2012-09-26 14:35:03 -0700508 union StateAndFlags old_state_and_flags = state_and_flags_;
509 state_and_flags_.as_struct.state = new_state;
510 return static_cast<ThreadState>(old_state_and_flags.as_struct.state);
Ian Rogers474b6da2012-09-25 00:20:38 -0700511}
512
Ian Rogers01ae5802012-09-28 16:14:01 -0700513// Attempt to rectify locks so that we dump thread list with required locks before exiting.
514static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -0700515 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -0700516 Locks::thread_suspend_count_lock_->Unlock(self);
517 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
518 Locks::mutator_lock_->SharedTryLock(self);
519 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
520 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
521 }
522 }
523 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
524 Locks::thread_list_lock_->TryLock(self);
525 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
526 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
527 }
528 }
529 std::ostringstream ss;
530 Runtime::Current()->GetThreadList()->DumpLocked(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -0700531 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -0700532}
533
534void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
536 << delta << " " << debug_suspend_count_ << " " << this;
537 DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
Ian Rogers01ae5802012-09-28 16:14:01 -0700538 Locks::thread_suspend_count_lock_->AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700539
Ian Rogers01ae5802012-09-28 16:14:01 -0700540 if (UNLIKELY(delta < 0 && suspend_count_ <= 0)) {
541 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 return;
543 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700544
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700545 suspend_count_ += delta;
546 if (for_debugger) {
547 debug_suspend_count_ += delta;
548 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700549
Ian Rogers474b6da2012-09-25 00:20:38 -0700550 if (suspend_count_ == 0) {
551 AtomicClearFlag(kSuspendRequest);
552 } else {
553 AtomicSetFlag(kSuspendRequest);
554 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700555}
556
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700557bool Thread::RequestCheckpoint(Closure* function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700558 CHECK(!ReadFlag(kCheckpointRequest)) << "Already have a pending checkpoint request";
559 checkpoint_function_ = function;
560 union StateAndFlags old_state_and_flags = state_and_flags_;
561 // We must be runnable to request a checkpoint.
562 old_state_and_flags.as_struct.state = kRunnable;
563 union StateAndFlags new_state_and_flags = old_state_and_flags;
564 new_state_and_flags.as_struct.flags |= kCheckpointRequest;
565 int succeeded = android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
566 &state_and_flags_.as_int);
567 return succeeded == 0;
568}
569
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700570void Thread::FullSuspendCheck() {
571 VLOG(threads) << this << " self-suspending";
572 // Make thread appear suspended to other threads, release mutator_lock_.
573 TransitionFromRunnableToSuspended(kSuspended);
574 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
575 TransitionFromSuspendedToRunnable();
576 VLOG(threads) << this << " self-reviving";
577}
578
579void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
580 AssertThreadSuspensionIsAllowable();
Ian Rogers474b6da2012-09-25 00:20:38 -0700581 DCHECK_NE(new_state, kRunnable);
582 DCHECK_EQ(this, Thread::Current());
Ian Rogersc747cff2012-08-31 18:20:08 -0700583 // Change to non-runnable state, thereby appearing suspended to the system.
Ian Rogers474b6da2012-09-25 00:20:38 -0700584 DCHECK_EQ(GetState(), kRunnable);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700585 union StateAndFlags old_state_and_flags;
586 union StateAndFlags new_state_and_flags;
587 do {
588 old_state_and_flags = state_and_flags_;
589 // Copy over flags and try to clear the checkpoint bit if it is set.
590 new_state_and_flags.as_struct.flags = old_state_and_flags.as_struct.flags & ~kCheckpointRequest;
591 new_state_and_flags.as_struct.state = new_state;
592 } while (android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
593 &state_and_flags_.as_int) != 0);
594 // If we toggled the checkpoint flag we must have cleared it.
595 uint16_t flag_change = new_state_and_flags.as_struct.flags ^ old_state_and_flags.as_struct.flags;
596 if ((flag_change & kCheckpointRequest) != 0) {
597 RunCheckpointFunction();
598 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599 // Release share on mutator_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -0700600 Locks::mutator_lock_->SharedUnlock(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700601}
602
603ThreadState Thread::TransitionFromSuspendedToRunnable() {
604 bool done = false;
Ian Rogers01ae5802012-09-28 16:14:01 -0700605 union StateAndFlags old_state_and_flags = state_and_flags_;
606 int16_t old_state = old_state_and_flags.as_struct.state;
607 DCHECK_NE(static_cast<ThreadState>(old_state), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 do {
Ian Rogers81d425b2012-09-27 16:03:43 -0700609 Locks::mutator_lock_->AssertNotHeld(this); // Otherwise we starve GC..
Ian Rogers01ae5802012-09-28 16:14:01 -0700610 old_state_and_flags = state_and_flags_;
611 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
612 if ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700613 // Wait while our suspend count is non-zero.
Ian Rogers81d425b2012-09-27 16:03:43 -0700614 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
Ian Rogers01ae5802012-09-28 16:14:01 -0700615 old_state_and_flags = state_and_flags_;
616 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
617 while ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700618 // Re-check when Thread::resume_cond_ is notified.
Ian Rogersc604d732012-10-14 16:09:54 -0700619 Thread::resume_cond_->Wait(this);
Ian Rogers01ae5802012-09-28 16:14:01 -0700620 old_state_and_flags = state_and_flags_;
621 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700623 DCHECK_EQ(GetSuspendCount(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700624 }
625 // Re-acquire shared mutator_lock_ access.
Ian Rogers81d425b2012-09-27 16:03:43 -0700626 Locks::mutator_lock_->SharedLock(this);
Ian Rogers474b6da2012-09-25 00:20:38 -0700627 // Atomically change from suspended to runnable if no suspend request pending.
Ian Rogers01ae5802012-09-28 16:14:01 -0700628 old_state_and_flags = state_and_flags_;
629 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
630 if ((old_state_and_flags.as_struct.flags & kSuspendRequest) == 0) {
631 union StateAndFlags new_state_and_flags = old_state_and_flags;
632 new_state_and_flags.as_struct.state = kRunnable;
633 done = android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
Ian Rogers81d425b2012-09-27 16:03:43 -0700634 &state_and_flags_.as_int)
Ian Rogers474b6da2012-09-25 00:20:38 -0700635 == 0;
636 }
637 if (!done) {
638 // Failed to transition to Runnable. Release shared mutator_lock_ access and try again.
Ian Rogers81d425b2012-09-27 16:03:43 -0700639 Locks::mutator_lock_->SharedUnlock(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700640 }
641 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700642 return static_cast<ThreadState>(old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700643}
644
645Thread* Thread::SuspendForDebugger(jobject peer, bool request_suspension, bool* timeout) {
646 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
647 useconds_t total_delay_us = 0;
648 useconds_t delay_us = 0;
649 bool did_suspend_request = false;
650 *timeout = false;
651 while (true) {
652 Thread* thread;
653 {
654 ScopedObjectAccess soa(Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700655 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656 thread = Thread::FromManagedThread(soa, peer);
657 if (thread == NULL) {
658 LOG(WARNING) << "No such thread for suspend: " << peer;
659 return NULL;
660 }
661 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700662 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663 if (request_suspension) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700664 thread->ModifySuspendCount(soa.Self(), +1, true /* for_debugger */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700665 request_suspension = false;
666 did_suspend_request = true;
667 }
668 // IsSuspended on the current thread will fail as the current thread is changed into
669 // Runnable above. As the suspend count is now raised if this is the current thread
670 // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
671 // to just explicitly handle the current thread in the callers to this code.
672 CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
673 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
674 // count, or else we've waited and it has self suspended) or is the current thread, we're
675 // done.
676 if (thread->IsSuspended()) {
677 return thread;
678 }
679 if (total_delay_us >= kTimeoutUs) {
680 LOG(ERROR) << "Thread suspension timed out: " << peer;
681 if (did_suspend_request) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700682 thread->ModifySuspendCount(soa.Self(), -1, true /* for_debugger */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700683 }
684 *timeout = true;
685 return NULL;
686 }
687 }
688 // Release locks and come out of runnable state.
689 }
690 for (int i = kMaxMutexLevel; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700691 BaseMutex* held_mutex = Thread::Current()->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 if (held_mutex != NULL) {
693 LOG(FATAL) << "Holding " << held_mutex->GetName()
694 << " while sleeping for thread suspension";
695 }
696 }
697 {
698 useconds_t new_delay_us = delay_us * 2;
699 CHECK_GE(new_delay_us, delay_us);
700 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
701 delay_us = new_delay_us;
702 }
703 }
704 if (delay_us == 0) {
705 sched_yield();
706 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
707 delay_us = 500;
708 } else {
709 usleep(delay_us);
710 total_delay_us += delay_us;
711 }
712 }
713}
714
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700715void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700716 std::string group_name;
717 int priority;
718 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700719 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700720
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700721 if (thread != NULL && thread->peer_ != NULL) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700722 ScopedObjectAccess soa(self);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700723 Object* native_peer = soa.Decode<Object*>(thread->peer_);
724 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(native_peer);
725 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(native_peer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700726
Ian Rogers120f1c72012-09-28 17:17:10 -0700727 Object* thread_group =
728 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(native_peer);
729
Elliott Hughesd369bb72011-09-12 14:41:14 -0700730 if (thread_group != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700731 Field* group_name_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700732 String* group_name_string = reinterpret_cast<String*>(group_name_field->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700733 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
734 }
735 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700736 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700737 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700738
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700739 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700740 if (scheduler_group_name.empty()) {
741 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700742 }
743
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700744 if (thread != NULL) {
745 os << '"' << *thread->name_ << '"';
746 if (is_daemon) {
747 os << " daemon";
748 }
749 os << " prio=" << priority
750 << " tid=" << thread->GetThinLockId()
751 << " " << thread->GetState() << "\n";
752 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700753 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700754 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700755 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700756 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700757
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700758 if (thread != NULL) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700759 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700760 os << " | group=\"" << group_name << "\""
761 << " sCount=" << thread->suspend_count_
762 << " dsCount=" << thread->debug_suspend_count_
763 << " obj=" << reinterpret_cast<void*>(thread->peer_)
764 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
765 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700766
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700767 os << " | sysTid=" << tid
768 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700769 << " cgrp=" << scheduler_group_name;
770 if (thread != NULL) {
771 int policy;
772 sched_param sp;
773 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
774 os << " sched=" << policy << "/" << sp.sched_priority
775 << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
776 }
777 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700778
779 // Grab the scheduler stats for this thread.
780 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700781 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700782 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
783 } else {
784 scheduler_stats = "0 0 0";
785 }
786
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700787 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700788 int utime = 0;
789 int stime = 0;
790 int task_cpu = 0;
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700791 GetTaskStats(tid, native_thread_state, utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700792
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700793 os << " | state=" << native_thread_state
794 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700795 << " utm=" << utime
796 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700797 << " core=" << task_cpu
798 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
799 if (thread != NULL) {
800 os << " | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
801 << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
802 }
803}
804
805void Thread::DumpState(std::ostream& os) const {
806 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700807}
808
Ian Rogers0399dde2012-06-06 17:09:28 -0700809struct StackDumpVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700810 StackDumpVisitor(std::ostream& os, const Thread* thread, Context* context, bool can_allocate)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700811 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -0800812 : StackVisitor(thread->GetManagedStack(), thread->GetInstrumentationStack(), context),
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700813 os(os), thread(thread), can_allocate(can_allocate),
814 last_method(NULL), last_line_number(0), repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700815 }
816
Ian Rogersbdb03912011-09-14 00:55:44 -0700817 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700818 if (frame_count == 0) {
819 os << " (no managed stack frames)\n";
820 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700821 }
822
Ian Rogersb726dcb2012-09-05 08:57:23 -0700823 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700824 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700825 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700826 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700827 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700828 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700829 Class* c = m->GetDeclaringClass();
Ian Rogersb861dc02011-11-14 17:00:05 -0800830 const DexCache* dex_cache = c->GetDexCache();
831 int line_number = -1;
832 if (dex_cache != NULL) { // be tolerant of bad input
Ian Rogers4445a7e2012-10-05 17:19:13 -0700833 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -0700834 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Ian Rogersb861dc02011-11-14 17:00:05 -0800835 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700836 if (line_number == last_line_number && last_method == m) {
837 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700838 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700839 if (repetition_count >= kMaxRepetition) {
840 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
841 }
842 repetition_count = 0;
843 last_line_number = line_number;
844 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700845 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700846 if (repetition_count < kMaxRepetition) {
847 os << " at " << PrettyMethod(m, false);
848 if (m->IsNative()) {
849 os << "(Native method)";
850 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800851 mh.ChangeMethod(m);
852 const char* source_file(mh.GetDeclaringClassSourceFile());
853 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700854 << ":" << line_number << ")";
855 }
856 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700857 if (frame_count == 0) {
858 Monitor::DescribeWait(os, thread);
859 }
860 if (can_allocate) {
861 Monitor::DescribeLocks(os, this);
862 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700863 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700864
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700865 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700866 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700867 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700868 std::ostream& os;
869 const Thread* thread;
870 bool can_allocate;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800871 MethodHelper mh;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700872 AbstractMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700873 int last_line_number;
874 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700875 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700876};
877
Elliott Hughesd92bec42011-09-02 17:04:36 -0700878void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800879 // If we're currently in native code, dump that stack before dumping the managed stack.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700880 if (GetState() == kNative) {
Elliott Hughes46e251b2012-05-22 15:10:45 -0700881 DumpKernelStack(os, GetTid(), " kernel: ", false);
882 DumpNativeStack(os, GetTid(), " native: ", false);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800883 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700884 UniquePtr<Context> context(Context::Create());
885 StackDumpVisitor dumper(os, this, context.get(), !throwing_OutOfMemoryError_);
Ian Rogers0399dde2012-06-06 17:09:28 -0700886 dumper.WalkStack();
Elliott Hughese27955c2011-08-26 15:21:24 -0700887}
888
Elliott Hughesbe759c62011-09-08 19:38:21 -0700889void Thread::ThreadExitCallback(void* arg) {
890 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700891 if (self->thread_exit_check_count_ == 0) {
892 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
893 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
894 self->thread_exit_check_count_ = 1;
895 } else {
896 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
897 }
Carl Shapirob5573532011-07-12 18:22:59 -0700898}
899
Elliott Hughesbe759c62011-09-08 19:38:21 -0700900void Thread::Startup() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700901 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700902 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_); // Keep GCC happy.
Ian Rogersc604d732012-10-14 16:09:54 -0700903 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
904 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700905 }
906
Carl Shapirob5573532011-07-12 18:22:59 -0700907 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700908 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700909
910 // Double-check the TLS slot allocation.
911 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800912 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700913 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700914}
Carl Shapirob5573532011-07-12 18:22:59 -0700915
Elliott Hughes038a8062011-09-18 14:12:41 -0700916void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -0700917 Runtime* runtime = Runtime::Current();
918 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700919
Elliott Hughes01158d72011-09-19 19:47:10 -0700920 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700921 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700922 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500923
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700924 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700925}
926
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700927void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700928 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700929}
930
Ian Rogers52673ff2012-06-27 23:25:34 -0700931Thread::Thread(bool daemon)
Ian Rogers0399dde2012-06-06 17:09:28 -0700932 : suspend_count_(0),
933 card_table_(NULL),
934 exception_(NULL),
935 stack_end_(NULL),
936 managed_stack_(),
937 jni_env_(NULL),
938 self_(NULL),
Elliott Hughes47179f72011-10-27 16:44:39 -0700939 peer_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700940 stack_begin_(NULL),
941 stack_size_(0),
942 thin_lock_id_(0),
943 tid_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700944 wait_mutex_(new Mutex("a thread wait mutex")),
Ian Rogersc604d732012-10-14 16:09:54 -0700945 wait_cond_(new ConditionVariable("a thread wait condition variable", *wait_mutex_)),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700946 wait_monitor_(NULL),
947 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700948 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700949 monitor_enter_object_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700950 top_sirt_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700951 runtime_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700952 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700953 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700954 throwing_OutOfMemoryError_(false),
Ian Rogers0399dde2012-06-06 17:09:28 -0700955 debug_suspend_count_(0),
jeffhaoe343b762011-12-05 16:36:44 -0800956 debug_invoke_req_(new DebugInvokeReq),
jeffhao725a9572012-11-13 18:20:12 -0800957 instrumentation_stack_(new std::vector<InstrumentationStackFrame>),
Ian Rogers0399dde2012-06-06 17:09:28 -0700958 name_(new std::string(kThreadNameDuringStartup)),
Ian Rogers52673ff2012-06-27 23:25:34 -0700959 daemon_(daemon),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700960 pthread_self_(0),
Ian Rogers52673ff2012-06-27 23:25:34 -0700961 no_thread_suspension_(0),
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700962 last_no_thread_suspension_cause_(NULL),
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700963 checkpoint_function_(0),
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700964 thread_exit_check_count_(0) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700965 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Ian Rogers30e173f2012-09-26 14:35:03 -0700966 state_and_flags_.as_struct.flags = 0;
967 state_and_flags_.as_struct.state = kNative;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800968 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700969}
970
Elliott Hughes7dc51662012-05-16 14:48:43 -0700971bool Thread::IsStillStarting() const {
972 // You might think you can check whether the state is kStarting, but for much of thread startup,
973 // the thread might also be in kVmWait.
974 // You might think you can check whether the peer is NULL, but the peer is actually created and
975 // assigned fairly early on, and needs to be.
976 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
977 // this thread _ever_ entered kRunnable".
978 return (*name_ == kThreadNameDuringStartup);
979}
980
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700981void Thread::AssertNoPendingException() const {
982 if (UNLIKELY(IsExceptionPending())) {
983 ScopedObjectAccess soa(Thread::Current());
984 Throwable* exception = GetException();
985 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
986 }
987}
988
989static void MonitorExitVisitor(const Object* object, void* arg) NO_THREAD_SAFETY_ANALYSIS {
990 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700991 Object* entered_monitor = const_cast<Object*>(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700992 if (self->HoldsLock(entered_monitor)) {
993 LOG(WARNING) << "Calling MonitorExit on object "
994 << object << " (" << PrettyTypeOf(object) << ")"
995 << " left locked by native thread "
996 << *Thread::Current() << " which is detaching";
997 entered_monitor->MonitorExit(self);
998 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700999}
1000
Elliott Hughesc0f09332012-03-26 13:27:06 -07001001void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07001002 Thread* self = this;
1003 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001004
Elliott Hughes93e74e82011-09-13 11:07:03 -07001005 if (peer_ != NULL) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001006 // We may need to call user-supplied managed code, do this before final clean-up.
1007 HandleUncaughtExceptions();
1008 RemoveFromThreadGroup();
Elliott Hughes534da072012-03-27 15:17:42 -07001009
Elliott Hughes29f27422011-09-18 16:02:18 -07001010 // this.vmData = 0;
Ian Rogers120f1c72012-09-28 17:17:10 -07001011 jni_env_->SetIntField(peer_, WellKnownClasses::java_lang_Thread_vmData, 0);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001012
Ian Rogers120f1c72012-09-28 17:17:10 -07001013 {
1014 ScopedObjectAccess soa(self);
1015 Dbg::PostThreadDeath(self);
1016 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001017
Elliott Hughes29f27422011-09-18 16:02:18 -07001018 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1019 // object. Signal anyone who is waiting.
Ian Rogers120f1c72012-09-28 17:17:10 -07001020 ScopedLocalRef<jobject> lock(jni_env_,
1021 jni_env_->GetObjectField(peer_,
1022 WellKnownClasses::java_lang_Thread_lock));
Elliott Hughes038a8062011-09-18 14:12:41 -07001023 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Ian Rogers120f1c72012-09-28 17:17:10 -07001024 if (lock.get() != NULL) {
1025 jni_env_->MonitorEnter(lock.get());
1026 jni_env_->CallVoidMethod(lock.get(), WellKnownClasses::java_lang_Object_notify);
1027 jni_env_->MonitorExit(lock.get());
Elliott Hughes5f791332011-09-15 17:45:30 -07001028 }
1029 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001030
1031 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
1032 if (jni_env_ != NULL) {
1033 jni_env_->monitors.VisitRoots(MonitorExitVisitor, self);
1034 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001035}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001036
Elliott Hughesc0f09332012-03-26 13:27:06 -07001037Thread::~Thread() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001038 if (jni_env_ != NULL && peer_ != NULL) {
1039 // If pthread_create fails we don't have a jni env here.
1040 jni_env_->DeleteGlobalRef(peer_);
1041 }
1042 peer_ = NULL;
1043
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001044 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001045 jni_env_ = NULL;
1046
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001047 CHECK_NE(GetState(), kRunnable);
1048 // We may be deleting a still born thread.
1049 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001050
1051 delete wait_cond_;
1052 delete wait_mutex_;
1053
Ian Rogers776ac1f2012-04-13 23:36:36 -07001054#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -07001055 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -07001056#endif
Elliott Hughes475fc232011-10-25 15:00:35 -07001057
1058 delete debug_invoke_req_;
jeffhao725a9572012-11-13 18:20:12 -08001059 delete instrumentation_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -08001060 delete name_;
Elliott Hughesd8af1592012-04-16 20:40:15 -07001061
1062 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001063}
1064
Ian Rogers120f1c72012-09-28 17:17:10 -07001065void Thread::HandleUncaughtExceptions() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001066 if (!IsExceptionPending()) {
1067 return;
1068 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001069
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001070 // Get and clear the exception.
Ian Rogers120f1c72012-09-28 17:17:10 -07001071 ScopedLocalRef<jthrowable> exception(jni_env_, jni_env_->ExceptionOccurred());
1072 jni_env_->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001073
1074 // If the thread has its own handler, use that.
Ian Rogers120f1c72012-09-28 17:17:10 -07001075 ScopedLocalRef<jobject> handler(jni_env_,
1076 jni_env_->GetObjectField(peer_,
1077 WellKnownClasses::java_lang_Thread_uncaughtHandler));
1078 if (handler.get() == NULL) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001079 // Otherwise use the thread group's default handler.
Ian Rogers120f1c72012-09-28 17:17:10 -07001080 handler.reset(jni_env_->GetObjectField(peer_, WellKnownClasses::java_lang_Thread_group));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001081 }
1082
1083 // Call the handler.
Ian Rogers120f1c72012-09-28 17:17:10 -07001084 jni_env_->CallVoidMethod(handler.get(),
1085 WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException,
1086 peer_, exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001087
1088 // If the handler threw, clear that exception too.
Ian Rogers120f1c72012-09-28 17:17:10 -07001089 jni_env_->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001090}
1091
Ian Rogers120f1c72012-09-28 17:17:10 -07001092void Thread::RemoveFromThreadGroup() {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001093 // this.group.removeThread(this);
1094 // group can be null if we're in the compiler or a test.
Ian Rogers120f1c72012-09-28 17:17:10 -07001095 ScopedLocalRef<jobject> group(jni_env_,
1096 jni_env_->GetObjectField(peer_,
1097 WellKnownClasses::java_lang_Thread_group));
1098 if (group.get() != NULL) {
1099 jni_env_->CallVoidMethod(group.get(), WellKnownClasses::java_lang_ThreadGroup_removeThread,
1100 peer_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001101 }
1102}
1103
Ian Rogers408f79a2011-08-23 18:22:33 -07001104size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001105 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001106 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001107 count += cur->NumberOfReferences();
1108 }
1109 return count;
1110}
1111
Ian Rogers408f79a2011-08-23 18:22:33 -07001112bool Thread::SirtContains(jobject obj) {
1113 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001114 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1115 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001116 return true;
1117 }
1118 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001119 // JNI code invoked from portable code uses shadow frames rather than the SIRT.
1120 return managed_stack_.ShadowFramesContain(sirt_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001121}
1122
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001123void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001124 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001125 size_t num_refs = cur->NumberOfReferences();
1126 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001127 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001128 if (object != NULL) {
1129 visitor(object, arg);
1130 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001131 }
1132 }
1133}
1134
Ian Rogers408f79a2011-08-23 18:22:33 -07001135Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001136 Locks::mutator_lock_->AssertSharedHeld(this);
Ian Rogers408f79a2011-08-23 18:22:33 -07001137 if (obj == NULL) {
1138 return NULL;
1139 }
1140 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1141 IndirectRefKind kind = GetIndirectRefKind(ref);
1142 Object* result;
1143 switch (kind) {
1144 case kLocal:
1145 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001146 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001147 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001148 break;
1149 }
1150 case kGlobal:
1151 {
1152 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1153 IndirectReferenceTable& globals = vm->globals;
Ian Rogers81d425b2012-09-27 16:03:43 -07001154 MutexLock mu(this, vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001155 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001156 break;
1157 }
1158 case kWeakGlobal:
1159 {
1160 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1161 IndirectReferenceTable& weak_globals = vm->weak_globals;
Ian Rogers81d425b2012-09-27 16:03:43 -07001162 MutexLock mu(this, vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001163 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001164 if (result == kClearedJniWeakGlobal) {
1165 // This is a special case where it's okay to return NULL.
1166 return NULL;
1167 }
1168 break;
1169 }
1170 case kSirtOrInvalid:
1171 default:
1172 // TODO: make stack indirect reference table lookup more efficient
1173 // Check if this is a local reference in the SIRT
Ian Rogers0399dde2012-06-06 17:09:28 -07001174 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001175 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001176 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001177 // Assume an invalid local reference is actually a direct pointer.
1178 result = reinterpret_cast<Object*>(obj);
1179 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001180 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001181 }
1182 }
1183
1184 if (result == NULL) {
Elliott Hughes3f6635a2012-06-19 13:37:49 -07001185 JniAbortF(NULL, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
Elliott Hughesa2501992011-08-26 19:39:54 -07001186 } else {
1187 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001188 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001189 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001190 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001191 return result;
1192}
1193
Ian Rogers81d425b2012-09-27 16:03:43 -07001194// Implements java.lang.Thread.interrupted.
1195bool Thread::Interrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001196 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001197 bool interrupted = interrupted_;
1198 interrupted_ = false;
1199 return interrupted;
1200}
1201
1202// Implements java.lang.Thread.isInterrupted.
1203bool Thread::IsInterrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001204 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001205 return interrupted_;
1206}
1207
1208void Thread::Interrupt() {
Ian Rogersc604d732012-10-14 16:09:54 -07001209 Thread* self = Thread::Current();
1210 MutexLock mu(self, *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001211 if (interrupted_) {
1212 return;
1213 }
1214 interrupted_ = true;
Ian Rogersc604d732012-10-14 16:09:54 -07001215 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001216}
1217
1218void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07001219 Thread* self = Thread::Current();
1220 MutexLock mu(self, *wait_mutex_);
1221 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001222}
1223
Ian Rogersc604d732012-10-14 16:09:54 -07001224void Thread::NotifyLocked(Thread* self) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001225 if (wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -07001226 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001227 }
1228}
1229
Ian Rogers0399dde2012-06-06 17:09:28 -07001230class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001231 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001232 CountStackDepthVisitor(const ManagedStack* stack,
jeffhao725a9572012-11-13 18:20:12 -08001233 const std::vector<InstrumentationStackFrame>* instrumentation_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001235 : StackVisitor(stack, instrumentation_stack, NULL),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001236 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001237
Ian Rogersb726dcb2012-09-05 08:57:23 -07001238 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001239 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001240 // Note we also skip the frame if it doesn't have a method (namely the callee
1241 // save frame)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001242 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001243 if (skipping_ && !m->IsRuntimeMethod() &&
1244 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001245 skipping_ = false;
1246 }
1247 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001248 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001249 ++depth_;
1250 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001251 } else {
1252 ++skip_depth_;
1253 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001254 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001255 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001256
1257 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001258 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001259 }
1260
Elliott Hughes29f27422011-09-18 16:02:18 -07001261 int GetSkipDepth() const {
1262 return skip_depth_;
1263 }
1264
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001265 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001266 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001267 uint32_t skip_depth_;
1268 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001269};
1270
Ian Rogers0399dde2012-06-06 17:09:28 -07001271class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001272 public:
Ian Rogers1f539342012-10-03 21:09:42 -07001273 explicit BuildInternalStackTraceVisitor(Thread* self, const ManagedStack* stack,
jeffhao725a9572012-11-13 18:20:12 -08001274 const std::vector<InstrumentationStackFrame>* instrumentation_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001275 int skip_depth)
jeffhao725a9572012-11-13 18:20:12 -08001276 : StackVisitor(stack, instrumentation_stack, NULL), self_(self),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001277 skip_depth_(skip_depth), count_(0), dex_pc_trace_(NULL), method_trace_(NULL) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001278
Ian Rogers1f539342012-10-03 21:09:42 -07001279 bool Init(int depth)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001280 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001281 // Allocate method trace with an extra slot that will hold the PC trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001282 SirtRef<ObjectArray<Object> >
Ian Rogers1f539342012-10-03 21:09:42 -07001283 method_trace(self_,
Ian Rogers50b35e22012-10-04 10:09:15 -07001284 Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(self_,
1285 depth + 1));
Ian Rogers0399dde2012-06-06 17:09:28 -07001286 if (method_trace.get() == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001287 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001288 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001289 IntArray* dex_pc_trace = IntArray::Alloc(self_, depth);
Ian Rogers0399dde2012-06-06 17:09:28 -07001290 if (dex_pc_trace == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001291 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001292 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001293 // Save PC trace in last element of method trace, also places it into the
1294 // object graph.
Ian Rogers0399dde2012-06-06 17:09:28 -07001295 method_trace->Set(depth, dex_pc_trace);
1296 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001297 const char* last_no_suspend_cause =
Ian Rogers1f539342012-10-03 21:09:42 -07001298 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Ian Rogers52673ff2012-06-27 23:25:34 -07001299 CHECK(last_no_suspend_cause == NULL) << last_no_suspend_cause;
Ian Rogers0399dde2012-06-06 17:09:28 -07001300 method_trace_ = method_trace.get();
1301 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001302 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001303 }
1304
Ian Rogers0399dde2012-06-06 17:09:28 -07001305 virtual ~BuildInternalStackTraceVisitor() {
Ian Rogers52673ff2012-06-27 23:25:34 -07001306 if (method_trace_ != NULL) {
Ian Rogers1f539342012-10-03 21:09:42 -07001307 self_->EndAssertNoThreadSuspension(NULL);
Ian Rogers52673ff2012-06-27 23:25:34 -07001308 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001309 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001310
Ian Rogersb726dcb2012-09-05 08:57:23 -07001311 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001312 if (method_trace_ == NULL || dex_pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001313 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001314 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001315 if (skip_depth_ > 0) {
1316 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001317 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001318 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001319 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001320 if (m->IsRuntimeMethod()) {
1321 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001322 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001323 method_trace_->Set(count_, m);
1324 dex_pc_trace_->Set(count_, GetDexPc());
Ian Rogersaaa20802011-09-11 21:47:37 -07001325 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001326 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001327 }
1328
Ian Rogers0399dde2012-06-06 17:09:28 -07001329 ObjectArray<Object>* GetInternalStackTrace() const {
1330 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001331 }
1332
1333 private:
Ian Rogers1f539342012-10-03 21:09:42 -07001334 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001335 // How many more frames to skip.
1336 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001337 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001338 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001339 // Array of dex PC values.
1340 IntArray* dex_pc_trace_;
1341 // An array of the methods on the stack, the last entry is a reference to the PC trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001342 ObjectArray<Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001343};
1344
Ian Rogers64b6d142012-10-29 16:34:15 -07001345jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessUnchecked& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001346 // Compute depth of stack
jeffhao725a9572012-11-13 18:20:12 -08001347 CountStackDepthVisitor count_visitor(GetManagedStack(), GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001348 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001349 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001350 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001351
Ian Rogers1f539342012-10-03 21:09:42 -07001352 // Build internal stack trace.
jeffhao725a9572012-11-13 18:20:12 -08001353 BuildInternalStackTraceVisitor build_trace_visitor(soa.Self(), GetManagedStack(), GetInstrumentationStack(),
Ian Rogers0399dde2012-06-06 17:09:28 -07001354 skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07001355 if (!build_trace_visitor.Init(depth)) {
1356 return NULL; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08001357 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001358 build_trace_visitor.WalkStack();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001359 return soa.AddLocalReference<jobjectArray>(build_trace_visitor.GetInternalStackTrace());
Ian Rogersaaa20802011-09-11 21:47:37 -07001360}
1361
Elliott Hughes01158d72011-09-19 19:47:10 -07001362jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1363 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001364 // Transition into runnable state to work on Object*/Array*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001365 ScopedObjectAccess soa(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001366 // Decode the internal stack trace into the depth, method trace and PC trace
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001367 ObjectArray<Object>* method_trace = soa.Decode<ObjectArray<Object>*>(internal);
Ian Rogers9074b992011-10-26 17:41:55 -07001368 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001369 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1370
1371 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1372
Elliott Hughes01158d72011-09-19 19:47:10 -07001373 jobjectArray result;
1374 ObjectArray<StackTraceElement>* java_traces;
1375 if (output_array != NULL) {
1376 // Reuse the array we were given.
1377 result = output_array;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001378 java_traces = soa.Decode<ObjectArray<StackTraceElement>*>(output_array);
Elliott Hughes01158d72011-09-19 19:47:10 -07001379 // ...adjusting the number of frames we'll write to not exceed the array length.
1380 depth = std::min(depth, java_traces->GetLength());
1381 } else {
1382 // Create java_trace array and place in local reference table
Ian Rogers50b35e22012-10-04 10:09:15 -07001383 java_traces = class_linker->AllocStackTraceElementArray(soa.Self(), depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001384 if (java_traces == NULL) {
1385 return NULL;
1386 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001387 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001388 }
1389
1390 if (stack_depth != NULL) {
1391 *stack_depth = depth;
1392 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001393
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001394 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001395 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001396 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001397 AbstractMethod* method = down_cast<AbstractMethod*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001398 mh.ChangeMethod(method);
Ian Rogers0399dde2012-06-06 17:09:28 -07001399 uint32_t dex_pc = pc_trace->Get(i);
1400 int32_t line_number = mh.GetLineNumFromDexPC(dex_pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001401 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001402 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001403 const char* descriptor = mh.GetDeclaringClassDescriptor();
1404 CHECK(descriptor != NULL);
1405 std::string class_name(PrettyDescriptor(descriptor));
Ian Rogers1f539342012-10-03 21:09:42 -07001406 SirtRef<String> class_name_object(soa.Self(),
Ian Rogers50b35e22012-10-04 10:09:15 -07001407 String::AllocFromModifiedUtf8(soa.Self(),
1408 class_name.c_str()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001409 if (class_name_object.get() == NULL) {
1410 return NULL;
1411 }
Ian Rogers48601312011-12-07 16:45:19 -08001412 const char* method_name = mh.GetName();
1413 CHECK(method_name != NULL);
Ian Rogers50b35e22012-10-04 10:09:15 -07001414 SirtRef<String> method_name_object(soa.Self(), String::AllocFromModifiedUtf8(soa.Self(),
1415 method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001416 if (method_name_object.get() == NULL) {
1417 return NULL;
1418 }
Ian Rogers48601312011-12-07 16:45:19 -08001419 const char* source_file = mh.GetDeclaringClassSourceFile();
Ian Rogers50b35e22012-10-04 10:09:15 -07001420 SirtRef<String> source_name_object(soa.Self(), String::AllocFromModifiedUtf8(soa.Self(),
1421 source_file));
1422 StackTraceElement* obj = StackTraceElement::Alloc(soa.Self(),
1423 class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001424 method_name_object.get(),
1425 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001426 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001427 if (obj == NULL) {
1428 return NULL;
1429 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001430#ifdef MOVING_GARBAGE_COLLECTOR
1431 // Re-read after potential GC
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001432 java_traces = Decode<ObjectArray<Object>*>(soa.Env(), result);
1433 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(soa.Env(), internal));
Ian Rogersaaa20802011-09-11 21:47:37 -07001434 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1435#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001436 java_traces->Set(i, obj);
1437 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001438 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001439}
1440
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001441void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001442 va_list args;
1443 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001444 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001445 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001446}
1447
1448void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1449 std::string msg;
1450 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001451 ThrowNewException(exception_class_descriptor, msg.c_str());
1452}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001453
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001454void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001455 AssertNoPendingException(); // Callers should either clear or call ThrowNewWrappedException.
Elliott Hughesa4f94742012-05-29 16:28:38 -07001456 ThrowNewWrappedException(exception_class_descriptor, msg);
1457}
1458
1459void Thread::ThrowNewWrappedException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001460 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001461 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001462 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001463 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001464 descriptor.erase(descriptor.length() - 1);
1465
1466 JNIEnv* env = GetJniEnv();
Elliott Hughesa4f94742012-05-29 16:28:38 -07001467 jobject cause = env->ExceptionOccurred();
1468 env->ExceptionClear();
1469
Elliott Hughes726079d2011-10-07 18:43:44 -07001470 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001471 if (exception_class.get() == NULL) {
1472 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1473 << PrettyTypeOf(GetException());
1474 CHECK(IsExceptionPending());
1475 return;
1476 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001477 if (!Runtime::Current()->IsStarted()) {
1478 // Something is trying to throw an exception without a started
1479 // runtime, which is the common case in the compiler. We won't be
1480 // able to invoke the constructor of the exception, so use
1481 // AllocObject which will not invoke a constructor.
1482 ScopedLocalRef<jthrowable> exception(
1483 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1484 if (exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001485 ScopedObjectAccessUnchecked soa(env);
1486 Throwable* t = reinterpret_cast<Throwable*>(soa.Self()->DecodeJObject(exception.get()));
Ian Rogers50b35e22012-10-04 10:09:15 -07001487 t->SetDetailMessage(String::AllocFromModifiedUtf8(soa.Self(), msg));
Ian Rogers64b6d142012-10-29 16:34:15 -07001488 if (cause != NULL) {
1489 t->SetCause(soa.Decode<Throwable*>(cause));
1490 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001491 soa.Self()->SetException(t);
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001492 } else {
1493 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1494 << PrettyTypeOf(GetException());
1495 CHECK(IsExceptionPending());
1496 }
1497 return;
1498 }
Elliott Hughesa4f94742012-05-29 16:28:38 -07001499 int rc = ::art::ThrowNewException(env, exception_class.get(), msg, cause);
Elliott Hughes30646832011-10-13 16:59:46 -07001500 if (rc != JNI_OK) {
1501 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1502 << PrettyTypeOf(GetException());
1503 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001504 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001505}
1506
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001507void Thread::ThrowOutOfMemoryError(const char* msg) {
1508 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1509 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001510 if (!throwing_OutOfMemoryError_) {
1511 throwing_OutOfMemoryError_ = true;
Elliott Hughes57aba862012-06-20 14:00:47 -07001512 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001513 } else {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001514 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
1515 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001516 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001517 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001518}
1519
Elliott Hughes498508c2011-10-17 14:58:22 -07001520Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001521 return Thread::Current();
1522}
1523
1524void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001525 std::ostringstream ss;
1526 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001527 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001528 // log to stderr for debugging command line processes
1529 std::cerr << str;
1530#ifdef HAVE_ANDROID_OS
1531 // log to logcat for debugging frameworks processes
1532 LOG(INFO) << str;
1533#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001534}
1535
Elliott Hughes98e20172012-04-24 15:38:13 -07001536struct EntryPointInfo {
1537 uint32_t offset;
1538 const char* name;
1539};
1540#define ENTRY_POINT_INFO(x) { ENTRYPOINT_OFFSET(x), #x }
1541static const EntryPointInfo gThreadEntryPointInfo[] = {
1542 ENTRY_POINT_INFO(pAllocArrayFromCode),
1543 ENTRY_POINT_INFO(pAllocArrayFromCodeWithAccessCheck),
1544 ENTRY_POINT_INFO(pAllocObjectFromCode),
1545 ENTRY_POINT_INFO(pAllocObjectFromCodeWithAccessCheck),
1546 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCode),
1547 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCodeWithAccessCheck),
1548 ENTRY_POINT_INFO(pInstanceofNonTrivialFromCode),
1549 ENTRY_POINT_INFO(pCanPutArrayElementFromCode),
1550 ENTRY_POINT_INFO(pCheckCastFromCode),
1551 ENTRY_POINT_INFO(pDebugMe),
1552 ENTRY_POINT_INFO(pUpdateDebuggerFromCode),
1553 ENTRY_POINT_INFO(pInitializeStaticStorage),
1554 ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccessFromCode),
1555 ENTRY_POINT_INFO(pInitializeTypeFromCode),
1556 ENTRY_POINT_INFO(pResolveStringFromCode),
Ian Rogers474b6da2012-09-25 00:20:38 -07001557 ENTRY_POINT_INFO(pGetAndClearException),
Elliott Hughes98e20172012-04-24 15:38:13 -07001558 ENTRY_POINT_INFO(pSet32Instance),
1559 ENTRY_POINT_INFO(pSet32Static),
1560 ENTRY_POINT_INFO(pSet64Instance),
1561 ENTRY_POINT_INFO(pSet64Static),
1562 ENTRY_POINT_INFO(pSetObjInstance),
1563 ENTRY_POINT_INFO(pSetObjStatic),
1564 ENTRY_POINT_INFO(pGet32Instance),
1565 ENTRY_POINT_INFO(pGet32Static),
1566 ENTRY_POINT_INFO(pGet64Instance),
1567 ENTRY_POINT_INFO(pGet64Static),
1568 ENTRY_POINT_INFO(pGetObjInstance),
1569 ENTRY_POINT_INFO(pGetObjStatic),
1570 ENTRY_POINT_INFO(pHandleFillArrayDataFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001571 ENTRY_POINT_INFO(pFindNativeMethod),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 ENTRY_POINT_INFO(pJniMethodStart),
1573 ENTRY_POINT_INFO(pJniMethodStartSynchronized),
1574 ENTRY_POINT_INFO(pJniMethodEnd),
1575 ENTRY_POINT_INFO(pJniMethodEndSynchronized),
1576 ENTRY_POINT_INFO(pJniMethodEndWithReference),
1577 ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
Elliott Hughes98e20172012-04-24 15:38:13 -07001578 ENTRY_POINT_INFO(pLockObjectFromCode),
1579 ENTRY_POINT_INFO(pUnlockObjectFromCode),
1580 ENTRY_POINT_INFO(pCmpgDouble),
1581 ENTRY_POINT_INFO(pCmpgFloat),
1582 ENTRY_POINT_INFO(pCmplDouble),
1583 ENTRY_POINT_INFO(pCmplFloat),
Elliott Hughes98e20172012-04-24 15:38:13 -07001584 ENTRY_POINT_INFO(pFmod),
Ian Rogers0183dd72012-09-17 23:06:51 -07001585 ENTRY_POINT_INFO(pSqrt),
Elliott Hughes98e20172012-04-24 15:38:13 -07001586 ENTRY_POINT_INFO(pL2d),
Elliott Hughes98e20172012-04-24 15:38:13 -07001587 ENTRY_POINT_INFO(pFmodf),
Elliott Hughes98e20172012-04-24 15:38:13 -07001588 ENTRY_POINT_INFO(pL2f),
1589 ENTRY_POINT_INFO(pD2iz),
1590 ENTRY_POINT_INFO(pF2iz),
1591 ENTRY_POINT_INFO(pIdivmod),
1592 ENTRY_POINT_INFO(pD2l),
1593 ENTRY_POINT_INFO(pF2l),
1594 ENTRY_POINT_INFO(pLdiv),
1595 ENTRY_POINT_INFO(pLdivmod),
1596 ENTRY_POINT_INFO(pLmul),
1597 ENTRY_POINT_INFO(pShlLong),
1598 ENTRY_POINT_INFO(pShrLong),
1599 ENTRY_POINT_INFO(pUshrLong),
1600 ENTRY_POINT_INFO(pIndexOf),
1601 ENTRY_POINT_INFO(pMemcmp16),
1602 ENTRY_POINT_INFO(pStringCompareTo),
1603 ENTRY_POINT_INFO(pMemcpy),
1604 ENTRY_POINT_INFO(pUnresolvedDirectMethodTrampolineFromCode),
1605 ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
1606 ENTRY_POINT_INFO(pInvokeInterfaceTrampoline),
1607 ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
1608 ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
1609 ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
1610 ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
1611 ENTRY_POINT_INFO(pCheckSuspendFromCode),
1612 ENTRY_POINT_INFO(pTestSuspendFromCode),
1613 ENTRY_POINT_INFO(pDeliverException),
1614 ENTRY_POINT_INFO(pThrowAbstractMethodErrorFromCode),
1615 ENTRY_POINT_INFO(pThrowArrayBoundsFromCode),
1616 ENTRY_POINT_INFO(pThrowDivZeroFromCode),
1617 ENTRY_POINT_INFO(pThrowNoSuchMethodFromCode),
1618 ENTRY_POINT_INFO(pThrowNullPointerFromCode),
1619 ENTRY_POINT_INFO(pThrowStackOverflowFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001620};
1621#undef ENTRY_POINT_INFO
1622
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001623void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1624 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes98e20172012-04-24 15:38:13 -07001625
1626#define DO_THREAD_OFFSET(x) if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { os << # x; return; }
Ian Rogers474b6da2012-09-25 00:20:38 -07001627 DO_THREAD_OFFSET(state_and_flags_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001628 DO_THREAD_OFFSET(card_table_);
1629 DO_THREAD_OFFSET(exception_);
1630 DO_THREAD_OFFSET(jni_env_);
1631 DO_THREAD_OFFSET(self_);
1632 DO_THREAD_OFFSET(stack_end_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001633 DO_THREAD_OFFSET(suspend_count_);
1634 DO_THREAD_OFFSET(thin_lock_id_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001635 //DO_THREAD_OFFSET(top_of_managed_stack_);
1636 //DO_THREAD_OFFSET(top_of_managed_stack_pc_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001637 DO_THREAD_OFFSET(top_sirt_);
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001638#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001639
1640 size_t entry_point_count = arraysize(gThreadEntryPointInfo);
1641 CHECK_EQ(entry_point_count * size_of_pointers, sizeof(EntryPoints));
1642 uint32_t expected_offset = OFFSETOF_MEMBER(Thread, entrypoints_);
1643 for (size_t i = 0; i < entry_point_count; ++i) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001644 CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset) << gThreadEntryPointInfo[i].name;
Elliott Hughes98e20172012-04-24 15:38:13 -07001645 expected_offset += size_of_pointers;
1646 if (gThreadEntryPointInfo[i].offset == offset) {
1647 os << gThreadEntryPointInfo[i].name;
1648 return;
1649 }
1650 }
1651 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001652}
1653
Ian Rogers0399dde2012-06-06 17:09:28 -07001654static const bool kDebugExceptionDelivery = false;
1655class CatchBlockStackVisitor : public StackVisitor {
Ian Rogersbdb03912011-09-14 00:55:44 -07001656 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001657 CatchBlockStackVisitor(Thread* self, Throwable* exception)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001658 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001659 : StackVisitor(self->GetManagedStack(), self->GetInstrumentationStack(), self->GetLongJumpContext()),
Ian Rogers0399dde2012-06-06 17:09:28 -07001660 self_(self), exception_(exception), to_find_(exception->GetClass()), throw_method_(NULL),
1661 throw_frame_id_(0), throw_dex_pc_(0), handler_quick_frame_(NULL),
1662 handler_quick_frame_pc_(0), handler_dex_pc_(0), native_method_count_(0),
Ian Rogers57b86d42012-03-27 16:05:41 -07001663 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers52673ff2012-06-27 23:25:34 -07001664 // Exception not in root sets, can't allow GC.
1665 last_no_assert_suspension_cause_ = self->StartAssertNoThreadSuspension("Finding catch block");
1666 }
1667
1668 ~CatchBlockStackVisitor() {
1669 LOG(FATAL) << "UNREACHABLE"; // Expected to take long jump.
Ian Rogers67375ac2011-09-14 00:55:44 -07001670 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001671
Ian Rogersb726dcb2012-09-05 08:57:23 -07001672 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1673 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001674 AbstractMethod* method = GetMethod();
Elliott Hughes530fa002012-03-12 11:44:49 -07001675 if (method == NULL) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001676 // This is the upcall, we remember the frame and last pc so that we may long jump to them.
1677 handler_quick_frame_pc_ = GetCurrentQuickFramePc();
1678 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001679 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001680 }
1681 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001682 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001683 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001684 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001685 } else {
Ian Rogers0399dde2012-06-06 17:09:28 -07001686 if (throw_method_ == NULL) {
1687 throw_method_ = method;
1688 throw_frame_id_ = GetFrameId();
1689 throw_dex_pc_ = GetDexPc();
Ian Rogers67375ac2011-09-14 00:55:44 -07001690 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001691 if (method->IsNative()) {
1692 native_method_count_++;
1693 } else {
jeffhao725a9572012-11-13 18:20:12 -08001694 // Unwind stack when an exception occurs during instrumentation
1695 if (UNLIKELY(method_tracing_active_ && IsInstrumentationExitPc(GetCurrentQuickFramePc()))) {
1696 uintptr_t pc = InstrumentationMethodUnwindFromCode(Thread::Current());
Ian Rogers0c7abda2012-09-19 13:33:42 -07001697 dex_pc = method->ToDexPc(pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001698 } else {
1699 dex_pc = GetDexPc();
1700 }
1701 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001702 }
1703 if (dex_pc != DexFile::kDexNoIndex) {
1704 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1705 if (found_dex_pc != DexFile::kDexNoIndex) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001706 handler_dex_pc_ = found_dex_pc;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001707 handler_quick_frame_pc_ = method->ToNativePc(found_dex_pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001708 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001709 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001710 }
1711 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001712 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001713 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001714
Ian Rogersb726dcb2012-09-05 08:57:23 -07001715 void DoLongJump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001716 AbstractMethod* catch_method = *handler_quick_frame_;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001717 Dbg::PostException(self_, throw_frame_id_, throw_method_, throw_dex_pc_,
Ian Rogers0399dde2012-06-06 17:09:28 -07001718 catch_method, handler_dex_pc_, exception_);
1719 if (kDebugExceptionDelivery) {
1720 if (catch_method == NULL) {
1721 LOG(INFO) << "Handler is upcall";
1722 } else {
Ian Rogers4445a7e2012-10-05 17:19:13 -07001723 const DexFile& dex_file = *catch_method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -07001724 int line_number = dex_file.GetLineNumFromPC(catch_method, handler_dex_pc_);
1725 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
1726 }
1727 }
Ian Rogers52673ff2012-06-27 23:25:34 -07001728 self_->SetException(exception_); // Exception back in root set.
1729 self_->EndAssertNoThreadSuspension(last_no_assert_suspension_cause_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001730 // Place context back on thread so it will be available when we continue.
1731 self_->ReleaseLongJumpContext(context_);
1732 context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
1733 CHECK_NE(handler_quick_frame_pc_, 0u);
1734 context_->SetPC(handler_quick_frame_pc_);
1735 context_->SmashCallerSaves();
1736 context_->DoLongJump();
1737 }
1738
1739 private:
1740 Thread* self_;
1741 Throwable* exception_;
1742 // The type of the exception catch block to find.
Ian Rogersbdb03912011-09-14 00:55:44 -07001743 Class* to_find_;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001744 AbstractMethod* throw_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001745 JDWP::FrameId throw_frame_id_;
1746 uint32_t throw_dex_pc_;
1747 // Quick frame with found handler or last frame if no handler found.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001748 AbstractMethod** handler_quick_frame_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001749 // PC to branch to for the handler.
1750 uintptr_t handler_quick_frame_pc_;
1751 // Associated dex PC.
1752 uint32_t handler_dex_pc_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001753 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1754 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001755 // Is method tracing active?
1756 const bool method_tracing_active_;
Ian Rogers52673ff2012-06-27 23:25:34 -07001757 // Support for nesting no thread suspension checks.
1758 const char* last_no_assert_suspension_cause_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001759};
1760
jeffhao94d6df42012-11-26 16:02:12 -08001761void Thread::QuickDeliverException() {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001762 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001763 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001764 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001765 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001766 ClearException();
1767 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001768 String* msg = exception->GetDetailMessage();
1769 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1770 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
Elliott Hughesc073b072012-05-24 19:29:17 -07001771 << ": " << str_msg << "\n");
Ian Rogers28ad40d2011-10-27 15:19:26 -07001772 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001773 CatchBlockStackVisitor catch_finder(this, exception);
1774 catch_finder.WalkStack(true);
1775 catch_finder.DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001776 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001777}
1778
Ian Rogersbdb03912011-09-14 00:55:44 -07001779Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001780 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001781 if (result == NULL) {
1782 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07001783 } else {
1784 long_jump_context_ = NULL; // Avoid context being shared.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001785 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001786 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001787}
1788
Mathieu Chartier66f19252012-09-18 08:57:04 -07001789AbstractMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, size_t* frame_id) const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001790 struct CurrentMethodVisitor : public StackVisitor {
1791 CurrentMethodVisitor(const ManagedStack* stack,
jeffhao725a9572012-11-13 18:20:12 -08001792 const std::vector<InstrumentationStackFrame>* instrumentation_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001793 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001794 : StackVisitor(stack, instrumentation_stack, NULL), method_(NULL), dex_pc_(0), frame_id_(0) {}
Elliott Hughes8be2d402012-02-23 14:22:41 -08001795
Ian Rogersb726dcb2012-09-05 08:57:23 -07001796 virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001797 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001798 if (m->IsRuntimeMethod()) {
1799 // Continue if this is a runtime method.
1800 return true;
1801 }
1802 method_ = m;
1803 dex_pc_ = GetDexPc();
1804 frame_id_ = GetFrameId();
1805 return false;
1806 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001807 AbstractMethod* method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001808 uint32_t dex_pc_;
1809 size_t frame_id_;
1810 };
1811
jeffhao725a9572012-11-13 18:20:12 -08001812 CurrentMethodVisitor visitor(GetManagedStack(), GetInstrumentationStack());
Ian Rogers0399dde2012-06-06 17:09:28 -07001813 visitor.WalkStack(false);
1814 if (dex_pc != NULL) {
1815 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001816 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001817 if (frame_id != NULL) {
1818 *frame_id = visitor.frame_id_;
jeffhao33dc7712011-11-09 17:54:24 -08001819 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001820 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08001821}
1822
Elliott Hughes5f791332011-09-15 17:45:30 -07001823bool Thread::HoldsLock(Object* object) {
1824 if (object == NULL) {
1825 return false;
1826 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001827 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001828}
1829
Ian Rogers40e3bac2012-11-20 00:09:14 -08001830// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
1831template <typename RootVisitor>
Ian Rogers0399dde2012-06-06 17:09:28 -07001832class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001833 public:
jeffhao725a9572012-11-13 18:20:12 -08001834 ReferenceMapVisitor(const ManagedStack* stack, const std::vector<InstrumentationStackFrame>* instrumentation_stack,
Ian Rogers40e3bac2012-11-20 00:09:14 -08001835 Context* context, const RootVisitor& visitor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001836 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
jeffhao725a9572012-11-13 18:20:12 -08001837 : StackVisitor(stack, instrumentation_stack, context), visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07001838
Ian Rogersb726dcb2012-09-05 08:57:23 -07001839 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001840 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001841 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
1842 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001843 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001844 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
1845 if (shadow_frame != NULL) {
Ian Rogers40e3bac2012-11-20 00:09:14 -08001846 WrapperVisitor wrapperVisitor(visitor_, this);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001847 shadow_frame->VisitRoots(wrapperVisitor);
Ian Rogers0399dde2012-06-06 17:09:28 -07001848 } else {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001849 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001850 // Process register map (which native and runtime methods don't have)
Ian Rogers640495b2012-06-22 15:15:47 -07001851 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001852 const uint8_t* native_gc_map = m->GetNativeGcMap();
1853 CHECK(native_gc_map != NULL) << PrettyMethod(m);
1854 mh_.ChangeMethod(m);
1855 const DexFile::CodeItem* code_item = mh_.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001856 DCHECK(code_item != NULL) << PrettyMethod(m); // Can't be NULL or how would we compile its instructions?
Ian Rogers0c7abda2012-09-19 13:33:42 -07001857 NativePcOffsetToReferenceMap map(native_gc_map);
Ian Rogers0399dde2012-06-06 17:09:28 -07001858 size_t num_regs = std::min(map.RegWidth() * 8,
1859 static_cast<size_t>(code_item->registers_size_));
Ian Rogers0c7abda2012-09-19 13:33:42 -07001860 if (num_regs > 0) {
1861 const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
1862 DCHECK(reg_bitmap != NULL);
1863 const VmapTable vmap_table(m->GetVmapTableRaw());
1864 uint32_t core_spills = m->GetCoreSpillMask();
1865 uint32_t fp_spills = m->GetFpSpillMask();
1866 size_t frame_size = m->GetFrameSizeInBytes();
1867 // For all dex registers in the bitmap
Mathieu Chartier66f19252012-09-18 08:57:04 -07001868 AbstractMethod** cur_quick_frame = GetCurrentQuickFrame();
Ian Rogers0c7abda2012-09-19 13:33:42 -07001869 DCHECK(cur_quick_frame != NULL);
1870 for (size_t reg = 0; reg < num_regs; ++reg) {
1871 // Does this register hold a reference?
1872 if (TestBitmap(reg, reg_bitmap)) {
1873 uint32_t vmap_offset;
1874 Object* ref;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001875 if (vmap_table.IsInContext(reg, vmap_offset, kReferenceVReg)) {
1876 uintptr_t val = GetGPR(vmap_table.ComputeRegister(core_spills, vmap_offset,
1877 kReferenceVReg));
1878 ref = reinterpret_cast<Object*>(val);
Ian Rogers0c7abda2012-09-19 13:33:42 -07001879 } else {
1880 ref = reinterpret_cast<Object*>(GetVReg(cur_quick_frame, code_item, core_spills,
1881 fp_spills, frame_size, reg));
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001882 }
1883
1884 if (ref != NULL) {
Ian Rogers40e3bac2012-11-20 00:09:14 -08001885 visitor_(ref, reg, this);
Ian Rogers0c7abda2012-09-19 13:33:42 -07001886 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001887 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001888 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001889 }
1890 }
1891 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001892 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001893 }
1894
1895 private:
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001896
1897 class WrapperVisitor {
1898 public:
Ian Rogers40e3bac2012-11-20 00:09:14 -08001899 WrapperVisitor(const RootVisitor& root_visitor, const StackVisitor* stack_visitor)
1900 : root_visitor_(root_visitor), stack_visitor_(stack_visitor) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001901
1902 void operator()(const Object* obj, size_t offset) const {
Ian Rogers40e3bac2012-11-20 00:09:14 -08001903 root_visitor_(obj, offset, stack_visitor_);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001904 }
1905
1906 private:
Ian Rogers40e3bac2012-11-20 00:09:14 -08001907 const RootVisitor& root_visitor_;
1908 const StackVisitor* const stack_visitor_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001909 };
1910
1911 static bool TestBitmap(int reg, const uint8_t* reg_vector) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001912 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1913 }
1914
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001915 // Visitor for when we visit a root.
Ian Rogers40e3bac2012-11-20 00:09:14 -08001916 const RootVisitor& visitor_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001917
Ian Rogers0c7abda2012-09-19 13:33:42 -07001918 // A method helper we keep around to avoid dex file/cache re-computations.
1919 MethodHelper mh_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001920};
1921
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001922class RootCallbackVisitor {
1923 public:
1924 RootCallbackVisitor(Heap::RootVisitor* visitor, void* arg) : visitor_(visitor), arg_(arg) {
1925
1926 }
1927
Ian Rogers40e3bac2012-11-20 00:09:14 -08001928 void operator()(const Object* obj, size_t, const StackVisitor*) const {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001929 visitor_(obj, arg_);
1930 }
1931
1932 private:
1933 Heap::RootVisitor* visitor_;
1934 void* arg_;
1935};
1936
1937class VerifyCallbackVisitor {
1938 public:
1939 VerifyCallbackVisitor(Heap::VerifyRootVisitor* visitor, void* arg)
1940 : visitor_(visitor),
1941 arg_(arg) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001942 }
1943
Ian Rogers40e3bac2012-11-20 00:09:14 -08001944 void operator()(const Object* obj, size_t vreg, const StackVisitor* visitor) const {
1945 visitor_(obj, arg_, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001946 }
1947
1948 private:
Ian Rogers40e3bac2012-11-20 00:09:14 -08001949 Heap::VerifyRootVisitor* const visitor_;
1950 void* const arg_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001951};
1952
1953struct VerifyRootWrapperArg {
1954 Heap::VerifyRootVisitor* visitor;
1955 void* arg;
1956};
1957
1958static void VerifyRootWrapperCallback(const Object* root, void* arg) {
1959 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
1960 wrapperArg->visitor(root, wrapperArg->arg, 0, NULL);
1961}
1962
1963void Thread::VerifyRoots(Heap::VerifyRootVisitor* visitor, void* arg) {
1964 // We need to map from a RootVisitor to VerifyRootVisitor, so pass in nulls for arguments we
1965 // don't have.
1966 VerifyRootWrapperArg wrapperArg;
1967 wrapperArg.arg = arg;
1968 wrapperArg.visitor = visitor;
1969
1970 if (exception_ != NULL) {
1971 VerifyRootWrapperCallback(exception_, &wrapperArg);
1972 }
1973 if (class_loader_override_ != NULL) {
1974 VerifyRootWrapperCallback(class_loader_override_, &wrapperArg);
1975 }
1976 jni_env_->locals.VisitRoots(VerifyRootWrapperCallback, &wrapperArg);
1977 jni_env_->monitors.VisitRoots(VerifyRootWrapperCallback, &wrapperArg);
1978
1979 SirtVisitRoots(VerifyRootWrapperCallback, &wrapperArg);
1980
1981 // Visit roots on this thread's stack
1982 Context* context = GetLongJumpContext();
1983 VerifyCallbackVisitor visitorToCallback(visitor, arg);
jeffhao725a9572012-11-13 18:20:12 -08001984 ReferenceMapVisitor<VerifyCallbackVisitor> mapper(GetManagedStack(), GetInstrumentationStack(), context,
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001985 visitorToCallback);
1986 mapper.WalkStack();
1987 ReleaseLongJumpContext(context);
1988}
1989
Ian Rogersd6b1f612011-09-27 13:38:14 -07001990void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001991 if (exception_ != NULL) {
1992 visitor(exception_, arg);
1993 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001994 if (class_loader_override_ != NULL) {
1995 visitor(class_loader_override_, arg);
1996 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001997 jni_env_->locals.VisitRoots(visitor, arg);
1998 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001999
2000 SirtVisitRoots(visitor, arg);
2001
Ian Rogersd6b1f612011-09-27 13:38:14 -07002002 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07002003 Context* context = GetLongJumpContext();
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002004 RootCallbackVisitor visitorToCallback(visitor, arg);
jeffhao725a9572012-11-13 18:20:12 -08002005 ReferenceMapVisitor<RootCallbackVisitor> mapper(GetManagedStack(), GetInstrumentationStack(), context,
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002006 visitorToCallback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002007 mapper.WalkStack();
2008 ReleaseLongJumpContext(context);
Elliott Hughes410c0c82011-09-01 17:58:25 -07002009}
2010
jeffhao25045522012-03-13 19:34:37 -07002011#if VERIFY_OBJECT_ENABLED
Ian Rogers0399dde2012-06-06 17:09:28 -07002012static void VerifyObject(const Object* obj, void* arg) {
2013 Heap* heap = reinterpret_cast<Heap*>(arg);
2014 heap->VerifyObject(obj);
jeffhao25045522012-03-13 19:34:37 -07002015}
2016
2017void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07002018 UniquePtr<Context> context(Context::Create());
jeffhao4eb68ed2012-10-17 16:41:07 -07002019 RootCallbackVisitor visitorToCallback(VerifyObject, Runtime::Current()->GetHeap());
jeffhao725a9572012-11-13 18:20:12 -08002020 ReferenceMapVisitor<RootCallbackVisitor> mapper(GetManagedStack(), GetInstrumentationStack(), context.get(),
jeffhao4eb68ed2012-10-17 16:41:07 -07002021 visitorToCallback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002022 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07002023}
2024#endif
2025
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002026// Set the stack end to that to be used during a stack overflow
2027void Thread::SetStackEndForStackOverflow() {
2028 // During stack overflow we allow use of the full stack
2029 if (stack_end_ == stack_begin_) {
2030 DumpStack(std::cerr);
2031 LOG(FATAL) << "Need to increase kStackOverflowReservedBytes (currently "
2032 << kStackOverflowReservedBytes << ")";
2033 }
2034
2035 stack_end_ = stack_begin_;
2036}
2037
Elliott Hughes330304d2011-08-12 14:28:05 -07002038std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002039 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07002040 return os;
2041}
2042
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002043#ifndef NDEBUG
2044void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
2045 CHECK_EQ(0u, no_thread_suspension_) << last_no_thread_suspension_cause_;
2046 if (check_locks) {
2047 bool bad_mutexes_held = false;
2048 for (int i = kMaxMutexLevel; i >= 0; --i) {
2049 // We expect no locks except the mutator_lock_.
2050 if (i != kMutatorLock) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002051 BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002052 if (held_mutex != NULL) {
2053 LOG(ERROR) << "holding \"" << held_mutex->GetName()
2054 << "\" at point where thread suspension is expected";
Elliott Hughesffb465f2012-03-01 18:46:05 -08002055 bad_mutexes_held = true;
2056 }
2057 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08002058 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002059 CHECK(!bad_mutexes_held);
Elliott Hughesffb465f2012-03-01 18:46:05 -08002060 }
2061}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002062#endif
Elliott Hughesa4060e52012-03-02 16:51:35 -08002063
Elliott Hughes8daa0922011-09-11 13:46:25 -07002064} // namespace art