blob: f879ee2857055e600423fd0400db117d449c9a4e [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 Rogers57b86d42012-03-27 16:05:41 -070040#include "oat/runtime/context.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070041#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080042#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050043#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070044#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070045#include "runtime_support.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070046#include "scoped_thread_state_change.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070047#include "ScopedLocalRef.h"
Ian Rogers30fab402012-01-23 15:43:46 -080048#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070049#include "stack.h"
50#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070051#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070052#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070054
55namespace art {
56
57pthread_key_t Thread::pthread_key_self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070058ConditionVariable* Thread::resume_cond_;
Carl Shapirob5573532011-07-12 18:22:59 -070059
Elliott Hughes7dc51662012-05-16 14:48:43 -070060static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
61
Ian Rogers5d76c432011-10-31 21:42:49 -070062void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080063 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070064}
65
Elliott Hughes99250ba2012-04-17 11:09:17 -070066#if !defined(__APPLE__)
Elliott Hughes3ea0f422012-04-16 17:01:43 -070067static void UnimplementedEntryPoint() {
68 UNIMPLEMENTED(FATAL);
69}
Elliott Hughes99250ba2012-04-17 11:09:17 -070070#endif
Elliott Hughes3ea0f422012-04-16 17:01:43 -070071
buzbee3ea4ec52011-08-22 17:37:19 -070072void Thread::InitFunctionPointers() {
Elliott Hughes99250ba2012-04-17 11:09:17 -070073#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
Elliott Hughes3ea0f422012-04-16 17:01:43 -070074 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
75 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
76 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
77 for (uintptr_t* it = begin; it != end; ++it) {
78 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
79 }
Elliott Hughes99250ba2012-04-17 11:09:17 -070080#endif
Ian Rogers57b86d42012-03-27 16:05:41 -070081 InitEntryPoints(&entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -070082}
83
84void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
85 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers776ac1f2012-04-13 23:36:36 -070086#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070087 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
Ian Rogers776ac1f2012-04-13 23:36:36 -070088#else
89 UNIMPLEMENTED(FATAL);
90#endif
buzbee3ea4ec52011-08-22 17:37:19 -070091}
92
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070093void Thread::InitTid() {
94 tid_ = ::art::GetTid();
95}
96
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070097void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -070098 // One thread (us) survived the fork, but we have a new tid so we need to
99 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700100 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700101}
102
Brian Carlstrom78128a62011-09-15 17:21:19 -0700103void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700104 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700105 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700106
Elliott Hughes47179f72011-10-27 16:44:39 -0700107 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700108 ScopedObjectAccess soa(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700109 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700110 SirtRef<String> thread_name(self->GetThreadName(soa));
Ian Rogers365c1022012-06-22 15:05:28 -0700111 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
112 }
113
114 Dbg::PostThreadStart(self);
115
116 // Invoke the 'run' method of our java.lang.Thread.
117 CHECK(self->peer_ != NULL);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700118 Object* receiver = soa.Decode<Object*>(self->peer_);
Ian Rogers365c1022012-06-22 15:05:28 -0700119 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700120 AbstractMethod* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Ian Rogers365c1022012-06-22 15:05:28 -0700121 m->Invoke(self, receiver, NULL, NULL);
Elliott Hughes47179f72011-10-27 16:44:39 -0700122 }
123
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700124 // Detach and delete self.
125 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700126
Carl Shapirob5573532011-07-12 18:22:59 -0700127 return NULL;
128}
129
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700130static void SetVmData(const ScopedObjectAccess& soa, Object* managed_thread,
131 Thread* native_thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700134 f->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700135}
136
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, Object* thread_peer) {
138 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
139 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetInt(thread_peer)));
140 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
141 // to stop it from going away.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700142 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 if (result != NULL && !result->IsSuspended()) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700144 Locks::thread_list_lock_->AssertHeld();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700145 }
146 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800147}
148
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700149Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
150 return FromManagedThread(soa, soa.Decode<Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700151}
152
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700153static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700154 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700155 if (stack_size == 0) {
156 stack_size = Runtime::Current()->GetDefaultStackSize();
157 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700158
Brian Carlstrom6414a972012-04-14 14:20:04 -0700159 // Dalvik used the bionic pthread default stack size for native threads,
160 // so include that here to support apps that expect large native stacks.
161 stack_size += 1 * MB;
162
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700163 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
164 if (stack_size < PTHREAD_STACK_MIN) {
165 stack_size = PTHREAD_STACK_MIN;
166 }
167
168 // It's likely that callers are trying to ensure they have at least a certain amount of
169 // stack space, so we should add our reserved space on top of what they requested, rather
170 // than implicitly take it away from them.
171 stack_size += Thread::kStackOverflowReservedBytes;
172
173 // Some systems require the stack size to be a multiple of the system page size, so round up.
174 stack_size = RoundUp(stack_size, kPageSize);
175
176 return stack_size;
177}
178
Elliott Hughesd8af1592012-04-16 20:40:15 -0700179static void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
180 if (sigaltstack(new_stack, old_stack) == -1) {
181 PLOG(FATAL) << "sigaltstack failed";
182 }
183}
184
185static void SetUpAlternateSignalStack() {
186 // Create and set an alternate signal stack.
187 stack_t ss;
188 ss.ss_sp = new uint8_t[SIGSTKSZ];
189 ss.ss_size = SIGSTKSZ;
190 ss.ss_flags = 0;
191 CHECK(ss.ss_sp != NULL);
192 SigAltStack(&ss, NULL);
193
194 // Double-check that it worked.
195 ss.ss_sp = NULL;
196 SigAltStack(NULL, &ss);
197 VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
198}
199
200static void TearDownAlternateSignalStack() {
201 // Get the pointer so we can free the memory.
202 stack_t ss;
203 SigAltStack(NULL, &ss);
204 uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
205
206 // Tell the kernel to stop using it.
207 ss.ss_sp = NULL;
208 ss.ss_flags = SS_DISABLE;
Elliott Hughes4c5231d2012-04-18 16:54:31 -0700209 ss.ss_size = SIGSTKSZ; // Avoid ENOMEM failure with Mac OS' buggy libc.
Elliott Hughesd8af1592012-04-16 20:40:15 -0700210 SigAltStack(&ss, NULL);
211
212 // Free it.
213 delete[] allocated_signal_stack;
214}
215
Ian Rogers52673ff2012-06-27 23:25:34 -0700216void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool daemon) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700217 CHECK(java_peer != NULL);
218
Ian Rogers52673ff2012-06-27 23:25:34 -0700219 Thread* native_thread = new Thread(daemon);
Elliott Hughes47179f72011-10-27 16:44:39 -0700220 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700221 ScopedObjectAccess soa(env);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700222 // Use global JNI ref to hold peer live whilst child thread starts.
223 native_thread->peer_ = env->NewGlobalRef(java_peer);
Ian Rogers365c1022012-06-22 15:05:28 -0700224 stack_size = FixStackSize(stack_size);
225
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700226 // Thread.start is synchronized, so we know that vmData is 0, and know that we're not racing to
227 // assign it.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700228 Object* peer = soa.Decode<Object*>(native_thread->peer_);
229 CHECK(peer != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 SetVmData(soa, peer, native_thread);
Elliott Hughes47179f72011-10-27 16:44:39 -0700231 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700232
233 pthread_t new_pthread;
234 pthread_attr_t attr;
235 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
236 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
237 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
238 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, native_thread);
239 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
240
241 if (UNLIKELY(pthread_create_result != 0)) {
242 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700243 {
244 ScopedObjectAccess soa(env);
245 Object* peer = soa.Decode<Object*>(java_peer);
246 SetVmData(soa, peer, 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700247
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700248 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
249 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
250 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
251 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700252 // If we failed, manually delete the global reference since Thread::Init will not have been run.
253 env->DeleteGlobalRef(native_thread->peer_);
254 native_thread->peer_ = NULL;
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700255 delete native_thread;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256 return;
257 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700258}
259
Elliott Hughes462c9442012-03-23 18:47:50 -0700260void Thread::Init() {
261 // This function does all the initialization that must be run by the native thread it applies to.
262 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
263 // we can handshake with the corresponding native thread when it's ready.) Check this native
264 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700265 CHECK(Thread::Current() == NULL);
266
Elliott Hughesd8af1592012-04-16 20:40:15 -0700267 SetUpAlternateSignalStack();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700268 InitCpu();
269 InitFunctionPointers();
Shih-wei Liao21d28f52012-06-12 05:55:00 -0700270#ifdef ART_USE_GREENLAND_COMPILER
271 InitRuntimeEntryPoints(&runtime_entry_points_);
272#endif
Ian Rogers5d76c432011-10-31 21:42:49 -0700273 InitCardTable();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700274
Elliott Hughes462c9442012-03-23 18:47:50 -0700275 Runtime* runtime = Runtime::Current();
276 CHECK(runtime != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700277 if (runtime->IsShuttingDown()) {
278 UNIMPLEMENTED(WARNING) << "Thread attaching whilst runtime is shutting down";
279 }
Elliott Hughes462c9442012-03-23 18:47:50 -0700280 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Elliott Hughes0d39c122012-06-06 16:41:17 -0700281 pthread_self_ = pthread_self();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700282
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700283 InitTid();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700284 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700285
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700286 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700287
Elliott Hughes93e74e82011-09-13 11:07:03 -0700288 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700289
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700290 runtime->GetThreadList()->Register(this);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700291}
292
Ian Rogers365c1022012-06-22 15:05:28 -0700293Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group) {
Ian Rogers52673ff2012-06-27 23:25:34 -0700294 Thread* self = new Thread(as_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700295 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700296
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700297 CHECK_NE(self->GetState(), kRunnable);
298 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700299
Elliott Hughescac6cc72011-11-03 20:31:21 -0700300 // If we're the main thread, ClassLinker won't be created until after we're attached,
301 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800302 // In the compiler, all threads need this hack, because no-one's going to be getting
303 // a native peer!
304 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700305 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800306 } else {
307 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700308 if (thread_name != NULL) {
309 self->name_->assign(thread_name);
310 ::art::SetThreadName(thread_name);
311 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700312 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700313
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700314 return self;
315}
316
Ian Rogers365c1022012-06-22 15:05:28 -0700317void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
318 Runtime* runtime = Runtime::Current();
319 CHECK(runtime->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700320 JNIEnv* env = jni_env_;
321
Elliott Hughes462c9442012-03-23 18:47:50 -0700322 if (thread_group == NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -0700323 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700324 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700325 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700326 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700327 jboolean thread_is_daemon = as_daemon;
328
Elliott Hugheseac76672012-05-24 21:56:51 -0700329 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700330 if (peer.get() == NULL) {
331 CHECK(IsExceptionPending());
332 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700333 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700334 peer_ = env->NewGlobalRef(peer.get());
Elliott Hugheseac76672012-05-24 21:56:51 -0700335 env->CallNonvirtualVoidMethod(peer.get(),
336 WellKnownClasses::java_lang_Thread,
337 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700338 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700339 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700340
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700341 ScopedObjectAccess soa(this);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700342 Object* native_peer = soa.Decode<Object*>(peer.get());
343 SetVmData(soa, native_peer, Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700344 SirtRef<String> peer_thread_name(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700345 if (peer_thread_name.get() == NULL) {
346 // The Thread constructor should have set the Thread.name to a
347 // non-null value. However, because we can run without code
348 // available (in the compiler, in tests), we manually assign the
349 // fields the constructor should have set.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700350 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
351 SetBoolean(native_peer, thread_is_daemon);
352 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
353 SetObject(native_peer, soa.Decode<Object*>(thread_group));
354 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
355 SetObject(native_peer, soa.Decode<Object*>(thread_name.get()));
356 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
357 SetInt(native_peer, thread_priority);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700358 peer_thread_name.reset(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700359 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700360 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Brian Carlstrom00fae582011-10-28 01:16:28 -0700361 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800362 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700363 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700364}
365
Elliott Hughes899e7892012-01-24 14:57:32 -0800366void Thread::SetThreadName(const char* name) {
367 name_->assign(name);
368 ::art::SetThreadName(name);
369 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
370}
371
Elliott Hughesbe759c62011-09-08 19:38:21 -0700372void Thread::InitStackHwm() {
Elliott Hughese1884192012-04-23 12:38:15 -0700373 void* stack_base;
374 size_t stack_size;
375 GetThreadStack(stack_base, stack_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700376
377 // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
Elliott Hughese1884192012-04-23 12:38:15 -0700378 VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
379
380 stack_begin_ = reinterpret_cast<byte*>(stack_base);
381 stack_size_ = stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700382
Ian Rogers932746a2011-09-22 18:57:50 -0700383 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800384 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700385 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700386
Elliott Hughese1884192012-04-23 12:38:15 -0700387 // TODO: move this into the Linux GetThreadStack implementation.
388#if !defined(__APPLE__)
Elliott Hughes36ecb782012-04-17 16:55:45 -0700389 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
390 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
391 // will be broken because we'll die long before we get close to 2GB.
392 if (thin_lock_id_ == 1) {
393 rlimit stack_limit;
394 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
395 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
396 }
397 if (stack_limit.rlim_cur == RLIM_INFINITY) {
398 // Find the default stack size for new threads...
399 pthread_attr_t default_attributes;
400 size_t default_stack_size;
401 CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
402 CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
403 "default stack size query");
404 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
405
406 // ...and use that as our limit.
407 size_t old_stack_size = stack_size_;
408 stack_size_ = default_stack_size;
409 stack_begin_ += (old_stack_size - stack_size_);
Elliott Hughesfaf4ba02012-05-02 16:12:19 -0700410 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
411 << " to " << PrettySize(stack_size_)
412 << " with base " << reinterpret_cast<void*>(stack_begin_);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700413 }
414 }
Elliott Hughese1884192012-04-23 12:38:15 -0700415#endif
Elliott Hughes36ecb782012-04-17 16:55:45 -0700416
Ian Rogers932746a2011-09-22 18:57:50 -0700417 // Set stack_end_ to the bottom of the stack saving space of stack overflows
418 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700419
420 // Sanity check.
421 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700422 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700423}
424
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425void Thread::ShortDump(std::ostream& os) const {
426 os << "Thread[";
427 if (GetThinLockId() != 0) {
428 // If we're in kStarting, we won't have a thin lock id or tid yet.
429 os << GetThinLockId()
430 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700431 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700432 os << GetState()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700433 << ",Thread*=" << this
434 << ",peer=" << peer_
435 << ",\"" << *name_ << "\""
436 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700437}
438
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700439void Thread::Dump(std::ostream& os) const {
440 DumpState(os);
441 DumpStack(os);
442}
443
444String* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
445 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700446 Object* native_peer = soa.Decode<Object*>(peer_);
447 return (peer_ != NULL) ? reinterpret_cast<String*>(f->GetObject(native_peer)) : NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700448}
449
Elliott Hughesffb465f2012-03-01 18:46:05 -0800450void Thread::GetThreadName(std::string& name) const {
451 name.assign(*name_);
452}
453
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454// Attempt to rectify locks so that we dump thread list with required locks before exiting.
455static void UnsafeLogFatalForSuspendCount(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700456 Locks::thread_suspend_count_lock_->Unlock();
457 Locks::mutator_lock_->SharedTryLock();
458 if (!Locks::mutator_lock_->IsSharedHeld()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
460 }
Ian Rogersb726dcb2012-09-05 08:57:23 -0700461 Locks::thread_list_lock_->TryLock();
462 if (!Locks::thread_list_lock_->IsExclusiveHeld()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700463 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
464 }
465 std::ostringstream ss;
466 Runtime::Current()->GetThreadList()->DumpLocked(ss);
467 LOG(FATAL) << self << " suspend count already zero.\n" << ss.str();
468}
469
Ian Rogers474b6da2012-09-25 00:20:38 -0700470void Thread::AtomicSetFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700471 android_atomic_or(flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700472}
473
474void Thread::AtomicClearFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700475 android_atomic_and(-1 ^ flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700476}
477
478ThreadState Thread::SetState(ThreadState new_state) {
479 // Cannot use this code to change into Runnable as changing to Runnable should fail if
480 // old_state_and_flags.suspend_request is true.
481 DCHECK_NE(new_state, kRunnable);
482 DCHECK_EQ(this, Thread::Current());
Ian Rogers30e173f2012-09-26 14:35:03 -0700483 union StateAndFlags old_state_and_flags = state_and_flags_;
484 state_and_flags_.as_struct.state = new_state;
485 return static_cast<ThreadState>(old_state_and_flags.as_struct.state);
Ian Rogers474b6da2012-09-25 00:20:38 -0700486}
487
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488void Thread::ModifySuspendCount(int delta, bool for_debugger) {
489 DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
490 << delta << " " << debug_suspend_count_ << " " << this;
491 DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
Ian Rogersb726dcb2012-09-05 08:57:23 -0700492 Locks::thread_suspend_count_lock_->AssertHeld();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493
494 if (delta == -1 && suspend_count_ <= 0) {
495 // This is expected if you attach a thread during a GC.
496 if (UNLIKELY(!IsStillStarting())) {
497 UnsafeLogFatalForSuspendCount(this);
498 }
499 return;
500 }
501 suspend_count_ += delta;
502 if (for_debugger) {
503 debug_suspend_count_ += delta;
504 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700505 if (suspend_count_ == 0) {
506 AtomicClearFlag(kSuspendRequest);
507 } else {
508 AtomicSetFlag(kSuspendRequest);
509 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510}
511
512void Thread::FullSuspendCheck() {
513 VLOG(threads) << this << " self-suspending";
514 // Make thread appear suspended to other threads, release mutator_lock_.
515 TransitionFromRunnableToSuspended(kSuspended);
516 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
517 TransitionFromSuspendedToRunnable();
518 VLOG(threads) << this << " self-reviving";
519}
520
521void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
522 AssertThreadSuspensionIsAllowable();
Ian Rogers474b6da2012-09-25 00:20:38 -0700523 DCHECK_NE(new_state, kRunnable);
524 DCHECK_EQ(this, Thread::Current());
Ian Rogersc747cff2012-08-31 18:20:08 -0700525 // Change to non-runnable state, thereby appearing suspended to the system.
Ian Rogers474b6da2012-09-25 00:20:38 -0700526 DCHECK_EQ(GetState(), kRunnable);
Ian Rogers30e173f2012-09-26 14:35:03 -0700527 state_and_flags_.as_struct.state = new_state;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700528 // Release share on mutator_lock_.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700529 Locks::mutator_lock_->SharedUnlock();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700530}
531
532ThreadState Thread::TransitionFromSuspendedToRunnable() {
533 bool done = false;
Ian Rogers474b6da2012-09-25 00:20:38 -0700534 ThreadState old_state = GetState();
Ian Rogersc747cff2012-08-31 18:20:08 -0700535 DCHECK_NE(old_state, kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700536 do {
Ian Rogers474b6da2012-09-25 00:20:38 -0700537 Locks::mutator_lock_->AssertNotHeld(); // Otherwise we starve GC..
538 DCHECK_EQ(GetState(), old_state);
539 if (ReadFlag(kSuspendRequest)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700540 // Wait while our suspend count is non-zero.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700541 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers474b6da2012-09-25 00:20:38 -0700542 DCHECK_EQ(GetState(), old_state);
543 while (ReadFlag(kSuspendRequest)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700544 // Re-check when Thread::resume_cond_ is notified.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700545 Thread::resume_cond_->Wait(*Locks::thread_suspend_count_lock_);
Ian Rogers474b6da2012-09-25 00:20:38 -0700546 DCHECK_EQ(GetState(), old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700548 DCHECK_EQ(GetSuspendCount(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700549 }
550 // Re-acquire shared mutator_lock_ access.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700551 Locks::mutator_lock_->SharedLock();
Ian Rogers474b6da2012-09-25 00:20:38 -0700552 // Atomically change from suspended to runnable if no suspend request pending.
Ian Rogers30e173f2012-09-26 14:35:03 -0700553 int16_t old_flags = state_and_flags_.as_struct.flags;
Ian Rogers474b6da2012-09-25 00:20:38 -0700554 if ((old_flags & kSuspendRequest) == 0) {
555 int32_t old_state_and_flags = old_flags | (old_state << 16);
556 int32_t new_state_and_flags = old_flags | (kRunnable << 16);
557 done = android_atomic_cmpxchg(old_state_and_flags, new_state_and_flags,
558 reinterpret_cast<volatile int32_t*>(&state_and_flags_))
559 == 0;
560 }
561 if (!done) {
562 // Failed to transition to Runnable. Release shared mutator_lock_ access and try again.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700563 Locks::mutator_lock_->SharedUnlock();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564 }
565 } while (!done);
566 return old_state;
567}
568
569Thread* Thread::SuspendForDebugger(jobject peer, bool request_suspension, bool* timeout) {
570 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
571 useconds_t total_delay_us = 0;
572 useconds_t delay_us = 0;
573 bool did_suspend_request = false;
574 *timeout = false;
575 while (true) {
576 Thread* thread;
577 {
578 ScopedObjectAccess soa(Thread::Current());
Ian Rogersb726dcb2012-09-05 08:57:23 -0700579 MutexLock mu(*Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700580 thread = Thread::FromManagedThread(soa, peer);
581 if (thread == NULL) {
582 LOG(WARNING) << "No such thread for suspend: " << peer;
583 return NULL;
584 }
585 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700586 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700587 if (request_suspension) {
588 thread->ModifySuspendCount(+1, true /* for_debugger */);
589 request_suspension = false;
590 did_suspend_request = true;
591 }
592 // IsSuspended on the current thread will fail as the current thread is changed into
593 // Runnable above. As the suspend count is now raised if this is the current thread
594 // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
595 // to just explicitly handle the current thread in the callers to this code.
596 CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
597 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
598 // count, or else we've waited and it has self suspended) or is the current thread, we're
599 // done.
600 if (thread->IsSuspended()) {
601 return thread;
602 }
603 if (total_delay_us >= kTimeoutUs) {
604 LOG(ERROR) << "Thread suspension timed out: " << peer;
605 if (did_suspend_request) {
606 thread->ModifySuspendCount(-1, true /* for_debugger */);
607 }
608 *timeout = true;
609 return NULL;
610 }
611 }
612 // Release locks and come out of runnable state.
613 }
614 for (int i = kMaxMutexLevel; i >= 0; --i) {
615 BaseMutex* held_mutex = Thread::Current()->GetHeldMutex(static_cast<MutexLevel>(i));
616 if (held_mutex != NULL) {
617 LOG(FATAL) << "Holding " << held_mutex->GetName()
618 << " while sleeping for thread suspension";
619 }
620 }
621 {
622 useconds_t new_delay_us = delay_us * 2;
623 CHECK_GE(new_delay_us, delay_us);
624 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
625 delay_us = new_delay_us;
626 }
627 }
628 if (delay_us == 0) {
629 sched_yield();
630 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
631 delay_us = 500;
632 } else {
633 usleep(delay_us);
634 total_delay_us += delay_us;
635 }
636 }
637}
638
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700639void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700640 std::string group_name;
641 int priority;
642 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700643
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700644 if (thread != NULL && thread->peer_ != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700645 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700646 Object* native_peer = soa.Decode<Object*>(thread->peer_);
647 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(native_peer);
648 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(native_peer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700649
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700650 Object* thread_group = thread->GetThreadGroup(soa);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700651 if (thread_group != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 Field* group_name_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700653 String* group_name_string = reinterpret_cast<String*>(group_name_field->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700654 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
655 }
656 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700657 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700658 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700659
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700660 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700661 if (scheduler_group_name.empty()) {
662 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700663 }
664
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700665 if (thread != NULL) {
666 os << '"' << *thread->name_ << '"';
667 if (is_daemon) {
668 os << " daemon";
669 }
Ian Rogersb726dcb2012-09-05 08:57:23 -0700670 MutexLock mu(*Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700671 os << " prio=" << priority
672 << " tid=" << thread->GetThinLockId()
673 << " " << thread->GetState() << "\n";
674 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700675 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700676 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700677 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700678 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700679
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700680 if (thread != NULL) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700681 MutexLock mu(*Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700682 os << " | group=\"" << group_name << "\""
683 << " sCount=" << thread->suspend_count_
684 << " dsCount=" << thread->debug_suspend_count_
685 << " obj=" << reinterpret_cast<void*>(thread->peer_)
686 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
687 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700688
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700689 os << " | sysTid=" << tid
690 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700691 << " cgrp=" << scheduler_group_name;
692 if (thread != NULL) {
693 int policy;
694 sched_param sp;
695 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
696 os << " sched=" << policy << "/" << sp.sched_priority
697 << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
698 }
699 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700700
701 // Grab the scheduler stats for this thread.
702 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700703 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700704 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
705 } else {
706 scheduler_stats = "0 0 0";
707 }
708
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700709 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700710 int utime = 0;
711 int stime = 0;
712 int task_cpu = 0;
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700713 GetTaskStats(tid, native_thread_state, utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700714
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700715 os << " | state=" << native_thread_state
716 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700717 << " utm=" << utime
718 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700719 << " core=" << task_cpu
720 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
721 if (thread != NULL) {
722 os << " | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
723 << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
724 }
725}
726
727void Thread::DumpState(std::ostream& os) const {
728 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700729}
730
Ian Rogers0399dde2012-06-06 17:09:28 -0700731struct StackDumpVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700732 StackDumpVisitor(std::ostream& os, const Thread* thread, Context* context, bool can_allocate)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700733 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700734 : StackVisitor(thread->GetManagedStack(), thread->GetTraceStack(), context),
735 os(os), thread(thread), can_allocate(can_allocate),
736 last_method(NULL), last_line_number(0), repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700737 }
738
Ian Rogersbdb03912011-09-14 00:55:44 -0700739 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700740 if (frame_count == 0) {
741 os << " (no managed stack frames)\n";
742 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700743 }
744
Ian Rogersb726dcb2012-09-05 08:57:23 -0700745 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700746 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700747 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700748 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700749 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700750 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700751 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700752 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800753 const DexCache* dex_cache = c->GetDexCache();
754 int line_number = -1;
755 if (dex_cache != NULL) { // be tolerant of bad input
756 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
Ian Rogers0399dde2012-06-06 17:09:28 -0700757 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Ian Rogersb861dc02011-11-14 17:00:05 -0800758 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700759 if (line_number == last_line_number && last_method == m) {
760 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700761 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700762 if (repetition_count >= kMaxRepetition) {
763 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
764 }
765 repetition_count = 0;
766 last_line_number = line_number;
767 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700768 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700769 if (repetition_count < kMaxRepetition) {
770 os << " at " << PrettyMethod(m, false);
771 if (m->IsNative()) {
772 os << "(Native method)";
773 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800774 mh.ChangeMethod(m);
775 const char* source_file(mh.GetDeclaringClassSourceFile());
776 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700777 << ":" << line_number << ")";
778 }
779 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700780 if (frame_count == 0) {
781 Monitor::DescribeWait(os, thread);
782 }
783 if (can_allocate) {
784 Monitor::DescribeLocks(os, this);
785 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700786 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700787
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700788 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700789 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700790 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700791 std::ostream& os;
792 const Thread* thread;
793 bool can_allocate;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800794 MethodHelper mh;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700795 AbstractMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700796 int last_line_number;
797 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700798 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700799};
800
Elliott Hughesd92bec42011-09-02 17:04:36 -0700801void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800802 // If we're currently in native code, dump that stack before dumping the managed stack.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700803 if (GetState() == kNative) {
Elliott Hughes46e251b2012-05-22 15:10:45 -0700804 DumpKernelStack(os, GetTid(), " kernel: ", false);
805 DumpNativeStack(os, GetTid(), " native: ", false);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800806 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700807 UniquePtr<Context> context(Context::Create());
808 StackDumpVisitor dumper(os, this, context.get(), !throwing_OutOfMemoryError_);
Ian Rogers0399dde2012-06-06 17:09:28 -0700809 dumper.WalkStack();
Elliott Hughese27955c2011-08-26 15:21:24 -0700810}
811
Elliott Hughesbe759c62011-09-08 19:38:21 -0700812void Thread::ThreadExitCallback(void* arg) {
813 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700814 if (self->thread_exit_check_count_ == 0) {
815 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
816 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
817 self->thread_exit_check_count_ = 1;
818 } else {
819 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
820 }
Carl Shapirob5573532011-07-12 18:22:59 -0700821}
822
Elliott Hughesbe759c62011-09-08 19:38:21 -0700823void Thread::Startup() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700824 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700825 MutexLock mu(*Locks::thread_suspend_count_lock_); // Keep GCC happy.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826 resume_cond_ = new ConditionVariable("Thread resumption condition variable");
827 }
828
Carl Shapirob5573532011-07-12 18:22:59 -0700829 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700830 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700831
832 // Double-check the TLS slot allocation.
833 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800834 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700835 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700836}
Carl Shapirob5573532011-07-12 18:22:59 -0700837
Elliott Hughes038a8062011-09-18 14:12:41 -0700838void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -0700839 Runtime* runtime = Runtime::Current();
840 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700841
Elliott Hughes01158d72011-09-19 19:47:10 -0700842 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700843 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700844 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500845
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700846 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700847}
848
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700849void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700850 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700851}
852
Ian Rogers52673ff2012-06-27 23:25:34 -0700853Thread::Thread(bool daemon)
Ian Rogers0399dde2012-06-06 17:09:28 -0700854 : suspend_count_(0),
855 card_table_(NULL),
856 exception_(NULL),
857 stack_end_(NULL),
858 managed_stack_(),
859 jni_env_(NULL),
860 self_(NULL),
Elliott Hughes47179f72011-10-27 16:44:39 -0700861 peer_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700862 stack_begin_(NULL),
863 stack_size_(0),
864 thin_lock_id_(0),
865 tid_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700866 wait_mutex_(new Mutex("a thread wait mutex")),
867 wait_cond_(new ConditionVariable("a thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700868 wait_monitor_(NULL),
869 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700870 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700871 monitor_enter_object_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700872 top_sirt_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700873 runtime_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700874 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700875 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700876 throwing_OutOfMemoryError_(false),
Ian Rogers0399dde2012-06-06 17:09:28 -0700877 debug_suspend_count_(0),
jeffhaoe343b762011-12-05 16:36:44 -0800878 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800879 trace_stack_(new std::vector<TraceStackFrame>),
Ian Rogers0399dde2012-06-06 17:09:28 -0700880 name_(new std::string(kThreadNameDuringStartup)),
Ian Rogers52673ff2012-06-27 23:25:34 -0700881 daemon_(daemon),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700882 pthread_self_(0),
Ian Rogers52673ff2012-06-27 23:25:34 -0700883 no_thread_suspension_(0),
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700884 last_no_thread_suspension_cause_(NULL),
885 thread_exit_check_count_(0) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700886 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Ian Rogers30e173f2012-09-26 14:35:03 -0700887 state_and_flags_.as_struct.flags = 0;
888 state_and_flags_.as_struct.state = kNative;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800889 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700890}
891
Elliott Hughes7dc51662012-05-16 14:48:43 -0700892bool Thread::IsStillStarting() const {
893 // You might think you can check whether the state is kStarting, but for much of thread startup,
894 // the thread might also be in kVmWait.
895 // You might think you can check whether the peer is NULL, but the peer is actually created and
896 // assigned fairly early on, and needs to be.
897 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
898 // this thread _ever_ entered kRunnable".
899 return (*name_ == kThreadNameDuringStartup);
900}
901
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700902void Thread::AssertNoPendingException() const {
903 if (UNLIKELY(IsExceptionPending())) {
904 ScopedObjectAccess soa(Thread::Current());
905 Throwable* exception = GetException();
906 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
907 }
908}
909
910static void MonitorExitVisitor(const Object* object, void* arg) NO_THREAD_SAFETY_ANALYSIS {
911 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700912 Object* entered_monitor = const_cast<Object*>(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700913 if (self->HoldsLock(entered_monitor)) {
914 LOG(WARNING) << "Calling MonitorExit on object "
915 << object << " (" << PrettyTypeOf(object) << ")"
916 << " left locked by native thread "
917 << *Thread::Current() << " which is detaching";
918 entered_monitor->MonitorExit(self);
919 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700920}
921
Elliott Hughesc0f09332012-03-26 13:27:06 -0700922void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700923 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700924 if (jni_env_ != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700925 jni_env_->monitors.VisitRoots(MonitorExitVisitor, Thread::Current());
Elliott Hughes93e74e82011-09-13 11:07:03 -0700926 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700927
Elliott Hughes93e74e82011-09-13 11:07:03 -0700928 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700929 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700930
Elliott Hughes534da072012-03-27 15:17:42 -0700931 // We may need to call user-supplied managed code.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700932 ScopedObjectAccess soa(this);
Elliott Hughes534da072012-03-27 15:17:42 -0700933
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700934 HandleUncaughtExceptions(soa);
935 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -0700936
Elliott Hughes29f27422011-09-18 16:02:18 -0700937 // this.vmData = 0;
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700938 SetVmData(soa, soa.Decode<Object*>(peer_), NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700939
Elliott Hughesc0f09332012-03-26 13:27:06 -0700940 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700941
Elliott Hughes29f27422011-09-18 16:02:18 -0700942 // Thread.join() is implemented as an Object.wait() on the Thread.lock
943 // object. Signal anyone who is waiting.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700944 Object* lock = soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->
945 GetObject(soa.Decode<Object*>(peer_));
Elliott Hughes038a8062011-09-18 14:12:41 -0700946 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700947 if (lock != NULL) {
948 lock->MonitorEnter(self);
949 lock->NotifyAll();
950 lock->MonitorExit(self);
951 }
952 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700953}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700954
Elliott Hughesc0f09332012-03-26 13:27:06 -0700955Thread::~Thread() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700956 if (jni_env_ != NULL && peer_ != NULL) {
957 // If pthread_create fails we don't have a jni env here.
958 jni_env_->DeleteGlobalRef(peer_);
959 }
960 peer_ = NULL;
961
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700962 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700963 jni_env_ = NULL;
964
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700965 CHECK_NE(GetState(), kRunnable);
966 // We may be deleting a still born thread.
967 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700968
969 delete wait_cond_;
970 delete wait_mutex_;
971
Ian Rogers776ac1f2012-04-13 23:36:36 -0700972#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -0700973 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -0700974#endif
Elliott Hughes475fc232011-10-25 15:00:35 -0700975
976 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800977 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800978 delete name_;
Elliott Hughesd8af1592012-04-16 20:40:15 -0700979
980 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700981}
982
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700983void Thread::HandleUncaughtExceptions(const ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700984 if (!IsExceptionPending()) {
985 return;
986 }
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700987 // Get and clear the exception.
988 Object* exception = GetException();
989 ClearException();
990
991 // If the thread has its own handler, use that.
Ian Rogers365c1022012-06-22 15:05:28 -0700992 Object* handler =
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700993 soa.DecodeField(WellKnownClasses::java_lang_Thread_uncaughtHandler)->
994 GetObject(soa.Decode<Object*>(peer_));
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700995 if (handler == NULL) {
996 // Otherwise use the thread group's default handler.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700997 handler = GetThreadGroup(soa);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700998 }
999
1000 // Call the handler.
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001001 jmethodID mid = WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001002 AbstractMethod* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Elliott Hughes77405792012-03-15 15:22:12 -07001003 JValue args[2];
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001004 args[0].SetL(soa.Decode<Object*>(peer_));
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001005 args[1].SetL(exception);
Elliott Hughes77405792012-03-15 15:22:12 -07001006 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001007
1008 // If the handler threw, clear that exception too.
1009 ClearException();
1010}
1011
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001012Object* Thread::GetThreadGroup(const ScopedObjectAccessUnchecked& soa) const {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001013 return soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
1014 GetObject(soa.Decode<Object*>(peer_));
Elliott Hughesa2155262011-11-16 16:26:58 -08001015}
1016
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001017void Thread::RemoveFromThreadGroup(const ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001018 // this.group.removeThread(this);
1019 // group can be null if we're in the compiler or a test.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001020 Object* group = GetThreadGroup(soa);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001021 if (group != NULL) {
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001022 jmethodID mid = WellKnownClasses::java_lang_ThreadGroup_removeThread;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001023 AbstractMethod* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Elliott Hughes77405792012-03-15 15:22:12 -07001024 JValue args[1];
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001025 args[0].SetL(soa.Decode<Object*>(peer_));
Elliott Hughes77405792012-03-15 15:22:12 -07001026 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001027 }
1028}
1029
Ian Rogers408f79a2011-08-23 18:22:33 -07001030size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001031 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001032 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001033 count += cur->NumberOfReferences();
1034 }
1035 return count;
1036}
1037
Ian Rogers408f79a2011-08-23 18:22:33 -07001038bool Thread::SirtContains(jobject obj) {
1039 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001040 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1041 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001042 return true;
1043 }
1044 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001045 // JNI code invoked from portable code uses shadow frames rather than the SIRT.
1046 return managed_stack_.ShadowFramesContain(sirt_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001047}
1048
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001049void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001050 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001051 size_t num_refs = cur->NumberOfReferences();
1052 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001053 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001054 if (object != NULL) {
1055 visitor(object, arg);
1056 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001057 }
1058 }
1059}
1060
Ian Rogers408f79a2011-08-23 18:22:33 -07001061Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001062 Locks::mutator_lock_->AssertSharedHeld();
Ian Rogers408f79a2011-08-23 18:22:33 -07001063 if (obj == NULL) {
1064 return NULL;
1065 }
1066 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1067 IndirectRefKind kind = GetIndirectRefKind(ref);
1068 Object* result;
1069 switch (kind) {
1070 case kLocal:
1071 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001072 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001073 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001074 break;
1075 }
1076 case kGlobal:
1077 {
1078 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1079 IndirectReferenceTable& globals = vm->globals;
1080 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001081 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001082 break;
1083 }
1084 case kWeakGlobal:
1085 {
1086 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1087 IndirectReferenceTable& weak_globals = vm->weak_globals;
1088 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001089 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001090 if (result == kClearedJniWeakGlobal) {
1091 // This is a special case where it's okay to return NULL.
1092 return NULL;
1093 }
1094 break;
1095 }
1096 case kSirtOrInvalid:
1097 default:
1098 // TODO: make stack indirect reference table lookup more efficient
1099 // Check if this is a local reference in the SIRT
Ian Rogers0399dde2012-06-06 17:09:28 -07001100 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001102 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001103 // Assume an invalid local reference is actually a direct pointer.
1104 result = reinterpret_cast<Object*>(obj);
1105 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001106 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001107 }
1108 }
1109
1110 if (result == NULL) {
Elliott Hughes3f6635a2012-06-19 13:37:49 -07001111 JniAbortF(NULL, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
Elliott Hughesa2501992011-08-26 19:39:54 -07001112 } else {
1113 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001114 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001115 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001116 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001117 return result;
1118}
1119
Ian Rogers0399dde2012-06-06 17:09:28 -07001120class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001121 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001122 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001123 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001124 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001125 : StackVisitor(stack, trace_stack, NULL),
1126 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001127
Ian Rogersb726dcb2012-09-05 08:57:23 -07001128 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001129 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001130 // Note we also skip the frame if it doesn't have a method (namely the callee
1131 // save frame)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001132 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001133 if (skipping_ && !m->IsRuntimeMethod() &&
1134 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001135 skipping_ = false;
1136 }
1137 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001138 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001139 ++depth_;
1140 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001141 } else {
1142 ++skip_depth_;
1143 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001144 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001145 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001146
1147 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001148 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001149 }
1150
Elliott Hughes29f27422011-09-18 16:02:18 -07001151 int GetSkipDepth() const {
1152 return skip_depth_;
1153 }
1154
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001155 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001156 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001157 uint32_t skip_depth_;
1158 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001159};
1160
Ian Rogers0399dde2012-06-06 17:09:28 -07001161class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001162 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001163 explicit BuildInternalStackTraceVisitor(const ManagedStack* stack,
1164 const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001165 int skip_depth)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001166 : StackVisitor(stack, trace_stack, NULL),
1167 skip_depth_(skip_depth), count_(0), dex_pc_trace_(NULL), method_trace_(NULL) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001168
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001169 bool Init(int depth, const ScopedObjectAccess& soa)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001170 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001171 // Allocate method trace with an extra slot that will hold the PC trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001172 SirtRef<ObjectArray<Object> >
1173 method_trace(Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1));
1174 if (method_trace.get() == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001175 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001176 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001177 IntArray* dex_pc_trace = IntArray::Alloc(depth);
1178 if (dex_pc_trace == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001179 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001180 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001181 // Save PC trace in last element of method trace, also places it into the
1182 // object graph.
Ian Rogers0399dde2012-06-06 17:09:28 -07001183 method_trace->Set(depth, dex_pc_trace);
1184 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001185 const char* last_no_suspend_cause =
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001186 soa.Self()->StartAssertNoThreadSuspension("Building internal stack trace");
Ian Rogers52673ff2012-06-27 23:25:34 -07001187 CHECK(last_no_suspend_cause == NULL) << last_no_suspend_cause;
Ian Rogers0399dde2012-06-06 17:09:28 -07001188 method_trace_ = method_trace.get();
1189 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001190 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001191 }
1192
Ian Rogers0399dde2012-06-06 17:09:28 -07001193 virtual ~BuildInternalStackTraceVisitor() {
Ian Rogers52673ff2012-06-27 23:25:34 -07001194 if (method_trace_ != NULL) {
1195 Thread::Current()->EndAssertNoThreadSuspension(NULL);
1196 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001197 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001198
Ian Rogersb726dcb2012-09-05 08:57:23 -07001199 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001200 if (method_trace_ == NULL || dex_pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001201 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001202 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001203 if (skip_depth_ > 0) {
1204 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001205 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001206 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001207 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001208 if (m->IsRuntimeMethod()) {
1209 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001210 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001211 method_trace_->Set(count_, m);
1212 dex_pc_trace_->Set(count_, GetDexPc());
Ian Rogersaaa20802011-09-11 21:47:37 -07001213 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001214 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001215 }
1216
Ian Rogers0399dde2012-06-06 17:09:28 -07001217 ObjectArray<Object>* GetInternalStackTrace() const {
1218 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001219 }
1220
1221 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001222 // How many more frames to skip.
1223 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001224 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001225 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001226 // Array of dex PC values.
1227 IntArray* dex_pc_trace_;
1228 // 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 -07001229 ObjectArray<Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001230};
1231
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001232void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1233 sirt->SetLink(top_sirt_);
1234 top_sirt_ = sirt;
1235}
1236
1237StackIndirectReferenceTable* Thread::PopSirt() {
1238 CHECK(top_sirt_ != NULL);
1239 StackIndirectReferenceTable* sirt = top_sirt_;
1240 top_sirt_ = top_sirt_->GetLink();
1241 return sirt;
1242}
1243
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001244jobject Thread::CreateInternalStackTrace(const ScopedObjectAccess& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001245 // Compute depth of stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001246 CountStackDepthVisitor count_visitor(GetManagedStack(), GetTraceStack());
1247 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001248 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001249 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001250
Ian Rogersaaa20802011-09-11 21:47:37 -07001251 // Build internal stack trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001252 BuildInternalStackTraceVisitor build_trace_visitor(GetManagedStack(), GetTraceStack(),
1253 skip_depth);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001254 if (!build_trace_visitor.Init(depth, soa)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001255 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001256 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001257 build_trace_visitor.WalkStack();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001258 return soa.AddLocalReference<jobjectArray>(build_trace_visitor.GetInternalStackTrace());
Ian Rogersaaa20802011-09-11 21:47:37 -07001259}
1260
Elliott Hughes01158d72011-09-19 19:47:10 -07001261jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1262 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001263 // Transition into runnable state to work on Object*/Array*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001264 ScopedObjectAccess soa(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001265 // Decode the internal stack trace into the depth, method trace and PC trace
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001266 ObjectArray<Object>* method_trace = soa.Decode<ObjectArray<Object>*>(internal);
Ian Rogers9074b992011-10-26 17:41:55 -07001267 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001268 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1269
1270 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1271
Elliott Hughes01158d72011-09-19 19:47:10 -07001272 jobjectArray result;
1273 ObjectArray<StackTraceElement>* java_traces;
1274 if (output_array != NULL) {
1275 // Reuse the array we were given.
1276 result = output_array;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001277 java_traces = soa.Decode<ObjectArray<StackTraceElement>*>(output_array);
Elliott Hughes01158d72011-09-19 19:47:10 -07001278 // ...adjusting the number of frames we'll write to not exceed the array length.
1279 depth = std::min(depth, java_traces->GetLength());
1280 } else {
1281 // Create java_trace array and place in local reference table
1282 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001283 if (java_traces == NULL) {
1284 return NULL;
1285 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001286 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001287 }
1288
1289 if (stack_depth != NULL) {
1290 *stack_depth = depth;
1291 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001292
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001293 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001294 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001295 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001296 AbstractMethod* method = down_cast<AbstractMethod*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001297 mh.ChangeMethod(method);
Ian Rogers0399dde2012-06-06 17:09:28 -07001298 uint32_t dex_pc = pc_trace->Get(i);
1299 int32_t line_number = mh.GetLineNumFromDexPC(dex_pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001300 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001301 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001302 const char* descriptor = mh.GetDeclaringClassDescriptor();
1303 CHECK(descriptor != NULL);
1304 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001305 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1306 if (class_name_object.get() == NULL) {
1307 return NULL;
1308 }
Ian Rogers48601312011-12-07 16:45:19 -08001309 const char* method_name = mh.GetName();
1310 CHECK(method_name != NULL);
1311 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001312 if (method_name_object.get() == NULL) {
1313 return NULL;
1314 }
Ian Rogers48601312011-12-07 16:45:19 -08001315 const char* source_file = mh.GetDeclaringClassSourceFile();
1316 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001317 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001318 method_name_object.get(),
1319 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001320 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001321 if (obj == NULL) {
1322 return NULL;
1323 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001324#ifdef MOVING_GARBAGE_COLLECTOR
1325 // Re-read after potential GC
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001326 java_traces = Decode<ObjectArray<Object>*>(soa.Env(), result);
1327 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(soa.Env(), internal));
Ian Rogersaaa20802011-09-11 21:47:37 -07001328 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1329#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001330 java_traces->Set(i, obj);
1331 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001332 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001333}
1334
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001335void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001336 va_list args;
1337 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001338 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001339 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001340}
1341
1342void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1343 std::string msg;
1344 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001345 ThrowNewException(exception_class_descriptor, msg.c_str());
1346}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001347
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001348void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001349 AssertNoPendingException(); // Callers should either clear or call ThrowNewWrappedException.
Elliott Hughesa4f94742012-05-29 16:28:38 -07001350 ThrowNewWrappedException(exception_class_descriptor, msg);
1351}
1352
1353void Thread::ThrowNewWrappedException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001354 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001355 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001356 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001357 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001358 descriptor.erase(descriptor.length() - 1);
1359
1360 JNIEnv* env = GetJniEnv();
Elliott Hughesa4f94742012-05-29 16:28:38 -07001361 jobject cause = env->ExceptionOccurred();
1362 env->ExceptionClear();
1363
Elliott Hughes726079d2011-10-07 18:43:44 -07001364 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001365 if (exception_class.get() == NULL) {
1366 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1367 << PrettyTypeOf(GetException());
1368 CHECK(IsExceptionPending());
1369 return;
1370 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001371 if (!Runtime::Current()->IsStarted()) {
1372 // Something is trying to throw an exception without a started
1373 // runtime, which is the common case in the compiler. We won't be
1374 // able to invoke the constructor of the exception, so use
1375 // AllocObject which will not invoke a constructor.
1376 ScopedLocalRef<jthrowable> exception(
1377 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1378 if (exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001379 ScopedObjectAccessUnchecked soa(env);
1380 Throwable* t = reinterpret_cast<Throwable*>(soa.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001381 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001382 soa.Self()->SetException(t);
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001383 } else {
1384 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1385 << PrettyTypeOf(GetException());
1386 CHECK(IsExceptionPending());
1387 }
1388 return;
1389 }
Elliott Hughesa4f94742012-05-29 16:28:38 -07001390 int rc = ::art::ThrowNewException(env, exception_class.get(), msg, cause);
Elliott Hughes30646832011-10-13 16:59:46 -07001391 if (rc != JNI_OK) {
1392 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1393 << PrettyTypeOf(GetException());
1394 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001395 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001396}
1397
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001398void Thread::ThrowOutOfMemoryError(const char* msg) {
1399 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1400 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001401 if (!throwing_OutOfMemoryError_) {
1402 throwing_OutOfMemoryError_ = true;
Elliott Hughes57aba862012-06-20 14:00:47 -07001403 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001404 } else {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001405 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
1406 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001407 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001408 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001409}
1410
Elliott Hughes498508c2011-10-17 14:58:22 -07001411Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001412 return Thread::Current();
1413}
1414
1415void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001416 std::ostringstream ss;
1417 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001418 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001419 // log to stderr for debugging command line processes
1420 std::cerr << str;
1421#ifdef HAVE_ANDROID_OS
1422 // log to logcat for debugging frameworks processes
1423 LOG(INFO) << str;
1424#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001425}
1426
Elliott Hughes98e20172012-04-24 15:38:13 -07001427struct EntryPointInfo {
1428 uint32_t offset;
1429 const char* name;
1430};
1431#define ENTRY_POINT_INFO(x) { ENTRYPOINT_OFFSET(x), #x }
1432static const EntryPointInfo gThreadEntryPointInfo[] = {
1433 ENTRY_POINT_INFO(pAllocArrayFromCode),
1434 ENTRY_POINT_INFO(pAllocArrayFromCodeWithAccessCheck),
1435 ENTRY_POINT_INFO(pAllocObjectFromCode),
1436 ENTRY_POINT_INFO(pAllocObjectFromCodeWithAccessCheck),
1437 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCode),
1438 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCodeWithAccessCheck),
1439 ENTRY_POINT_INFO(pInstanceofNonTrivialFromCode),
1440 ENTRY_POINT_INFO(pCanPutArrayElementFromCode),
1441 ENTRY_POINT_INFO(pCheckCastFromCode),
1442 ENTRY_POINT_INFO(pDebugMe),
1443 ENTRY_POINT_INFO(pUpdateDebuggerFromCode),
1444 ENTRY_POINT_INFO(pInitializeStaticStorage),
1445 ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccessFromCode),
1446 ENTRY_POINT_INFO(pInitializeTypeFromCode),
1447 ENTRY_POINT_INFO(pResolveStringFromCode),
Ian Rogers474b6da2012-09-25 00:20:38 -07001448 ENTRY_POINT_INFO(pGetAndClearException),
Elliott Hughes98e20172012-04-24 15:38:13 -07001449 ENTRY_POINT_INFO(pSet32Instance),
1450 ENTRY_POINT_INFO(pSet32Static),
1451 ENTRY_POINT_INFO(pSet64Instance),
1452 ENTRY_POINT_INFO(pSet64Static),
1453 ENTRY_POINT_INFO(pSetObjInstance),
1454 ENTRY_POINT_INFO(pSetObjStatic),
1455 ENTRY_POINT_INFO(pGet32Instance),
1456 ENTRY_POINT_INFO(pGet32Static),
1457 ENTRY_POINT_INFO(pGet64Instance),
1458 ENTRY_POINT_INFO(pGet64Static),
1459 ENTRY_POINT_INFO(pGetObjInstance),
1460 ENTRY_POINT_INFO(pGetObjStatic),
1461 ENTRY_POINT_INFO(pHandleFillArrayDataFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001462 ENTRY_POINT_INFO(pFindNativeMethod),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001463 ENTRY_POINT_INFO(pJniMethodStart),
1464 ENTRY_POINT_INFO(pJniMethodStartSynchronized),
1465 ENTRY_POINT_INFO(pJniMethodEnd),
1466 ENTRY_POINT_INFO(pJniMethodEndSynchronized),
1467 ENTRY_POINT_INFO(pJniMethodEndWithReference),
1468 ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
Elliott Hughes98e20172012-04-24 15:38:13 -07001469 ENTRY_POINT_INFO(pLockObjectFromCode),
1470 ENTRY_POINT_INFO(pUnlockObjectFromCode),
1471 ENTRY_POINT_INFO(pCmpgDouble),
1472 ENTRY_POINT_INFO(pCmpgFloat),
1473 ENTRY_POINT_INFO(pCmplDouble),
1474 ENTRY_POINT_INFO(pCmplFloat),
1475 ENTRY_POINT_INFO(pDadd),
1476 ENTRY_POINT_INFO(pDdiv),
1477 ENTRY_POINT_INFO(pDmul),
1478 ENTRY_POINT_INFO(pDsub),
1479 ENTRY_POINT_INFO(pF2d),
1480 ENTRY_POINT_INFO(pFmod),
Ian Rogers0183dd72012-09-17 23:06:51 -07001481 ENTRY_POINT_INFO(pSqrt),
Elliott Hughes98e20172012-04-24 15:38:13 -07001482 ENTRY_POINT_INFO(pI2d),
1483 ENTRY_POINT_INFO(pL2d),
1484 ENTRY_POINT_INFO(pD2f),
1485 ENTRY_POINT_INFO(pFadd),
1486 ENTRY_POINT_INFO(pFdiv),
1487 ENTRY_POINT_INFO(pFmodf),
1488 ENTRY_POINT_INFO(pFmul),
1489 ENTRY_POINT_INFO(pFsub),
1490 ENTRY_POINT_INFO(pI2f),
1491 ENTRY_POINT_INFO(pL2f),
1492 ENTRY_POINT_INFO(pD2iz),
1493 ENTRY_POINT_INFO(pF2iz),
1494 ENTRY_POINT_INFO(pIdivmod),
1495 ENTRY_POINT_INFO(pD2l),
1496 ENTRY_POINT_INFO(pF2l),
1497 ENTRY_POINT_INFO(pLdiv),
1498 ENTRY_POINT_INFO(pLdivmod),
1499 ENTRY_POINT_INFO(pLmul),
1500 ENTRY_POINT_INFO(pShlLong),
1501 ENTRY_POINT_INFO(pShrLong),
1502 ENTRY_POINT_INFO(pUshrLong),
1503 ENTRY_POINT_INFO(pIndexOf),
1504 ENTRY_POINT_INFO(pMemcmp16),
1505 ENTRY_POINT_INFO(pStringCompareTo),
1506 ENTRY_POINT_INFO(pMemcpy),
1507 ENTRY_POINT_INFO(pUnresolvedDirectMethodTrampolineFromCode),
1508 ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
1509 ENTRY_POINT_INFO(pInvokeInterfaceTrampoline),
1510 ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
1511 ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
1512 ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
1513 ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
1514 ENTRY_POINT_INFO(pCheckSuspendFromCode),
1515 ENTRY_POINT_INFO(pTestSuspendFromCode),
1516 ENTRY_POINT_INFO(pDeliverException),
1517 ENTRY_POINT_INFO(pThrowAbstractMethodErrorFromCode),
1518 ENTRY_POINT_INFO(pThrowArrayBoundsFromCode),
1519 ENTRY_POINT_INFO(pThrowDivZeroFromCode),
1520 ENTRY_POINT_INFO(pThrowNoSuchMethodFromCode),
1521 ENTRY_POINT_INFO(pThrowNullPointerFromCode),
1522 ENTRY_POINT_INFO(pThrowStackOverflowFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001523};
1524#undef ENTRY_POINT_INFO
1525
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001526void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1527 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes98e20172012-04-24 15:38:13 -07001528
1529#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 -07001530 DO_THREAD_OFFSET(state_and_flags_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001531 DO_THREAD_OFFSET(card_table_);
1532 DO_THREAD_OFFSET(exception_);
1533 DO_THREAD_OFFSET(jni_env_);
1534 DO_THREAD_OFFSET(self_);
1535 DO_THREAD_OFFSET(stack_end_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001536 DO_THREAD_OFFSET(suspend_count_);
1537 DO_THREAD_OFFSET(thin_lock_id_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001538 //DO_THREAD_OFFSET(top_of_managed_stack_);
1539 //DO_THREAD_OFFSET(top_of_managed_stack_pc_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001540 DO_THREAD_OFFSET(top_sirt_);
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001541#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001542
1543 size_t entry_point_count = arraysize(gThreadEntryPointInfo);
1544 CHECK_EQ(entry_point_count * size_of_pointers, sizeof(EntryPoints));
1545 uint32_t expected_offset = OFFSETOF_MEMBER(Thread, entrypoints_);
1546 for (size_t i = 0; i < entry_point_count; ++i) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001547 CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset) << gThreadEntryPointInfo[i].name;
Elliott Hughes98e20172012-04-24 15:38:13 -07001548 expected_offset += size_of_pointers;
1549 if (gThreadEntryPointInfo[i].offset == offset) {
1550 os << gThreadEntryPointInfo[i].name;
1551 return;
1552 }
1553 }
1554 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001555}
1556
Ian Rogers0399dde2012-06-06 17:09:28 -07001557static const bool kDebugExceptionDelivery = false;
1558class CatchBlockStackVisitor : public StackVisitor {
Ian Rogersbdb03912011-09-14 00:55:44 -07001559 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001560 CatchBlockStackVisitor(Thread* self, Throwable* exception)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001561 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers0399dde2012-06-06 17:09:28 -07001562 : StackVisitor(self->GetManagedStack(), self->GetTraceStack(), self->GetLongJumpContext()),
1563 self_(self), exception_(exception), to_find_(exception->GetClass()), throw_method_(NULL),
1564 throw_frame_id_(0), throw_dex_pc_(0), handler_quick_frame_(NULL),
1565 handler_quick_frame_pc_(0), handler_dex_pc_(0), native_method_count_(0),
Ian Rogers57b86d42012-03-27 16:05:41 -07001566 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers52673ff2012-06-27 23:25:34 -07001567 // Exception not in root sets, can't allow GC.
1568 last_no_assert_suspension_cause_ = self->StartAssertNoThreadSuspension("Finding catch block");
1569 }
1570
1571 ~CatchBlockStackVisitor() {
1572 LOG(FATAL) << "UNREACHABLE"; // Expected to take long jump.
Ian Rogers67375ac2011-09-14 00:55:44 -07001573 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001574
Ian Rogersb726dcb2012-09-05 08:57:23 -07001575 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1576 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001577 AbstractMethod* method = GetMethod();
Elliott Hughes530fa002012-03-12 11:44:49 -07001578 if (method == NULL) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001579 // This is the upcall, we remember the frame and last pc so that we may long jump to them.
1580 handler_quick_frame_pc_ = GetCurrentQuickFramePc();
1581 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001582 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001583 }
1584 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001585 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001586 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001587 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001588 } else {
Ian Rogers0399dde2012-06-06 17:09:28 -07001589 if (throw_method_ == NULL) {
1590 throw_method_ = method;
1591 throw_frame_id_ = GetFrameId();
1592 throw_dex_pc_ = GetDexPc();
Ian Rogers67375ac2011-09-14 00:55:44 -07001593 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001594 if (method->IsNative()) {
1595 native_method_count_++;
1596 } else {
1597 // Unwind stack when an exception occurs during method tracing
1598 if (UNLIKELY(method_tracing_active_ && IsTraceExitPc(GetCurrentQuickFramePc()))) {
buzbee8320f382012-09-11 16:29:42 -07001599 uintptr_t pc = TraceMethodUnwindFromCode(Thread::Current());
Ian Rogers0c7abda2012-09-19 13:33:42 -07001600 dex_pc = method->ToDexPc(pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001601 } else {
1602 dex_pc = GetDexPc();
1603 }
1604 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001605 }
1606 if (dex_pc != DexFile::kDexNoIndex) {
1607 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1608 if (found_dex_pc != DexFile::kDexNoIndex) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001609 handler_dex_pc_ = found_dex_pc;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001610 handler_quick_frame_pc_ = method->ToNativePc(found_dex_pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001611 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001612 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001613 }
1614 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001615 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001616 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001617
Ian Rogersb726dcb2012-09-05 08:57:23 -07001618 void DoLongJump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001619 AbstractMethod* catch_method = *handler_quick_frame_;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001620 Dbg::PostException(self_, throw_frame_id_, throw_method_, throw_dex_pc_,
Ian Rogers0399dde2012-06-06 17:09:28 -07001621 catch_method, handler_dex_pc_, exception_);
1622 if (kDebugExceptionDelivery) {
1623 if (catch_method == NULL) {
1624 LOG(INFO) << "Handler is upcall";
1625 } else {
1626 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1627 const DexFile& dex_file =
1628 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1629 int line_number = dex_file.GetLineNumFromPC(catch_method, handler_dex_pc_);
1630 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
1631 }
1632 }
Ian Rogers52673ff2012-06-27 23:25:34 -07001633 self_->SetException(exception_); // Exception back in root set.
1634 self_->EndAssertNoThreadSuspension(last_no_assert_suspension_cause_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001635 // Place context back on thread so it will be available when we continue.
1636 self_->ReleaseLongJumpContext(context_);
1637 context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
1638 CHECK_NE(handler_quick_frame_pc_, 0u);
1639 context_->SetPC(handler_quick_frame_pc_);
1640 context_->SmashCallerSaves();
1641 context_->DoLongJump();
1642 }
1643
1644 private:
1645 Thread* self_;
1646 Throwable* exception_;
1647 // The type of the exception catch block to find.
Ian Rogersbdb03912011-09-14 00:55:44 -07001648 Class* to_find_;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001649 AbstractMethod* throw_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001650 JDWP::FrameId throw_frame_id_;
1651 uint32_t throw_dex_pc_;
1652 // Quick frame with found handler or last frame if no handler found.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001653 AbstractMethod** handler_quick_frame_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001654 // PC to branch to for the handler.
1655 uintptr_t handler_quick_frame_pc_;
1656 // Associated dex PC.
1657 uint32_t handler_dex_pc_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001658 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1659 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001660 // Is method tracing active?
1661 const bool method_tracing_active_;
Ian Rogers52673ff2012-06-27 23:25:34 -07001662 // Support for nesting no thread suspension checks.
1663 const char* last_no_assert_suspension_cause_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001664};
1665
Ian Rogersff1ed472011-09-20 13:46:24 -07001666void Thread::DeliverException() {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001667 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001668 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001669 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001670 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001671 ClearException();
1672 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001673 String* msg = exception->GetDetailMessage();
1674 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1675 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
Elliott Hughesc073b072012-05-24 19:29:17 -07001676 << ": " << str_msg << "\n");
Ian Rogers28ad40d2011-10-27 15:19:26 -07001677 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001678 CatchBlockStackVisitor catch_finder(this, exception);
1679 catch_finder.WalkStack(true);
1680 catch_finder.DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001681 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001682}
1683
Ian Rogersbdb03912011-09-14 00:55:44 -07001684Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001685 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001686 if (result == NULL) {
1687 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07001688 } else {
1689 long_jump_context_ = NULL; // Avoid context being shared.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001690 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001691 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001692}
1693
Mathieu Chartier66f19252012-09-18 08:57:04 -07001694AbstractMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, size_t* frame_id) const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001695 struct CurrentMethodVisitor : public StackVisitor {
1696 CurrentMethodVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001697 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001698 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001699 : StackVisitor(stack, trace_stack, NULL), method_(NULL), dex_pc_(0), frame_id_(0) {}
Elliott Hughes8be2d402012-02-23 14:22:41 -08001700
Ian Rogersb726dcb2012-09-05 08:57:23 -07001701 virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001702 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001703 if (m->IsRuntimeMethod()) {
1704 // Continue if this is a runtime method.
1705 return true;
1706 }
1707 method_ = m;
1708 dex_pc_ = GetDexPc();
1709 frame_id_ = GetFrameId();
1710 return false;
1711 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001712 AbstractMethod* method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001713 uint32_t dex_pc_;
1714 size_t frame_id_;
1715 };
1716
1717 CurrentMethodVisitor visitor(GetManagedStack(), GetTraceStack());
1718 visitor.WalkStack(false);
1719 if (dex_pc != NULL) {
1720 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001721 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001722 if (frame_id != NULL) {
1723 *frame_id = visitor.frame_id_;
jeffhao33dc7712011-11-09 17:54:24 -08001724 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001725 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08001726}
1727
Elliott Hughes5f791332011-09-15 17:45:30 -07001728bool Thread::HoldsLock(Object* object) {
1729 if (object == NULL) {
1730 return false;
1731 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001732 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001733}
1734
Ian Rogers0399dde2012-06-06 17:09:28 -07001735class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001736 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001737 ReferenceMapVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001738 Context* context, Heap::RootVisitor* root_visitor, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001739 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersca190662012-06-26 15:45:57 -07001740 : StackVisitor(stack, trace_stack, context), root_visitor_(root_visitor), arg_(arg) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07001741
Ian Rogersb726dcb2012-09-05 08:57:23 -07001742 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001743 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001744 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
1745 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001746 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001747 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
1748 if (shadow_frame != NULL) {
1749 shadow_frame->VisitRoots(root_visitor_, arg_);
1750 } else {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001751 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001752 // Process register map (which native and runtime methods don't have)
Ian Rogers640495b2012-06-22 15:15:47 -07001753 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001754 const uint8_t* native_gc_map = m->GetNativeGcMap();
1755 CHECK(native_gc_map != NULL) << PrettyMethod(m);
1756 mh_.ChangeMethod(m);
1757 const DexFile::CodeItem* code_item = mh_.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001758 DCHECK(code_item != NULL) << PrettyMethod(m); // Can't be NULL or how would we compile its instructions?
Ian Rogers0c7abda2012-09-19 13:33:42 -07001759 NativePcOffsetToReferenceMap map(native_gc_map);
Ian Rogers0399dde2012-06-06 17:09:28 -07001760 size_t num_regs = std::min(map.RegWidth() * 8,
1761 static_cast<size_t>(code_item->registers_size_));
Ian Rogers0c7abda2012-09-19 13:33:42 -07001762 if (num_regs > 0) {
1763 const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
1764 DCHECK(reg_bitmap != NULL);
1765 const VmapTable vmap_table(m->GetVmapTableRaw());
1766 uint32_t core_spills = m->GetCoreSpillMask();
1767 uint32_t fp_spills = m->GetFpSpillMask();
1768 size_t frame_size = m->GetFrameSizeInBytes();
1769 // For all dex registers in the bitmap
Mathieu Chartier66f19252012-09-18 08:57:04 -07001770 AbstractMethod** cur_quick_frame = GetCurrentQuickFrame();
Ian Rogers0c7abda2012-09-19 13:33:42 -07001771 DCHECK(cur_quick_frame != NULL);
1772 for (size_t reg = 0; reg < num_regs; ++reg) {
1773 // Does this register hold a reference?
1774 if (TestBitmap(reg, reg_bitmap)) {
1775 uint32_t vmap_offset;
1776 Object* ref;
1777 if (vmap_table.IsInContext(reg, vmap_offset)) {
1778 // Compute the register we need to load from the context
1779 uint32_t spill_mask = core_spills;
1780 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1781 uint32_t matches = 0;
1782 uint32_t spill_shifts = 0;
1783 while (matches != (vmap_offset + 1)) {
1784 DCHECK_NE(spill_mask, 0u);
1785 matches += spill_mask & 1; // Add 1 if the low bit is set
1786 spill_mask >>= 1;
1787 spill_shifts++;
1788 }
1789 spill_shifts--; // wind back one as we want the last match
1790 ref = reinterpret_cast<Object*>(GetGPR(spill_shifts));
1791 } else {
1792 ref = reinterpret_cast<Object*>(GetVReg(cur_quick_frame, code_item, core_spills,
1793 fp_spills, frame_size, reg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001794 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07001795 if (ref != NULL) {
1796 root_visitor_(ref, arg_);
1797 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001798 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001799 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001800 }
1801 }
1802 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001803 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001804 }
1805
1806 private:
1807 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1808 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1809 }
1810
Ian Rogers0c7abda2012-09-19 13:33:42 -07001811 // Call-back when we visit a root.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001812 Heap::RootVisitor* root_visitor_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001813 // Argument to call-back.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001814 void* arg_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001815 // A method helper we keep around to avoid dex file/cache re-computations.
1816 MethodHelper mh_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001817};
1818
1819void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001820 if (exception_ != NULL) {
1821 visitor(exception_, arg);
1822 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001823 if (class_loader_override_ != NULL) {
1824 visitor(class_loader_override_, arg);
1825 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001826 jni_env_->locals.VisitRoots(visitor, arg);
1827 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001828
1829 SirtVisitRoots(visitor, arg);
1830
Ian Rogersd6b1f612011-09-27 13:38:14 -07001831 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001832 Context* context = GetLongJumpContext();
1833 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context, visitor, arg);
1834 mapper.WalkStack();
1835 ReleaseLongJumpContext(context);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001836}
1837
jeffhao25045522012-03-13 19:34:37 -07001838#if VERIFY_OBJECT_ENABLED
Ian Rogers0399dde2012-06-06 17:09:28 -07001839static void VerifyObject(const Object* obj, void* arg) {
1840 Heap* heap = reinterpret_cast<Heap*>(arg);
1841 heap->VerifyObject(obj);
jeffhao25045522012-03-13 19:34:37 -07001842}
1843
1844void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07001845 UniquePtr<Context> context(Context::Create());
Ian Rogers67054b52012-06-26 16:02:10 -07001846 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context.get(), VerifyObject,
Ian Rogers0399dde2012-06-06 17:09:28 -07001847 Runtime::Current()->GetHeap());
1848 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07001849}
1850#endif
1851
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001852// Set the stack end to that to be used during a stack overflow
1853void Thread::SetStackEndForStackOverflow() {
1854 // During stack overflow we allow use of the full stack
1855 if (stack_end_ == stack_begin_) {
1856 DumpStack(std::cerr);
1857 LOG(FATAL) << "Need to increase kStackOverflowReservedBytes (currently "
1858 << kStackOverflowReservedBytes << ")";
1859 }
1860
1861 stack_end_ = stack_begin_;
1862}
1863
Elliott Hughes330304d2011-08-12 14:28:05 -07001864std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001865 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07001866 return os;
1867}
1868
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001869#ifndef NDEBUG
1870void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
1871 CHECK_EQ(0u, no_thread_suspension_) << last_no_thread_suspension_cause_;
1872 if (check_locks) {
1873 bool bad_mutexes_held = false;
1874 for (int i = kMaxMutexLevel; i >= 0; --i) {
1875 // We expect no locks except the mutator_lock_.
1876 if (i != kMutatorLock) {
1877 BaseMutex* held_mutex = GetHeldMutex(static_cast<MutexLevel>(i));
1878 if (held_mutex != NULL) {
1879 LOG(ERROR) << "holding \"" << held_mutex->GetName()
1880 << "\" at point where thread suspension is expected";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001881 bad_mutexes_held = true;
1882 }
1883 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001884 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001885 CHECK(!bad_mutexes_held);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001886 }
1887}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001888#endif
Elliott Hughesa4060e52012-03-02 16:51:35 -08001889
Elliott Hughes8daa0922011-09-11 13:46:25 -07001890} // namespace art