blob: 15a4f1bdb47102aa7740da439b1e1f3b05c5c9f1 [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"
Ian Rogers30fab402012-01-23 15:43:46 -080050#include "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 {
113 MutexLock mu(*Locks::runtime_shutdown_lock_);
114 // Check that if we got here we cannot be shutting down (as shutdown should never have started
115 // while threads are being born).
116 CHECK(!runtime->IsShuttingDown());
117 self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
118 Runtime::Current()->EndThreadBirth();
119 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700120 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700121 ScopedObjectAccess soa(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700122 {
Ian Rogers1f539342012-10-03 21:09:42 -0700123 SirtRef<String> thread_name(self, self->GetThreadName(soa));
Ian Rogers365c1022012-06-22 15:05:28 -0700124 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
125 }
Ian Rogers365c1022012-06-22 15:05:28 -0700126 Dbg::PostThreadStart(self);
127
128 // Invoke the 'run' method of our java.lang.Thread.
129 CHECK(self->peer_ != NULL);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700130 Object* receiver = soa.Decode<Object*>(self->peer_);
Ian Rogers365c1022012-06-22 15:05:28 -0700131 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700132 AbstractMethod* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Ian Rogers365c1022012-06-22 15:05:28 -0700133 m->Invoke(self, receiver, NULL, NULL);
Elliott Hughes47179f72011-10-27 16:44:39 -0700134 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700135 // Detach and delete self.
136 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700137
Carl Shapirob5573532011-07-12 18:22:59 -0700138 return NULL;
139}
140
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, Object* thread_peer) {
142 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
143 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetInt(thread_peer)));
144 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
145 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700146 if (kIsDebugBuild) {
147 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
148 if (result != NULL && !result->IsSuspended()) {
149 Locks::thread_list_lock_->AssertHeld(soa.Self());
150 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700151 }
152 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800153}
154
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
156 return FromManagedThread(soa, soa.Decode<Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700157}
158
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700159static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700160 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700161 if (stack_size == 0) {
162 stack_size = Runtime::Current()->GetDefaultStackSize();
163 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700164
Brian Carlstrom6414a972012-04-14 14:20:04 -0700165 // Dalvik used the bionic pthread default stack size for native threads,
166 // so include that here to support apps that expect large native stacks.
167 stack_size += 1 * MB;
168
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700169 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
170 if (stack_size < PTHREAD_STACK_MIN) {
171 stack_size = PTHREAD_STACK_MIN;
172 }
173
174 // It's likely that callers are trying to ensure they have at least a certain amount of
175 // stack space, so we should add our reserved space on top of what they requested, rather
176 // than implicitly take it away from them.
177 stack_size += Thread::kStackOverflowReservedBytes;
178
179 // Some systems require the stack size to be a multiple of the system page size, so round up.
180 stack_size = RoundUp(stack_size, kPageSize);
181
182 return stack_size;
183}
184
Elliott Hughesd8af1592012-04-16 20:40:15 -0700185static void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
186 if (sigaltstack(new_stack, old_stack) == -1) {
187 PLOG(FATAL) << "sigaltstack failed";
188 }
189}
190
191static void SetUpAlternateSignalStack() {
192 // Create and set an alternate signal stack.
193 stack_t ss;
194 ss.ss_sp = new uint8_t[SIGSTKSZ];
195 ss.ss_size = SIGSTKSZ;
196 ss.ss_flags = 0;
197 CHECK(ss.ss_sp != NULL);
198 SigAltStack(&ss, NULL);
199
200 // Double-check that it worked.
201 ss.ss_sp = NULL;
202 SigAltStack(NULL, &ss);
203 VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
204}
205
206static void TearDownAlternateSignalStack() {
207 // Get the pointer so we can free the memory.
208 stack_t ss;
209 SigAltStack(NULL, &ss);
210 uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
211
212 // Tell the kernel to stop using it.
213 ss.ss_sp = NULL;
214 ss.ss_flags = SS_DISABLE;
Elliott Hughes4c5231d2012-04-18 16:54:31 -0700215 ss.ss_size = SIGSTKSZ; // Avoid ENOMEM failure with Mac OS' buggy libc.
Elliott Hughesd8af1592012-04-16 20:40:15 -0700216 SigAltStack(&ss, NULL);
217
218 // Free it.
219 delete[] allocated_signal_stack;
220}
221
Ian Rogers120f1c72012-09-28 17:17:10 -0700222void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700223 CHECK(java_peer != NULL);
Ian Rogers120f1c72012-09-28 17:17:10 -0700224 Thread* self = static_cast<JNIEnvExt*>(env)->self;
225 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700226
Ian Rogers120f1c72012-09-28 17:17:10 -0700227 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
228 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700229 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700230 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
231 if (runtime->IsShuttingDown()) {
232 thread_start_during_shutdown = true;
233 } else {
234 runtime->StartThreadBirth();
235 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700236 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700237 if (thread_start_during_shutdown) {
238 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
239 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
240 return;
241 }
242
243 Thread* child_thread = new Thread(is_daemon);
244 // Use global JNI ref to hold peer live while child thread starts.
245 child_thread->peer_ = env->NewGlobalRef(java_peer);
246 stack_size = FixStackSize(stack_size);
247
248 // Thread.start is synchronized, so we know that vmData is 0, and know that we're not racing to
249 // assign it.
250 env->SetIntField(java_peer, WellKnownClasses::java_lang_Thread_vmData,
251 reinterpret_cast<jint>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700252
253 pthread_t new_pthread;
254 pthread_attr_t attr;
255 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
256 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
257 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
Ian Rogers120f1c72012-09-28 17:17:10 -0700258 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, child_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700259 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
260
Ian Rogers120f1c72012-09-28 17:17:10 -0700261 if (pthread_create_result != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700262 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700263 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700264 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
265 runtime->EndThreadBirth();
266 }
267 // Manually delete the global reference since Thread::Init will not have been run.
268 env->DeleteGlobalRef(child_thread->peer_);
269 child_thread->peer_ = NULL;
270 delete child_thread;
271 child_thread = NULL;
272 // TODO: remove from thread group?
273 env->SetIntField(java_peer, WellKnownClasses::java_lang_Thread_vmData, 0);
274 {
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700275 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
276 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
Ian Rogers120f1c72012-09-28 17:17:10 -0700277 ScopedObjectAccess soa(env);
278 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700279 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700280 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700281}
282
Ian Rogers120f1c72012-09-28 17:17:10 -0700283void Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700284 // This function does all the initialization that must be run by the native thread it applies to.
285 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
286 // we can handshake with the corresponding native thread when it's ready.) Check this native
287 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700288 CHECK(Thread::Current() == NULL);
289
Elliott Hughesd8af1592012-04-16 20:40:15 -0700290 SetUpAlternateSignalStack();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700291 InitCpu();
292 InitFunctionPointers();
Shih-wei Liao21d28f52012-06-12 05:55:00 -0700293#ifdef ART_USE_GREENLAND_COMPILER
294 InitRuntimeEntryPoints(&runtime_entry_points_);
295#endif
Ian Rogers5d76c432011-10-31 21:42:49 -0700296 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700297 InitTid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700298
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
Ian Rogers365c1022012-06-22 15:05:28 -0700312Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700313 Thread* self;
314 Runtime* runtime = Runtime::Current();
315 if (runtime == NULL) {
316 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
317 return NULL;
318 }
319 {
320 MutexLock mu(NULL, *Locks::runtime_shutdown_lock_);
321 if (runtime->IsShuttingDown()) {
322 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
323 return NULL;
324 } else {
325 Runtime::Current()->StartThreadBirth();
326 self = new Thread(as_daemon);
327 self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
328 Runtime::Current()->EndThreadBirth();
329 }
330 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700331
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700332 CHECK_NE(self->GetState(), kRunnable);
333 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700334
Elliott Hughescac6cc72011-11-03 20:31:21 -0700335 // If we're the main thread, ClassLinker won't be created until after we're attached,
336 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800337 // In the compiler, all threads need this hack, because no-one's going to be getting
338 // a native peer!
339 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700340 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800341 } else {
342 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700343 if (thread_name != NULL) {
344 self->name_->assign(thread_name);
345 ::art::SetThreadName(thread_name);
346 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700347 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700348
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700349 return self;
350}
351
Ian Rogers365c1022012-06-22 15:05:28 -0700352void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
353 Runtime* runtime = Runtime::Current();
354 CHECK(runtime->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700355 JNIEnv* env = jni_env_;
356
Elliott Hughes462c9442012-03-23 18:47:50 -0700357 if (thread_group == NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -0700358 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700359 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700360 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700361 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700362 jboolean thread_is_daemon = as_daemon;
363
Elliott Hugheseac76672012-05-24 21:56:51 -0700364 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700365 if (peer.get() == NULL) {
366 CHECK(IsExceptionPending());
367 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700368 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700369 peer_ = env->NewGlobalRef(peer.get());
Elliott Hugheseac76672012-05-24 21:56:51 -0700370 env->CallNonvirtualVoidMethod(peer.get(),
371 WellKnownClasses::java_lang_Thread,
372 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700373 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700375
Ian Rogers120f1c72012-09-28 17:17:10 -0700376 Thread* self = this;
377 DCHECK_EQ(self, Thread::Current());
378 jni_env_->SetIntField(peer.get(), WellKnownClasses::java_lang_Thread_vmData,
379 reinterpret_cast<jint>(self));
380
381 ScopedObjectAccess soa(self);
Ian Rogers1f539342012-10-03 21:09:42 -0700382 SirtRef<String> peer_thread_name(soa.Self(), GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700383 if (peer_thread_name.get() == NULL) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700384 Object* native_peer = soa.Decode<Object*>(peer.get());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700385 // The Thread constructor should have set the Thread.name to a
386 // non-null value. However, because we can run without code
387 // available (in the compiler, in tests), we manually assign the
388 // fields the constructor should have set.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700389 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
390 SetBoolean(native_peer, thread_is_daemon);
391 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
392 SetObject(native_peer, soa.Decode<Object*>(thread_group));
393 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
394 SetObject(native_peer, soa.Decode<Object*>(thread_name.get()));
395 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
396 SetInt(native_peer, thread_priority);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700397 peer_thread_name.reset(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700398 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700399 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Brian Carlstrom00fae582011-10-28 01:16:28 -0700400 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800401 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700402 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700403}
404
Elliott Hughes899e7892012-01-24 14:57:32 -0800405void Thread::SetThreadName(const char* name) {
406 name_->assign(name);
407 ::art::SetThreadName(name);
408 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
409}
410
Elliott Hughesbe759c62011-09-08 19:38:21 -0700411void Thread::InitStackHwm() {
Elliott Hughese1884192012-04-23 12:38:15 -0700412 void* stack_base;
413 size_t stack_size;
Ian Rogers120f1c72012-09-28 17:17:10 -0700414 GetThreadStack(pthread_self_, stack_base, stack_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700415
416 // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
Elliott Hughese1884192012-04-23 12:38:15 -0700417 VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
418
419 stack_begin_ = reinterpret_cast<byte*>(stack_base);
420 stack_size_ = stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700421
Ian Rogers932746a2011-09-22 18:57:50 -0700422 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800423 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700424 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700425
Elliott Hughese1884192012-04-23 12:38:15 -0700426 // TODO: move this into the Linux GetThreadStack implementation.
427#if !defined(__APPLE__)
Elliott Hughes36ecb782012-04-17 16:55:45 -0700428 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
429 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
430 // will be broken because we'll die long before we get close to 2GB.
Ian Rogers120f1c72012-09-28 17:17:10 -0700431 bool is_main_thread = (::art::GetTid() == getpid());
432 if (is_main_thread) {
Elliott Hughes36ecb782012-04-17 16:55:45 -0700433 rlimit stack_limit;
434 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
435 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
436 }
437 if (stack_limit.rlim_cur == RLIM_INFINITY) {
438 // Find the default stack size for new threads...
439 pthread_attr_t default_attributes;
440 size_t default_stack_size;
441 CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
442 CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
443 "default stack size query");
444 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
445
446 // ...and use that as our limit.
447 size_t old_stack_size = stack_size_;
448 stack_size_ = default_stack_size;
449 stack_begin_ += (old_stack_size - stack_size_);
Elliott Hughesfaf4ba02012-05-02 16:12:19 -0700450 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
451 << " to " << PrettySize(stack_size_)
452 << " with base " << reinterpret_cast<void*>(stack_begin_);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700453 }
454 }
Elliott Hughese1884192012-04-23 12:38:15 -0700455#endif
Elliott Hughes36ecb782012-04-17 16:55:45 -0700456
Ian Rogers932746a2011-09-22 18:57:50 -0700457 // Set stack_end_ to the bottom of the stack saving space of stack overflows
458 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700459
460 // Sanity check.
461 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700462 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700463}
464
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465void Thread::ShortDump(std::ostream& os) const {
466 os << "Thread[";
467 if (GetThinLockId() != 0) {
468 // If we're in kStarting, we won't have a thin lock id or tid yet.
469 os << GetThinLockId()
470 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700471 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700472 os << GetState()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 << ",Thread*=" << this
474 << ",peer=" << peer_
475 << ",\"" << *name_ << "\""
476 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700477}
478
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479void Thread::Dump(std::ostream& os) const {
480 DumpState(os);
481 DumpStack(os);
482}
483
484String* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
485 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700486 Object* native_peer = soa.Decode<Object*>(peer_);
487 return (peer_ != NULL) ? reinterpret_cast<String*>(f->GetObject(native_peer)) : NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700488}
489
Elliott Hughesffb465f2012-03-01 18:46:05 -0800490void Thread::GetThreadName(std::string& name) const {
491 name.assign(*name_);
492}
493
Ian Rogers474b6da2012-09-25 00:20:38 -0700494void Thread::AtomicSetFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700495 android_atomic_or(flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700496}
497
498void Thread::AtomicClearFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700499 android_atomic_and(-1 ^ flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700500}
501
502ThreadState Thread::SetState(ThreadState new_state) {
503 // Cannot use this code to change into Runnable as changing to Runnable should fail if
504 // old_state_and_flags.suspend_request is true.
505 DCHECK_NE(new_state, kRunnable);
506 DCHECK_EQ(this, Thread::Current());
Ian Rogers30e173f2012-09-26 14:35:03 -0700507 union StateAndFlags old_state_and_flags = state_and_flags_;
508 state_and_flags_.as_struct.state = new_state;
509 return static_cast<ThreadState>(old_state_and_flags.as_struct.state);
Ian Rogers474b6da2012-09-25 00:20:38 -0700510}
511
Ian Rogers01ae5802012-09-28 16:14:01 -0700512// Attempt to rectify locks so that we dump thread list with required locks before exiting.
513static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -0700514 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -0700515 Locks::thread_suspend_count_lock_->Unlock(self);
516 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
517 Locks::mutator_lock_->SharedTryLock(self);
518 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
519 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
520 }
521 }
522 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
523 Locks::thread_list_lock_->TryLock(self);
524 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
525 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
526 }
527 }
528 std::ostringstream ss;
529 Runtime::Current()->GetThreadList()->DumpLocked(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -0700530 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -0700531}
532
533void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700534 DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
535 << delta << " " << debug_suspend_count_ << " " << this;
536 DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
Ian Rogers01ae5802012-09-28 16:14:01 -0700537 Locks::thread_suspend_count_lock_->AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700538
Ian Rogers01ae5802012-09-28 16:14:01 -0700539 if (UNLIKELY(delta < 0 && suspend_count_ <= 0)) {
540 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700541 return;
542 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700543
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700544 suspend_count_ += delta;
545 if (for_debugger) {
546 debug_suspend_count_ += delta;
547 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700548
Ian Rogers474b6da2012-09-25 00:20:38 -0700549 if (suspend_count_ == 0) {
550 AtomicClearFlag(kSuspendRequest);
551 } else {
552 AtomicSetFlag(kSuspendRequest);
553 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700554}
555
556void Thread::FullSuspendCheck() {
557 VLOG(threads) << this << " self-suspending";
558 // Make thread appear suspended to other threads, release mutator_lock_.
559 TransitionFromRunnableToSuspended(kSuspended);
560 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
561 TransitionFromSuspendedToRunnable();
562 VLOG(threads) << this << " self-reviving";
563}
564
565void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
566 AssertThreadSuspensionIsAllowable();
Ian Rogers474b6da2012-09-25 00:20:38 -0700567 DCHECK_NE(new_state, kRunnable);
568 DCHECK_EQ(this, Thread::Current());
Ian Rogersc747cff2012-08-31 18:20:08 -0700569 // Change to non-runnable state, thereby appearing suspended to the system.
Ian Rogers474b6da2012-09-25 00:20:38 -0700570 DCHECK_EQ(GetState(), kRunnable);
Ian Rogers30e173f2012-09-26 14:35:03 -0700571 state_and_flags_.as_struct.state = new_state;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 // Release share on mutator_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -0700573 Locks::mutator_lock_->SharedUnlock(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700574}
575
576ThreadState Thread::TransitionFromSuspendedToRunnable() {
577 bool done = false;
Ian Rogers01ae5802012-09-28 16:14:01 -0700578 union StateAndFlags old_state_and_flags = state_and_flags_;
579 int16_t old_state = old_state_and_flags.as_struct.state;
580 DCHECK_NE(static_cast<ThreadState>(old_state), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 do {
Ian Rogers81d425b2012-09-27 16:03:43 -0700582 Locks::mutator_lock_->AssertNotHeld(this); // Otherwise we starve GC..
Ian Rogers01ae5802012-09-28 16:14:01 -0700583 old_state_and_flags = state_and_flags_;
584 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
585 if ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700586 // Wait while our suspend count is non-zero.
Ian Rogers81d425b2012-09-27 16:03:43 -0700587 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
Ian Rogers01ae5802012-09-28 16:14:01 -0700588 old_state_and_flags = state_and_flags_;
589 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
590 while ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700591 // Re-check when Thread::resume_cond_ is notified.
Ian Rogers81d425b2012-09-27 16:03:43 -0700592 Thread::resume_cond_->Wait(this, *Locks::thread_suspend_count_lock_);
Ian Rogers01ae5802012-09-28 16:14:01 -0700593 old_state_and_flags = state_and_flags_;
594 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700595 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700596 DCHECK_EQ(GetSuspendCount(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700597 }
598 // Re-acquire shared mutator_lock_ access.
Ian Rogers81d425b2012-09-27 16:03:43 -0700599 Locks::mutator_lock_->SharedLock(this);
Ian Rogers474b6da2012-09-25 00:20:38 -0700600 // Atomically change from suspended to runnable if no suspend request pending.
Ian Rogers01ae5802012-09-28 16:14:01 -0700601 old_state_and_flags = state_and_flags_;
602 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
603 if ((old_state_and_flags.as_struct.flags & kSuspendRequest) == 0) {
604 union StateAndFlags new_state_and_flags = old_state_and_flags;
605 new_state_and_flags.as_struct.state = kRunnable;
606 done = android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
Ian Rogers81d425b2012-09-27 16:03:43 -0700607 &state_and_flags_.as_int)
Ian Rogers474b6da2012-09-25 00:20:38 -0700608 == 0;
609 }
610 if (!done) {
611 // Failed to transition to Runnable. Release shared mutator_lock_ access and try again.
Ian Rogers81d425b2012-09-27 16:03:43 -0700612 Locks::mutator_lock_->SharedUnlock(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700613 }
614 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700615 return static_cast<ThreadState>(old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616}
617
618Thread* Thread::SuspendForDebugger(jobject peer, bool request_suspension, bool* timeout) {
619 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
620 useconds_t total_delay_us = 0;
621 useconds_t delay_us = 0;
622 bool did_suspend_request = false;
623 *timeout = false;
624 while (true) {
625 Thread* thread;
626 {
627 ScopedObjectAccess soa(Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700628 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700629 thread = Thread::FromManagedThread(soa, peer);
630 if (thread == NULL) {
631 LOG(WARNING) << "No such thread for suspend: " << peer;
632 return NULL;
633 }
634 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700635 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636 if (request_suspension) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700637 thread->ModifySuspendCount(soa.Self(), +1, true /* for_debugger */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638 request_suspension = false;
639 did_suspend_request = true;
640 }
641 // IsSuspended on the current thread will fail as the current thread is changed into
642 // Runnable above. As the suspend count is now raised if this is the current thread
643 // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
644 // to just explicitly handle the current thread in the callers to this code.
645 CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
646 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
647 // count, or else we've waited and it has self suspended) or is the current thread, we're
648 // done.
649 if (thread->IsSuspended()) {
650 return thread;
651 }
652 if (total_delay_us >= kTimeoutUs) {
653 LOG(ERROR) << "Thread suspension timed out: " << peer;
654 if (did_suspend_request) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700655 thread->ModifySuspendCount(soa.Self(), -1, true /* for_debugger */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656 }
657 *timeout = true;
658 return NULL;
659 }
660 }
661 // Release locks and come out of runnable state.
662 }
663 for (int i = kMaxMutexLevel; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700664 BaseMutex* held_mutex = Thread::Current()->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700665 if (held_mutex != NULL) {
666 LOG(FATAL) << "Holding " << held_mutex->GetName()
667 << " while sleeping for thread suspension";
668 }
669 }
670 {
671 useconds_t new_delay_us = delay_us * 2;
672 CHECK_GE(new_delay_us, delay_us);
673 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
674 delay_us = new_delay_us;
675 }
676 }
677 if (delay_us == 0) {
678 sched_yield();
679 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
680 delay_us = 500;
681 } else {
682 usleep(delay_us);
683 total_delay_us += delay_us;
684 }
685 }
686}
687
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700688void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700689 std::string group_name;
690 int priority;
691 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700692 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700693
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700694 if (thread != NULL && thread->peer_ != NULL) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700695 ScopedObjectAccess soa(self);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700696 Object* native_peer = soa.Decode<Object*>(thread->peer_);
697 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(native_peer);
698 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(native_peer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700699
Ian Rogers120f1c72012-09-28 17:17:10 -0700700 Object* thread_group =
701 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(native_peer);
702
Elliott Hughesd369bb72011-09-12 14:41:14 -0700703 if (thread_group != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 Field* group_name_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700705 String* group_name_string = reinterpret_cast<String*>(group_name_field->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700706 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
707 }
708 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700709 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700710 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700711
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700712 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700713 if (scheduler_group_name.empty()) {
714 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700715 }
716
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700717 if (thread != NULL) {
718 os << '"' << *thread->name_ << '"';
719 if (is_daemon) {
720 os << " daemon";
721 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700722 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700723 os << " prio=" << priority
724 << " tid=" << thread->GetThinLockId()
725 << " " << thread->GetState() << "\n";
726 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700727 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700728 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700729 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700730 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700731
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700732 if (thread != NULL) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700733 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700734 os << " | group=\"" << group_name << "\""
735 << " sCount=" << thread->suspend_count_
736 << " dsCount=" << thread->debug_suspend_count_
737 << " obj=" << reinterpret_cast<void*>(thread->peer_)
738 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
739 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700740
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700741 os << " | sysTid=" << tid
742 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700743 << " cgrp=" << scheduler_group_name;
744 if (thread != NULL) {
745 int policy;
746 sched_param sp;
747 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
748 os << " sched=" << policy << "/" << sp.sched_priority
749 << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
750 }
751 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700752
753 // Grab the scheduler stats for this thread.
754 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700755 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700756 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
757 } else {
758 scheduler_stats = "0 0 0";
759 }
760
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700761 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700762 int utime = 0;
763 int stime = 0;
764 int task_cpu = 0;
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700765 GetTaskStats(tid, native_thread_state, utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700766
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700767 os << " | state=" << native_thread_state
768 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700769 << " utm=" << utime
770 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700771 << " core=" << task_cpu
772 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
773 if (thread != NULL) {
774 os << " | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
775 << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
776 }
777}
778
779void Thread::DumpState(std::ostream& os) const {
780 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700781}
782
Ian Rogers0399dde2012-06-06 17:09:28 -0700783struct StackDumpVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700784 StackDumpVisitor(std::ostream& os, const Thread* thread, Context* context, bool can_allocate)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700785 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700786 : StackVisitor(thread->GetManagedStack(), thread->GetTraceStack(), context),
787 os(os), thread(thread), can_allocate(can_allocate),
788 last_method(NULL), last_line_number(0), repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700789 }
790
Ian Rogersbdb03912011-09-14 00:55:44 -0700791 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700792 if (frame_count == 0) {
793 os << " (no managed stack frames)\n";
794 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700795 }
796
Ian Rogersb726dcb2012-09-05 08:57:23 -0700797 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700798 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700799 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700800 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700801 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700802 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700803 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700804 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800805 const DexCache* dex_cache = c->GetDexCache();
806 int line_number = -1;
807 if (dex_cache != NULL) { // be tolerant of bad input
808 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
Ian Rogers0399dde2012-06-06 17:09:28 -0700809 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Ian Rogersb861dc02011-11-14 17:00:05 -0800810 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700811 if (line_number == last_line_number && last_method == m) {
812 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700813 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700814 if (repetition_count >= kMaxRepetition) {
815 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
816 }
817 repetition_count = 0;
818 last_line_number = line_number;
819 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700820 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700821 if (repetition_count < kMaxRepetition) {
822 os << " at " << PrettyMethod(m, false);
823 if (m->IsNative()) {
824 os << "(Native method)";
825 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800826 mh.ChangeMethod(m);
827 const char* source_file(mh.GetDeclaringClassSourceFile());
828 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700829 << ":" << line_number << ")";
830 }
831 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700832 if (frame_count == 0) {
833 Monitor::DescribeWait(os, thread);
834 }
835 if (can_allocate) {
836 Monitor::DescribeLocks(os, this);
837 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700838 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700839
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700840 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700841 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700842 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700843 std::ostream& os;
844 const Thread* thread;
845 bool can_allocate;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800846 MethodHelper mh;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700847 AbstractMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700848 int last_line_number;
849 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700850 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700851};
852
Elliott Hughesd92bec42011-09-02 17:04:36 -0700853void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800854 // If we're currently in native code, dump that stack before dumping the managed stack.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700855 if (GetState() == kNative) {
Elliott Hughes46e251b2012-05-22 15:10:45 -0700856 DumpKernelStack(os, GetTid(), " kernel: ", false);
857 DumpNativeStack(os, GetTid(), " native: ", false);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800858 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700859 UniquePtr<Context> context(Context::Create());
860 StackDumpVisitor dumper(os, this, context.get(), !throwing_OutOfMemoryError_);
Ian Rogers0399dde2012-06-06 17:09:28 -0700861 dumper.WalkStack();
Elliott Hughese27955c2011-08-26 15:21:24 -0700862}
863
Elliott Hughesbe759c62011-09-08 19:38:21 -0700864void Thread::ThreadExitCallback(void* arg) {
865 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700866 if (self->thread_exit_check_count_ == 0) {
867 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
868 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
869 self->thread_exit_check_count_ = 1;
870 } else {
871 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
872 }
Carl Shapirob5573532011-07-12 18:22:59 -0700873}
874
Elliott Hughesbe759c62011-09-08 19:38:21 -0700875void Thread::Startup() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700876 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700877 MutexLock mu(*Locks::thread_suspend_count_lock_); // Keep GCC happy.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878 resume_cond_ = new ConditionVariable("Thread resumption condition variable");
879 }
880
Carl Shapirob5573532011-07-12 18:22:59 -0700881 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700882 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700883
884 // Double-check the TLS slot allocation.
885 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800886 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700887 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700888}
Carl Shapirob5573532011-07-12 18:22:59 -0700889
Elliott Hughes038a8062011-09-18 14:12:41 -0700890void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -0700891 Runtime* runtime = Runtime::Current();
892 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700893
Elliott Hughes01158d72011-09-19 19:47:10 -0700894 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700895 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700896 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500897
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700898 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700899}
900
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700901void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700902 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700903}
904
Ian Rogers52673ff2012-06-27 23:25:34 -0700905Thread::Thread(bool daemon)
Ian Rogers0399dde2012-06-06 17:09:28 -0700906 : suspend_count_(0),
907 card_table_(NULL),
908 exception_(NULL),
909 stack_end_(NULL),
910 managed_stack_(),
911 jni_env_(NULL),
912 self_(NULL),
Elliott Hughes47179f72011-10-27 16:44:39 -0700913 peer_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700914 stack_begin_(NULL),
915 stack_size_(0),
916 thin_lock_id_(0),
917 tid_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700918 wait_mutex_(new Mutex("a thread wait mutex")),
919 wait_cond_(new ConditionVariable("a thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700920 wait_monitor_(NULL),
921 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700922 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700923 monitor_enter_object_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700924 top_sirt_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700925 runtime_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700926 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700927 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700928 throwing_OutOfMemoryError_(false),
Ian Rogers0399dde2012-06-06 17:09:28 -0700929 debug_suspend_count_(0),
jeffhaoe343b762011-12-05 16:36:44 -0800930 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800931 trace_stack_(new std::vector<TraceStackFrame>),
Ian Rogers0399dde2012-06-06 17:09:28 -0700932 name_(new std::string(kThreadNameDuringStartup)),
Ian Rogers52673ff2012-06-27 23:25:34 -0700933 daemon_(daemon),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700934 pthread_self_(0),
Ian Rogers52673ff2012-06-27 23:25:34 -0700935 no_thread_suspension_(0),
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700936 last_no_thread_suspension_cause_(NULL),
937 thread_exit_check_count_(0) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700938 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Ian Rogers30e173f2012-09-26 14:35:03 -0700939 state_and_flags_.as_struct.flags = 0;
940 state_and_flags_.as_struct.state = kNative;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800941 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700942}
943
Elliott Hughes7dc51662012-05-16 14:48:43 -0700944bool Thread::IsStillStarting() const {
945 // You might think you can check whether the state is kStarting, but for much of thread startup,
946 // the thread might also be in kVmWait.
947 // You might think you can check whether the peer is NULL, but the peer is actually created and
948 // assigned fairly early on, and needs to be.
949 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
950 // this thread _ever_ entered kRunnable".
951 return (*name_ == kThreadNameDuringStartup);
952}
953
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700954void Thread::AssertNoPendingException() const {
955 if (UNLIKELY(IsExceptionPending())) {
956 ScopedObjectAccess soa(Thread::Current());
957 Throwable* exception = GetException();
958 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
959 }
960}
961
962static void MonitorExitVisitor(const Object* object, void* arg) NO_THREAD_SAFETY_ANALYSIS {
963 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700964 Object* entered_monitor = const_cast<Object*>(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700965 if (self->HoldsLock(entered_monitor)) {
966 LOG(WARNING) << "Calling MonitorExit on object "
967 << object << " (" << PrettyTypeOf(object) << ")"
968 << " left locked by native thread "
969 << *Thread::Current() << " which is detaching";
970 entered_monitor->MonitorExit(self);
971 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700972}
973
Elliott Hughesc0f09332012-03-26 13:27:06 -0700974void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -0700975 Thread* self = this;
976 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700977
Elliott Hughes93e74e82011-09-13 11:07:03 -0700978 if (peer_ != NULL) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700979 // We may need to call user-supplied managed code, do this before final clean-up.
980 HandleUncaughtExceptions();
981 RemoveFromThreadGroup();
Elliott Hughes534da072012-03-27 15:17:42 -0700982
Elliott Hughes29f27422011-09-18 16:02:18 -0700983 // this.vmData = 0;
Ian Rogers120f1c72012-09-28 17:17:10 -0700984 jni_env_->SetIntField(peer_, WellKnownClasses::java_lang_Thread_vmData, 0);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700985
Ian Rogers120f1c72012-09-28 17:17:10 -0700986 {
987 ScopedObjectAccess soa(self);
988 Dbg::PostThreadDeath(self);
989 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700990
Elliott Hughes29f27422011-09-18 16:02:18 -0700991 // Thread.join() is implemented as an Object.wait() on the Thread.lock
992 // object. Signal anyone who is waiting.
Ian Rogers120f1c72012-09-28 17:17:10 -0700993 ScopedLocalRef<jobject> lock(jni_env_,
994 jni_env_->GetObjectField(peer_,
995 WellKnownClasses::java_lang_Thread_lock));
Elliott Hughes038a8062011-09-18 14:12:41 -0700996 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Ian Rogers120f1c72012-09-28 17:17:10 -0700997 if (lock.get() != NULL) {
998 jni_env_->MonitorEnter(lock.get());
999 jni_env_->CallVoidMethod(lock.get(), WellKnownClasses::java_lang_Object_notify);
1000 jni_env_->MonitorExit(lock.get());
Elliott Hughes5f791332011-09-15 17:45:30 -07001001 }
1002 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001003
1004 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
1005 if (jni_env_ != NULL) {
1006 jni_env_->monitors.VisitRoots(MonitorExitVisitor, self);
1007 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001008}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001009
Elliott Hughesc0f09332012-03-26 13:27:06 -07001010Thread::~Thread() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001011 if (jni_env_ != NULL && peer_ != NULL) {
1012 // If pthread_create fails we don't have a jni env here.
1013 jni_env_->DeleteGlobalRef(peer_);
1014 }
1015 peer_ = NULL;
1016
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001017 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001018 jni_env_ = NULL;
1019
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001020 CHECK_NE(GetState(), kRunnable);
1021 // We may be deleting a still born thread.
1022 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001023
1024 delete wait_cond_;
1025 delete wait_mutex_;
1026
Ian Rogers776ac1f2012-04-13 23:36:36 -07001027#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -07001028 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -07001029#endif
Elliott Hughes475fc232011-10-25 15:00:35 -07001030
1031 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -08001032 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -08001033 delete name_;
Elliott Hughesd8af1592012-04-16 20:40:15 -07001034
1035 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001036}
1037
Ian Rogers120f1c72012-09-28 17:17:10 -07001038void Thread::HandleUncaughtExceptions() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001039 if (!IsExceptionPending()) {
1040 return;
1041 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001042
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001043 // Get and clear the exception.
Ian Rogers120f1c72012-09-28 17:17:10 -07001044 ScopedLocalRef<jthrowable> exception(jni_env_, jni_env_->ExceptionOccurred());
1045 jni_env_->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001046
1047 // If the thread has its own handler, use that.
Ian Rogers120f1c72012-09-28 17:17:10 -07001048 ScopedLocalRef<jobject> handler(jni_env_,
1049 jni_env_->GetObjectField(peer_,
1050 WellKnownClasses::java_lang_Thread_uncaughtHandler));
1051 if (handler.get() == NULL) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001052 // Otherwise use the thread group's default handler.
Ian Rogers120f1c72012-09-28 17:17:10 -07001053 handler.reset(jni_env_->GetObjectField(peer_, WellKnownClasses::java_lang_Thread_group));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001054 }
1055
1056 // Call the handler.
Ian Rogers120f1c72012-09-28 17:17:10 -07001057 jni_env_->CallVoidMethod(handler.get(),
1058 WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException,
1059 peer_, exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001060
1061 // If the handler threw, clear that exception too.
Ian Rogers120f1c72012-09-28 17:17:10 -07001062 jni_env_->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001063}
1064
Ian Rogers120f1c72012-09-28 17:17:10 -07001065void Thread::RemoveFromThreadGroup() {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001066 // this.group.removeThread(this);
1067 // group can be null if we're in the compiler or a test.
Ian Rogers120f1c72012-09-28 17:17:10 -07001068 ScopedLocalRef<jobject> group(jni_env_,
1069 jni_env_->GetObjectField(peer_,
1070 WellKnownClasses::java_lang_Thread_group));
1071 if (group.get() != NULL) {
1072 jni_env_->CallVoidMethod(group.get(), WellKnownClasses::java_lang_ThreadGroup_removeThread,
1073 peer_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001074 }
1075}
1076
Ian Rogers408f79a2011-08-23 18:22:33 -07001077size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001078 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001079 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001080 count += cur->NumberOfReferences();
1081 }
1082 return count;
1083}
1084
Ian Rogers408f79a2011-08-23 18:22:33 -07001085bool Thread::SirtContains(jobject obj) {
1086 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001087 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1088 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001089 return true;
1090 }
1091 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001092 // JNI code invoked from portable code uses shadow frames rather than the SIRT.
1093 return managed_stack_.ShadowFramesContain(sirt_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001094}
1095
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001096void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001097 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001098 size_t num_refs = cur->NumberOfReferences();
1099 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001100 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001101 if (object != NULL) {
1102 visitor(object, arg);
1103 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001104 }
1105 }
1106}
1107
Ian Rogers408f79a2011-08-23 18:22:33 -07001108Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001109 Locks::mutator_lock_->AssertSharedHeld(this);
Ian Rogers408f79a2011-08-23 18:22:33 -07001110 if (obj == NULL) {
1111 return NULL;
1112 }
1113 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1114 IndirectRefKind kind = GetIndirectRefKind(ref);
1115 Object* result;
1116 switch (kind) {
1117 case kLocal:
1118 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001119 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001120 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001121 break;
1122 }
1123 case kGlobal:
1124 {
1125 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1126 IndirectReferenceTable& globals = vm->globals;
Ian Rogers81d425b2012-09-27 16:03:43 -07001127 MutexLock mu(this, vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001128 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001129 break;
1130 }
1131 case kWeakGlobal:
1132 {
1133 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1134 IndirectReferenceTable& weak_globals = vm->weak_globals;
Ian Rogers81d425b2012-09-27 16:03:43 -07001135 MutexLock mu(this, vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001136 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001137 if (result == kClearedJniWeakGlobal) {
1138 // This is a special case where it's okay to return NULL.
1139 return NULL;
1140 }
1141 break;
1142 }
1143 case kSirtOrInvalid:
1144 default:
1145 // TODO: make stack indirect reference table lookup more efficient
1146 // Check if this is a local reference in the SIRT
Ian Rogers0399dde2012-06-06 17:09:28 -07001147 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001148 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001149 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001150 // Assume an invalid local reference is actually a direct pointer.
1151 result = reinterpret_cast<Object*>(obj);
1152 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001153 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001154 }
1155 }
1156
1157 if (result == NULL) {
Elliott Hughes3f6635a2012-06-19 13:37:49 -07001158 JniAbortF(NULL, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
Elliott Hughesa2501992011-08-26 19:39:54 -07001159 } else {
1160 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001161 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001162 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001163 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001164 return result;
1165}
1166
Ian Rogers81d425b2012-09-27 16:03:43 -07001167// Implements java.lang.Thread.interrupted.
1168bool Thread::Interrupted() {
1169 MutexLock mu(*wait_mutex_);
1170 bool interrupted = interrupted_;
1171 interrupted_ = false;
1172 return interrupted;
1173}
1174
1175// Implements java.lang.Thread.isInterrupted.
1176bool Thread::IsInterrupted() {
1177 MutexLock mu(*wait_mutex_);
1178 return interrupted_;
1179}
1180
1181void Thread::Interrupt() {
1182 MutexLock mu(*wait_mutex_);
1183 if (interrupted_) {
1184 return;
1185 }
1186 interrupted_ = true;
1187 NotifyLocked();
1188}
1189
1190void Thread::Notify() {
1191 MutexLock mu(*wait_mutex_);
1192 NotifyLocked();
1193}
1194
1195void Thread::NotifyLocked() {
1196 if (wait_monitor_ != NULL) {
1197 wait_cond_->Signal();
1198 }
1199}
1200
Ian Rogers0399dde2012-06-06 17:09:28 -07001201class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001202 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001203 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001204 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001205 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001206 : StackVisitor(stack, trace_stack, NULL),
1207 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001208
Ian Rogersb726dcb2012-09-05 08:57:23 -07001209 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001210 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001211 // Note we also skip the frame if it doesn't have a method (namely the callee
1212 // save frame)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001213 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001214 if (skipping_ && !m->IsRuntimeMethod() &&
1215 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001216 skipping_ = false;
1217 }
1218 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001219 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001220 ++depth_;
1221 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001222 } else {
1223 ++skip_depth_;
1224 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001225 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001226 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001227
1228 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001229 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001230 }
1231
Elliott Hughes29f27422011-09-18 16:02:18 -07001232 int GetSkipDepth() const {
1233 return skip_depth_;
1234 }
1235
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001236 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001237 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001238 uint32_t skip_depth_;
1239 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001240};
1241
Ian Rogers0399dde2012-06-06 17:09:28 -07001242class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001243 public:
Ian Rogers1f539342012-10-03 21:09:42 -07001244 explicit BuildInternalStackTraceVisitor(Thread* self, const ManagedStack* stack,
Ian Rogers0399dde2012-06-06 17:09:28 -07001245 const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001246 int skip_depth)
Ian Rogers1f539342012-10-03 21:09:42 -07001247 : StackVisitor(stack, trace_stack, NULL), self_(self),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001248 skip_depth_(skip_depth), count_(0), dex_pc_trace_(NULL), method_trace_(NULL) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001249
Ian Rogers1f539342012-10-03 21:09:42 -07001250 bool Init(int depth)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001252 // Allocate method trace with an extra slot that will hold the PC trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001253 SirtRef<ObjectArray<Object> >
Ian Rogers1f539342012-10-03 21:09:42 -07001254 method_trace(self_,
1255 Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1));
Ian Rogers0399dde2012-06-06 17:09:28 -07001256 if (method_trace.get() == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001257 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001258 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001259 IntArray* dex_pc_trace = IntArray::Alloc(depth);
1260 if (dex_pc_trace == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001261 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001262 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001263 // Save PC trace in last element of method trace, also places it into the
1264 // object graph.
Ian Rogers0399dde2012-06-06 17:09:28 -07001265 method_trace->Set(depth, dex_pc_trace);
1266 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001267 const char* last_no_suspend_cause =
Ian Rogers1f539342012-10-03 21:09:42 -07001268 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Ian Rogers52673ff2012-06-27 23:25:34 -07001269 CHECK(last_no_suspend_cause == NULL) << last_no_suspend_cause;
Ian Rogers0399dde2012-06-06 17:09:28 -07001270 method_trace_ = method_trace.get();
1271 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001272 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001273 }
1274
Ian Rogers0399dde2012-06-06 17:09:28 -07001275 virtual ~BuildInternalStackTraceVisitor() {
Ian Rogers52673ff2012-06-27 23:25:34 -07001276 if (method_trace_ != NULL) {
Ian Rogers1f539342012-10-03 21:09:42 -07001277 self_->EndAssertNoThreadSuspension(NULL);
Ian Rogers52673ff2012-06-27 23:25:34 -07001278 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001279 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001280
Ian Rogersb726dcb2012-09-05 08:57:23 -07001281 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001282 if (method_trace_ == NULL || dex_pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001283 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001284 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001285 if (skip_depth_ > 0) {
1286 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001287 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001288 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001289 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001290 if (m->IsRuntimeMethod()) {
1291 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001292 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001293 method_trace_->Set(count_, m);
1294 dex_pc_trace_->Set(count_, GetDexPc());
Ian Rogersaaa20802011-09-11 21:47:37 -07001295 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001296 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001297 }
1298
Ian Rogers0399dde2012-06-06 17:09:28 -07001299 ObjectArray<Object>* GetInternalStackTrace() const {
1300 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001301 }
1302
1303 private:
Ian Rogers1f539342012-10-03 21:09:42 -07001304 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001305 // How many more frames to skip.
1306 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001307 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001308 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001309 // Array of dex PC values.
1310 IntArray* dex_pc_trace_;
1311 // 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 -07001312 ObjectArray<Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001313};
1314
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001315jobject Thread::CreateInternalStackTrace(const ScopedObjectAccess& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001316 // Compute depth of stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001317 CountStackDepthVisitor count_visitor(GetManagedStack(), GetTraceStack());
1318 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001319 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001320 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001321
Ian Rogers1f539342012-10-03 21:09:42 -07001322 // Build internal stack trace.
1323 BuildInternalStackTraceVisitor build_trace_visitor(soa.Self(), GetManagedStack(), GetTraceStack(),
Ian Rogers0399dde2012-06-06 17:09:28 -07001324 skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07001325 if (!build_trace_visitor.Init(depth)) {
1326 return NULL; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08001327 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001328 build_trace_visitor.WalkStack();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001329 return soa.AddLocalReference<jobjectArray>(build_trace_visitor.GetInternalStackTrace());
Ian Rogersaaa20802011-09-11 21:47:37 -07001330}
1331
Elliott Hughes01158d72011-09-19 19:47:10 -07001332jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1333 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001334 // Transition into runnable state to work on Object*/Array*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001335 ScopedObjectAccess soa(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001336 // Decode the internal stack trace into the depth, method trace and PC trace
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001337 ObjectArray<Object>* method_trace = soa.Decode<ObjectArray<Object>*>(internal);
Ian Rogers9074b992011-10-26 17:41:55 -07001338 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001339 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1340
1341 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1342
Elliott Hughes01158d72011-09-19 19:47:10 -07001343 jobjectArray result;
1344 ObjectArray<StackTraceElement>* java_traces;
1345 if (output_array != NULL) {
1346 // Reuse the array we were given.
1347 result = output_array;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001348 java_traces = soa.Decode<ObjectArray<StackTraceElement>*>(output_array);
Elliott Hughes01158d72011-09-19 19:47:10 -07001349 // ...adjusting the number of frames we'll write to not exceed the array length.
1350 depth = std::min(depth, java_traces->GetLength());
1351 } else {
1352 // Create java_trace array and place in local reference table
1353 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001354 if (java_traces == NULL) {
1355 return NULL;
1356 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001357 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001358 }
1359
1360 if (stack_depth != NULL) {
1361 *stack_depth = depth;
1362 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001363
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001364 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001365 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001366 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001367 AbstractMethod* method = down_cast<AbstractMethod*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001368 mh.ChangeMethod(method);
Ian Rogers0399dde2012-06-06 17:09:28 -07001369 uint32_t dex_pc = pc_trace->Get(i);
1370 int32_t line_number = mh.GetLineNumFromDexPC(dex_pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001371 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001372 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001373 const char* descriptor = mh.GetDeclaringClassDescriptor();
1374 CHECK(descriptor != NULL);
1375 std::string class_name(PrettyDescriptor(descriptor));
Ian Rogers1f539342012-10-03 21:09:42 -07001376 SirtRef<String> class_name_object(soa.Self(),
1377 String::AllocFromModifiedUtf8(class_name.c_str()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001378 if (class_name_object.get() == NULL) {
1379 return NULL;
1380 }
Ian Rogers48601312011-12-07 16:45:19 -08001381 const char* method_name = mh.GetName();
1382 CHECK(method_name != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07001383 SirtRef<String> method_name_object(soa.Self(), String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001384 if (method_name_object.get() == NULL) {
1385 return NULL;
1386 }
Ian Rogers48601312011-12-07 16:45:19 -08001387 const char* source_file = mh.GetDeclaringClassSourceFile();
Ian Rogers1f539342012-10-03 21:09:42 -07001388 SirtRef<String> source_name_object(soa.Self(), String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001389 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001390 method_name_object.get(),
1391 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001392 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001393 if (obj == NULL) {
1394 return NULL;
1395 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001396#ifdef MOVING_GARBAGE_COLLECTOR
1397 // Re-read after potential GC
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001398 java_traces = Decode<ObjectArray<Object>*>(soa.Env(), result);
1399 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(soa.Env(), internal));
Ian Rogersaaa20802011-09-11 21:47:37 -07001400 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1401#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001402 java_traces->Set(i, obj);
1403 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001404 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001405}
1406
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001407void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001408 va_list args;
1409 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001410 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001411 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001412}
1413
1414void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1415 std::string msg;
1416 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001417 ThrowNewException(exception_class_descriptor, msg.c_str());
1418}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001419
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001420void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001421 AssertNoPendingException(); // Callers should either clear or call ThrowNewWrappedException.
Elliott Hughesa4f94742012-05-29 16:28:38 -07001422 ThrowNewWrappedException(exception_class_descriptor, msg);
1423}
1424
1425void Thread::ThrowNewWrappedException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001426 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001427 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001428 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001429 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001430 descriptor.erase(descriptor.length() - 1);
1431
1432 JNIEnv* env = GetJniEnv();
Elliott Hughesa4f94742012-05-29 16:28:38 -07001433 jobject cause = env->ExceptionOccurred();
1434 env->ExceptionClear();
1435
Elliott Hughes726079d2011-10-07 18:43:44 -07001436 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001437 if (exception_class.get() == NULL) {
1438 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1439 << PrettyTypeOf(GetException());
1440 CHECK(IsExceptionPending());
1441 return;
1442 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001443 if (!Runtime::Current()->IsStarted()) {
1444 // Something is trying to throw an exception without a started
1445 // runtime, which is the common case in the compiler. We won't be
1446 // able to invoke the constructor of the exception, so use
1447 // AllocObject which will not invoke a constructor.
1448 ScopedLocalRef<jthrowable> exception(
1449 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1450 if (exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001451 ScopedObjectAccessUnchecked soa(env);
1452 Throwable* t = reinterpret_cast<Throwable*>(soa.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001453 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001454 soa.Self()->SetException(t);
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001455 } else {
1456 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1457 << PrettyTypeOf(GetException());
1458 CHECK(IsExceptionPending());
1459 }
1460 return;
1461 }
Elliott Hughesa4f94742012-05-29 16:28:38 -07001462 int rc = ::art::ThrowNewException(env, exception_class.get(), msg, cause);
Elliott Hughes30646832011-10-13 16:59:46 -07001463 if (rc != JNI_OK) {
1464 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1465 << PrettyTypeOf(GetException());
1466 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001467 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001468}
1469
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001470void Thread::ThrowOutOfMemoryError(const char* msg) {
1471 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1472 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001473 if (!throwing_OutOfMemoryError_) {
1474 throwing_OutOfMemoryError_ = true;
Elliott Hughes57aba862012-06-20 14:00:47 -07001475 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001476 } else {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001477 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
1478 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001479 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001480 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001481}
1482
Elliott Hughes498508c2011-10-17 14:58:22 -07001483Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001484 return Thread::Current();
1485}
1486
1487void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001488 std::ostringstream ss;
1489 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001490 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001491 // log to stderr for debugging command line processes
1492 std::cerr << str;
1493#ifdef HAVE_ANDROID_OS
1494 // log to logcat for debugging frameworks processes
1495 LOG(INFO) << str;
1496#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001497}
1498
Elliott Hughes98e20172012-04-24 15:38:13 -07001499struct EntryPointInfo {
1500 uint32_t offset;
1501 const char* name;
1502};
1503#define ENTRY_POINT_INFO(x) { ENTRYPOINT_OFFSET(x), #x }
1504static const EntryPointInfo gThreadEntryPointInfo[] = {
1505 ENTRY_POINT_INFO(pAllocArrayFromCode),
1506 ENTRY_POINT_INFO(pAllocArrayFromCodeWithAccessCheck),
1507 ENTRY_POINT_INFO(pAllocObjectFromCode),
1508 ENTRY_POINT_INFO(pAllocObjectFromCodeWithAccessCheck),
1509 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCode),
1510 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCodeWithAccessCheck),
1511 ENTRY_POINT_INFO(pInstanceofNonTrivialFromCode),
1512 ENTRY_POINT_INFO(pCanPutArrayElementFromCode),
1513 ENTRY_POINT_INFO(pCheckCastFromCode),
1514 ENTRY_POINT_INFO(pDebugMe),
1515 ENTRY_POINT_INFO(pUpdateDebuggerFromCode),
1516 ENTRY_POINT_INFO(pInitializeStaticStorage),
1517 ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccessFromCode),
1518 ENTRY_POINT_INFO(pInitializeTypeFromCode),
1519 ENTRY_POINT_INFO(pResolveStringFromCode),
Ian Rogers474b6da2012-09-25 00:20:38 -07001520 ENTRY_POINT_INFO(pGetAndClearException),
Elliott Hughes98e20172012-04-24 15:38:13 -07001521 ENTRY_POINT_INFO(pSet32Instance),
1522 ENTRY_POINT_INFO(pSet32Static),
1523 ENTRY_POINT_INFO(pSet64Instance),
1524 ENTRY_POINT_INFO(pSet64Static),
1525 ENTRY_POINT_INFO(pSetObjInstance),
1526 ENTRY_POINT_INFO(pSetObjStatic),
1527 ENTRY_POINT_INFO(pGet32Instance),
1528 ENTRY_POINT_INFO(pGet32Static),
1529 ENTRY_POINT_INFO(pGet64Instance),
1530 ENTRY_POINT_INFO(pGet64Static),
1531 ENTRY_POINT_INFO(pGetObjInstance),
1532 ENTRY_POINT_INFO(pGetObjStatic),
1533 ENTRY_POINT_INFO(pHandleFillArrayDataFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001534 ENTRY_POINT_INFO(pFindNativeMethod),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 ENTRY_POINT_INFO(pJniMethodStart),
1536 ENTRY_POINT_INFO(pJniMethodStartSynchronized),
1537 ENTRY_POINT_INFO(pJniMethodEnd),
1538 ENTRY_POINT_INFO(pJniMethodEndSynchronized),
1539 ENTRY_POINT_INFO(pJniMethodEndWithReference),
1540 ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
Elliott Hughes98e20172012-04-24 15:38:13 -07001541 ENTRY_POINT_INFO(pLockObjectFromCode),
1542 ENTRY_POINT_INFO(pUnlockObjectFromCode),
1543 ENTRY_POINT_INFO(pCmpgDouble),
1544 ENTRY_POINT_INFO(pCmpgFloat),
1545 ENTRY_POINT_INFO(pCmplDouble),
1546 ENTRY_POINT_INFO(pCmplFloat),
1547 ENTRY_POINT_INFO(pDadd),
1548 ENTRY_POINT_INFO(pDdiv),
1549 ENTRY_POINT_INFO(pDmul),
1550 ENTRY_POINT_INFO(pDsub),
1551 ENTRY_POINT_INFO(pF2d),
1552 ENTRY_POINT_INFO(pFmod),
Ian Rogers0183dd72012-09-17 23:06:51 -07001553 ENTRY_POINT_INFO(pSqrt),
Elliott Hughes98e20172012-04-24 15:38:13 -07001554 ENTRY_POINT_INFO(pI2d),
1555 ENTRY_POINT_INFO(pL2d),
1556 ENTRY_POINT_INFO(pD2f),
1557 ENTRY_POINT_INFO(pFadd),
1558 ENTRY_POINT_INFO(pFdiv),
1559 ENTRY_POINT_INFO(pFmodf),
1560 ENTRY_POINT_INFO(pFmul),
1561 ENTRY_POINT_INFO(pFsub),
1562 ENTRY_POINT_INFO(pI2f),
1563 ENTRY_POINT_INFO(pL2f),
1564 ENTRY_POINT_INFO(pD2iz),
1565 ENTRY_POINT_INFO(pF2iz),
1566 ENTRY_POINT_INFO(pIdivmod),
1567 ENTRY_POINT_INFO(pD2l),
1568 ENTRY_POINT_INFO(pF2l),
1569 ENTRY_POINT_INFO(pLdiv),
1570 ENTRY_POINT_INFO(pLdivmod),
1571 ENTRY_POINT_INFO(pLmul),
1572 ENTRY_POINT_INFO(pShlLong),
1573 ENTRY_POINT_INFO(pShrLong),
1574 ENTRY_POINT_INFO(pUshrLong),
1575 ENTRY_POINT_INFO(pIndexOf),
1576 ENTRY_POINT_INFO(pMemcmp16),
1577 ENTRY_POINT_INFO(pStringCompareTo),
1578 ENTRY_POINT_INFO(pMemcpy),
1579 ENTRY_POINT_INFO(pUnresolvedDirectMethodTrampolineFromCode),
1580 ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
1581 ENTRY_POINT_INFO(pInvokeInterfaceTrampoline),
1582 ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
1583 ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
1584 ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
1585 ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
1586 ENTRY_POINT_INFO(pCheckSuspendFromCode),
1587 ENTRY_POINT_INFO(pTestSuspendFromCode),
1588 ENTRY_POINT_INFO(pDeliverException),
1589 ENTRY_POINT_INFO(pThrowAbstractMethodErrorFromCode),
1590 ENTRY_POINT_INFO(pThrowArrayBoundsFromCode),
1591 ENTRY_POINT_INFO(pThrowDivZeroFromCode),
1592 ENTRY_POINT_INFO(pThrowNoSuchMethodFromCode),
1593 ENTRY_POINT_INFO(pThrowNullPointerFromCode),
1594 ENTRY_POINT_INFO(pThrowStackOverflowFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001595};
1596#undef ENTRY_POINT_INFO
1597
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001598void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1599 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes98e20172012-04-24 15:38:13 -07001600
1601#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 -07001602 DO_THREAD_OFFSET(state_and_flags_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001603 DO_THREAD_OFFSET(card_table_);
1604 DO_THREAD_OFFSET(exception_);
1605 DO_THREAD_OFFSET(jni_env_);
1606 DO_THREAD_OFFSET(self_);
1607 DO_THREAD_OFFSET(stack_end_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001608 DO_THREAD_OFFSET(suspend_count_);
1609 DO_THREAD_OFFSET(thin_lock_id_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001610 //DO_THREAD_OFFSET(top_of_managed_stack_);
1611 //DO_THREAD_OFFSET(top_of_managed_stack_pc_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001612 DO_THREAD_OFFSET(top_sirt_);
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001613#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001614
1615 size_t entry_point_count = arraysize(gThreadEntryPointInfo);
1616 CHECK_EQ(entry_point_count * size_of_pointers, sizeof(EntryPoints));
1617 uint32_t expected_offset = OFFSETOF_MEMBER(Thread, entrypoints_);
1618 for (size_t i = 0; i < entry_point_count; ++i) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001619 CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset) << gThreadEntryPointInfo[i].name;
Elliott Hughes98e20172012-04-24 15:38:13 -07001620 expected_offset += size_of_pointers;
1621 if (gThreadEntryPointInfo[i].offset == offset) {
1622 os << gThreadEntryPointInfo[i].name;
1623 return;
1624 }
1625 }
1626 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001627}
1628
Ian Rogers0399dde2012-06-06 17:09:28 -07001629static const bool kDebugExceptionDelivery = false;
1630class CatchBlockStackVisitor : public StackVisitor {
Ian Rogersbdb03912011-09-14 00:55:44 -07001631 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001632 CatchBlockStackVisitor(Thread* self, Throwable* exception)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001633 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers0399dde2012-06-06 17:09:28 -07001634 : StackVisitor(self->GetManagedStack(), self->GetTraceStack(), self->GetLongJumpContext()),
1635 self_(self), exception_(exception), to_find_(exception->GetClass()), throw_method_(NULL),
1636 throw_frame_id_(0), throw_dex_pc_(0), handler_quick_frame_(NULL),
1637 handler_quick_frame_pc_(0), handler_dex_pc_(0), native_method_count_(0),
Ian Rogers57b86d42012-03-27 16:05:41 -07001638 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers52673ff2012-06-27 23:25:34 -07001639 // Exception not in root sets, can't allow GC.
1640 last_no_assert_suspension_cause_ = self->StartAssertNoThreadSuspension("Finding catch block");
1641 }
1642
1643 ~CatchBlockStackVisitor() {
1644 LOG(FATAL) << "UNREACHABLE"; // Expected to take long jump.
Ian Rogers67375ac2011-09-14 00:55:44 -07001645 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001646
Ian Rogersb726dcb2012-09-05 08:57:23 -07001647 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1648 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001649 AbstractMethod* method = GetMethod();
Elliott Hughes530fa002012-03-12 11:44:49 -07001650 if (method == NULL) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001651 // This is the upcall, we remember the frame and last pc so that we may long jump to them.
1652 handler_quick_frame_pc_ = GetCurrentQuickFramePc();
1653 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001654 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001655 }
1656 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001657 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001658 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001659 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001660 } else {
Ian Rogers0399dde2012-06-06 17:09:28 -07001661 if (throw_method_ == NULL) {
1662 throw_method_ = method;
1663 throw_frame_id_ = GetFrameId();
1664 throw_dex_pc_ = GetDexPc();
Ian Rogers67375ac2011-09-14 00:55:44 -07001665 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001666 if (method->IsNative()) {
1667 native_method_count_++;
1668 } else {
1669 // Unwind stack when an exception occurs during method tracing
1670 if (UNLIKELY(method_tracing_active_ && IsTraceExitPc(GetCurrentQuickFramePc()))) {
buzbee8320f382012-09-11 16:29:42 -07001671 uintptr_t pc = TraceMethodUnwindFromCode(Thread::Current());
Ian Rogers0c7abda2012-09-19 13:33:42 -07001672 dex_pc = method->ToDexPc(pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001673 } else {
1674 dex_pc = GetDexPc();
1675 }
1676 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001677 }
1678 if (dex_pc != DexFile::kDexNoIndex) {
1679 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1680 if (found_dex_pc != DexFile::kDexNoIndex) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001681 handler_dex_pc_ = found_dex_pc;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001682 handler_quick_frame_pc_ = method->ToNativePc(found_dex_pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001683 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001684 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001685 }
1686 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001687 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001688 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001689
Ian Rogersb726dcb2012-09-05 08:57:23 -07001690 void DoLongJump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001691 AbstractMethod* catch_method = *handler_quick_frame_;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001692 Dbg::PostException(self_, throw_frame_id_, throw_method_, throw_dex_pc_,
Ian Rogers0399dde2012-06-06 17:09:28 -07001693 catch_method, handler_dex_pc_, exception_);
1694 if (kDebugExceptionDelivery) {
1695 if (catch_method == NULL) {
1696 LOG(INFO) << "Handler is upcall";
1697 } else {
1698 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1699 const DexFile& dex_file =
1700 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1701 int line_number = dex_file.GetLineNumFromPC(catch_method, handler_dex_pc_);
1702 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
1703 }
1704 }
Ian Rogers52673ff2012-06-27 23:25:34 -07001705 self_->SetException(exception_); // Exception back in root set.
1706 self_->EndAssertNoThreadSuspension(last_no_assert_suspension_cause_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001707 // Place context back on thread so it will be available when we continue.
1708 self_->ReleaseLongJumpContext(context_);
1709 context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
1710 CHECK_NE(handler_quick_frame_pc_, 0u);
1711 context_->SetPC(handler_quick_frame_pc_);
1712 context_->SmashCallerSaves();
1713 context_->DoLongJump();
1714 }
1715
1716 private:
1717 Thread* self_;
1718 Throwable* exception_;
1719 // The type of the exception catch block to find.
Ian Rogersbdb03912011-09-14 00:55:44 -07001720 Class* to_find_;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001721 AbstractMethod* throw_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001722 JDWP::FrameId throw_frame_id_;
1723 uint32_t throw_dex_pc_;
1724 // Quick frame with found handler or last frame if no handler found.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001725 AbstractMethod** handler_quick_frame_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001726 // PC to branch to for the handler.
1727 uintptr_t handler_quick_frame_pc_;
1728 // Associated dex PC.
1729 uint32_t handler_dex_pc_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001730 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1731 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001732 // Is method tracing active?
1733 const bool method_tracing_active_;
Ian Rogers52673ff2012-06-27 23:25:34 -07001734 // Support for nesting no thread suspension checks.
1735 const char* last_no_assert_suspension_cause_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001736};
1737
Ian Rogersff1ed472011-09-20 13:46:24 -07001738void Thread::DeliverException() {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001739 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001740 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001741 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001742 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001743 ClearException();
1744 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001745 String* msg = exception->GetDetailMessage();
1746 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1747 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
Elliott Hughesc073b072012-05-24 19:29:17 -07001748 << ": " << str_msg << "\n");
Ian Rogers28ad40d2011-10-27 15:19:26 -07001749 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001750 CatchBlockStackVisitor catch_finder(this, exception);
1751 catch_finder.WalkStack(true);
1752 catch_finder.DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001753 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001754}
1755
Ian Rogersbdb03912011-09-14 00:55:44 -07001756Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001757 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001758 if (result == NULL) {
1759 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07001760 } else {
1761 long_jump_context_ = NULL; // Avoid context being shared.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001762 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001763 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001764}
1765
Mathieu Chartier66f19252012-09-18 08:57:04 -07001766AbstractMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, size_t* frame_id) const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001767 struct CurrentMethodVisitor : public StackVisitor {
1768 CurrentMethodVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001769 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001770 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001771 : StackVisitor(stack, trace_stack, NULL), method_(NULL), dex_pc_(0), frame_id_(0) {}
Elliott Hughes8be2d402012-02-23 14:22:41 -08001772
Ian Rogersb726dcb2012-09-05 08:57:23 -07001773 virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001774 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001775 if (m->IsRuntimeMethod()) {
1776 // Continue if this is a runtime method.
1777 return true;
1778 }
1779 method_ = m;
1780 dex_pc_ = GetDexPc();
1781 frame_id_ = GetFrameId();
1782 return false;
1783 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001784 AbstractMethod* method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001785 uint32_t dex_pc_;
1786 size_t frame_id_;
1787 };
1788
1789 CurrentMethodVisitor visitor(GetManagedStack(), GetTraceStack());
1790 visitor.WalkStack(false);
1791 if (dex_pc != NULL) {
1792 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001793 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001794 if (frame_id != NULL) {
1795 *frame_id = visitor.frame_id_;
jeffhao33dc7712011-11-09 17:54:24 -08001796 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001797 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08001798}
1799
Elliott Hughes5f791332011-09-15 17:45:30 -07001800bool Thread::HoldsLock(Object* object) {
1801 if (object == NULL) {
1802 return false;
1803 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001804 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001805}
1806
Ian Rogers0399dde2012-06-06 17:09:28 -07001807class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001808 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001809 ReferenceMapVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001810 Context* context, Heap::RootVisitor* root_visitor, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001811 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersca190662012-06-26 15:45:57 -07001812 : StackVisitor(stack, trace_stack, context), root_visitor_(root_visitor), arg_(arg) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07001813
Ian Rogersb726dcb2012-09-05 08:57:23 -07001814 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001815 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001816 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
1817 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001818 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001819 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
1820 if (shadow_frame != NULL) {
1821 shadow_frame->VisitRoots(root_visitor_, arg_);
1822 } else {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001823 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001824 // Process register map (which native and runtime methods don't have)
Ian Rogers640495b2012-06-22 15:15:47 -07001825 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001826 const uint8_t* native_gc_map = m->GetNativeGcMap();
1827 CHECK(native_gc_map != NULL) << PrettyMethod(m);
1828 mh_.ChangeMethod(m);
1829 const DexFile::CodeItem* code_item = mh_.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001830 DCHECK(code_item != NULL) << PrettyMethod(m); // Can't be NULL or how would we compile its instructions?
Ian Rogers0c7abda2012-09-19 13:33:42 -07001831 NativePcOffsetToReferenceMap map(native_gc_map);
Ian Rogers0399dde2012-06-06 17:09:28 -07001832 size_t num_regs = std::min(map.RegWidth() * 8,
1833 static_cast<size_t>(code_item->registers_size_));
Ian Rogers0c7abda2012-09-19 13:33:42 -07001834 if (num_regs > 0) {
1835 const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
1836 DCHECK(reg_bitmap != NULL);
1837 const VmapTable vmap_table(m->GetVmapTableRaw());
1838 uint32_t core_spills = m->GetCoreSpillMask();
1839 uint32_t fp_spills = m->GetFpSpillMask();
1840 size_t frame_size = m->GetFrameSizeInBytes();
1841 // For all dex registers in the bitmap
Mathieu Chartier66f19252012-09-18 08:57:04 -07001842 AbstractMethod** cur_quick_frame = GetCurrentQuickFrame();
Ian Rogers0c7abda2012-09-19 13:33:42 -07001843 DCHECK(cur_quick_frame != NULL);
1844 for (size_t reg = 0; reg < num_regs; ++reg) {
1845 // Does this register hold a reference?
1846 if (TestBitmap(reg, reg_bitmap)) {
1847 uint32_t vmap_offset;
1848 Object* ref;
1849 if (vmap_table.IsInContext(reg, vmap_offset)) {
1850 // Compute the register we need to load from the context
1851 uint32_t spill_mask = core_spills;
1852 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1853 uint32_t matches = 0;
1854 uint32_t spill_shifts = 0;
1855 while (matches != (vmap_offset + 1)) {
1856 DCHECK_NE(spill_mask, 0u);
1857 matches += spill_mask & 1; // Add 1 if the low bit is set
1858 spill_mask >>= 1;
1859 spill_shifts++;
1860 }
1861 spill_shifts--; // wind back one as we want the last match
1862 ref = reinterpret_cast<Object*>(GetGPR(spill_shifts));
1863 } else {
1864 ref = reinterpret_cast<Object*>(GetVReg(cur_quick_frame, code_item, core_spills,
1865 fp_spills, frame_size, reg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001866 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07001867 if (ref != NULL) {
1868 root_visitor_(ref, arg_);
1869 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001870 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001871 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001872 }
1873 }
1874 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001875 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001876 }
1877
1878 private:
1879 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1880 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1881 }
1882
Ian Rogers0c7abda2012-09-19 13:33:42 -07001883 // Call-back when we visit a root.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001884 Heap::RootVisitor* root_visitor_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001885 // Argument to call-back.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001886 void* arg_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001887 // A method helper we keep around to avoid dex file/cache re-computations.
1888 MethodHelper mh_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001889};
1890
1891void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001892 if (exception_ != NULL) {
1893 visitor(exception_, arg);
1894 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001895 if (class_loader_override_ != NULL) {
1896 visitor(class_loader_override_, arg);
1897 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001898 jni_env_->locals.VisitRoots(visitor, arg);
1899 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001900
1901 SirtVisitRoots(visitor, arg);
1902
Ian Rogersd6b1f612011-09-27 13:38:14 -07001903 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001904 Context* context = GetLongJumpContext();
1905 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context, visitor, arg);
1906 mapper.WalkStack();
1907 ReleaseLongJumpContext(context);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001908}
1909
jeffhao25045522012-03-13 19:34:37 -07001910#if VERIFY_OBJECT_ENABLED
Ian Rogers0399dde2012-06-06 17:09:28 -07001911static void VerifyObject(const Object* obj, void* arg) {
1912 Heap* heap = reinterpret_cast<Heap*>(arg);
1913 heap->VerifyObject(obj);
jeffhao25045522012-03-13 19:34:37 -07001914}
1915
1916void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07001917 UniquePtr<Context> context(Context::Create());
Ian Rogers67054b52012-06-26 16:02:10 -07001918 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context.get(), VerifyObject,
Ian Rogers0399dde2012-06-06 17:09:28 -07001919 Runtime::Current()->GetHeap());
1920 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07001921}
1922#endif
1923
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001924// Set the stack end to that to be used during a stack overflow
1925void Thread::SetStackEndForStackOverflow() {
1926 // During stack overflow we allow use of the full stack
1927 if (stack_end_ == stack_begin_) {
1928 DumpStack(std::cerr);
1929 LOG(FATAL) << "Need to increase kStackOverflowReservedBytes (currently "
1930 << kStackOverflowReservedBytes << ")";
1931 }
1932
1933 stack_end_ = stack_begin_;
1934}
1935
Elliott Hughes330304d2011-08-12 14:28:05 -07001936std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001937 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07001938 return os;
1939}
1940
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001941#ifndef NDEBUG
1942void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
1943 CHECK_EQ(0u, no_thread_suspension_) << last_no_thread_suspension_cause_;
1944 if (check_locks) {
1945 bool bad_mutexes_held = false;
1946 for (int i = kMaxMutexLevel; i >= 0; --i) {
1947 // We expect no locks except the mutator_lock_.
1948 if (i != kMutatorLock) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001949 BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001950 if (held_mutex != NULL) {
1951 LOG(ERROR) << "holding \"" << held_mutex->GetName()
1952 << "\" at point where thread suspension is expected";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001953 bad_mutexes_held = true;
1954 }
1955 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001956 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001957 CHECK(!bad_mutexes_held);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001958 }
1959}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001960#endif
Elliott Hughesa4060e52012-03-02 16:51:35 -08001961
Elliott Hughes8daa0922011-09-11 13:46:25 -07001962} // namespace art