blob: 9db25f464c6a801efc05bbd5785f8fa585f14f55 [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"
Elliott Hughes46e251b2012-05-22 15:10:45 -070033#include "debugger.h"
Ian Rogers0c7abda2012-09-19 13:33:42 -070034#include "gc_map.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070035#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070036#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070037#include "monitor.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070038#include "oat/runtime/context.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070039#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050041#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070042#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070043#include "runtime_support.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070044#include "scoped_thread_state_change.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070045#include "ScopedLocalRef.h"
Ian Rogers30fab402012-01-23 15:43:46 -080046#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070047#include "stack.h"
48#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070049#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070050#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070051#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070052
53namespace art {
54
55pthread_key_t Thread::pthread_key_self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070056ConditionVariable* Thread::resume_cond_;
Carl Shapirob5573532011-07-12 18:22:59 -070057
Elliott Hughes7dc51662012-05-16 14:48:43 -070058static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
59
Ian Rogers5d76c432011-10-31 21:42:49 -070060void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080061 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070062}
63
Elliott Hughes99250ba2012-04-17 11:09:17 -070064#if !defined(__APPLE__)
Elliott Hughes3ea0f422012-04-16 17:01:43 -070065static void UnimplementedEntryPoint() {
66 UNIMPLEMENTED(FATAL);
67}
Elliott Hughes99250ba2012-04-17 11:09:17 -070068#endif
Elliott Hughes3ea0f422012-04-16 17:01:43 -070069
buzbee3ea4ec52011-08-22 17:37:19 -070070void Thread::InitFunctionPointers() {
Elliott Hughes99250ba2012-04-17 11:09:17 -070071#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
Elliott Hughes3ea0f422012-04-16 17:01:43 -070072 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
73 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
74 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
75 for (uintptr_t* it = begin; it != end; ++it) {
76 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
77 }
Elliott Hughes99250ba2012-04-17 11:09:17 -070078#endif
Ian Rogers57b86d42012-03-27 16:05:41 -070079 InitEntryPoints(&entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -070080}
81
82void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
83 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers776ac1f2012-04-13 23:36:36 -070084#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070085 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
Ian Rogers776ac1f2012-04-13 23:36:36 -070086#else
87 UNIMPLEMENTED(FATAL);
88#endif
buzbee3ea4ec52011-08-22 17:37:19 -070089}
90
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070091void Thread::InitTid() {
92 tid_ = ::art::GetTid();
93}
94
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070095void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -070096 // One thread (us) survived the fork, but we have a new tid so we need to
97 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070098 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070099}
100
Brian Carlstrom78128a62011-09-15 17:21:19 -0700101void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700102 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700103 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700104
Elliott Hughes47179f72011-10-27 16:44:39 -0700105 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700106 ScopedObjectAccess soa(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700107 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700108 SirtRef<String> thread_name(self->GetThreadName(soa));
Ian Rogers365c1022012-06-22 15:05:28 -0700109 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
110 }
111
112 Dbg::PostThreadStart(self);
113
114 // Invoke the 'run' method of our java.lang.Thread.
115 CHECK(self->peer_ != NULL);
116 Object* receiver = self->peer_;
117 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700118 AbstractMethod* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Ian Rogers365c1022012-06-22 15:05:28 -0700119 m->Invoke(self, receiver, NULL, NULL);
Elliott Hughes47179f72011-10-27 16:44:39 -0700120 }
121
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700122 // Detach and delete self.
123 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700124
Carl Shapirob5573532011-07-12 18:22:59 -0700125 return NULL;
126}
127
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700128static void SetVmData(const ScopedObjectAccess& soa, Object* managed_thread,
129 Thread* native_thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700131 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700132 f->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700133}
134
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700135Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, Object* thread_peer) {
136 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
137 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetInt(thread_peer)));
138 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
139 // to stop it from going away.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700140 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141 if (result != NULL && !result->IsSuspended()) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700142 Locks::thread_list_lock_->AssertHeld();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 }
144 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800145}
146
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700147Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
148 return FromManagedThread(soa, soa.Decode<Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700149}
150
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700151static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700152 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700153 if (stack_size == 0) {
154 stack_size = Runtime::Current()->GetDefaultStackSize();
155 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700156
Brian Carlstrom6414a972012-04-14 14:20:04 -0700157 // Dalvik used the bionic pthread default stack size for native threads,
158 // so include that here to support apps that expect large native stacks.
159 stack_size += 1 * MB;
160
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700161 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
162 if (stack_size < PTHREAD_STACK_MIN) {
163 stack_size = PTHREAD_STACK_MIN;
164 }
165
166 // It's likely that callers are trying to ensure they have at least a certain amount of
167 // stack space, so we should add our reserved space on top of what they requested, rather
168 // than implicitly take it away from them.
169 stack_size += Thread::kStackOverflowReservedBytes;
170
171 // Some systems require the stack size to be a multiple of the system page size, so round up.
172 stack_size = RoundUp(stack_size, kPageSize);
173
174 return stack_size;
175}
176
Elliott Hughesd8af1592012-04-16 20:40:15 -0700177static void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
178 if (sigaltstack(new_stack, old_stack) == -1) {
179 PLOG(FATAL) << "sigaltstack failed";
180 }
181}
182
183static void SetUpAlternateSignalStack() {
184 // Create and set an alternate signal stack.
185 stack_t ss;
186 ss.ss_sp = new uint8_t[SIGSTKSZ];
187 ss.ss_size = SIGSTKSZ;
188 ss.ss_flags = 0;
189 CHECK(ss.ss_sp != NULL);
190 SigAltStack(&ss, NULL);
191
192 // Double-check that it worked.
193 ss.ss_sp = NULL;
194 SigAltStack(NULL, &ss);
195 VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
196}
197
198static void TearDownAlternateSignalStack() {
199 // Get the pointer so we can free the memory.
200 stack_t ss;
201 SigAltStack(NULL, &ss);
202 uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
203
204 // Tell the kernel to stop using it.
205 ss.ss_sp = NULL;
206 ss.ss_flags = SS_DISABLE;
Elliott Hughes4c5231d2012-04-18 16:54:31 -0700207 ss.ss_size = SIGSTKSZ; // Avoid ENOMEM failure with Mac OS' buggy libc.
Elliott Hughesd8af1592012-04-16 20:40:15 -0700208 SigAltStack(&ss, NULL);
209
210 // Free it.
211 delete[] allocated_signal_stack;
212}
213
Ian Rogers52673ff2012-06-27 23:25:34 -0700214void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool daemon) {
215 Thread* native_thread = new Thread(daemon);
Elliott Hughes47179f72011-10-27 16:44:39 -0700216 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700217 ScopedObjectAccess soa(env);
218 Object* peer = soa.Decode<Object*>(java_peer);
Ian Rogers365c1022012-06-22 15:05:28 -0700219 CHECK(peer != NULL);
220 native_thread->peer_ = peer;
221
222 stack_size = FixStackSize(stack_size);
223
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 // Thread.start is synchronized, so we know that vmData is 0, and know that we're not racing to
225 // assign it.
226 SetVmData(soa, peer, native_thread);
Elliott Hughes47179f72011-10-27 16:44:39 -0700227 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700228
229 pthread_t new_pthread;
230 pthread_attr_t attr;
231 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
232 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
233 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
234 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, native_thread);
235 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
236
237 if (UNLIKELY(pthread_create_result != 0)) {
238 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700239 {
240 ScopedObjectAccess soa(env);
241 Object* peer = soa.Decode<Object*>(java_peer);
242 SetVmData(soa, peer, 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700243
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700244 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
245 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
246 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
247 }
248 delete native_thread;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700249 return;
250 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700251}
252
Elliott Hughes462c9442012-03-23 18:47:50 -0700253void Thread::Init() {
254 // This function does all the initialization that must be run by the native thread it applies to.
255 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
256 // we can handshake with the corresponding native thread when it's ready.) Check this native
257 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700258 CHECK(Thread::Current() == NULL);
259
Elliott Hughesd8af1592012-04-16 20:40:15 -0700260 SetUpAlternateSignalStack();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700261 InitCpu();
262 InitFunctionPointers();
Shih-wei Liao21d28f52012-06-12 05:55:00 -0700263#ifdef ART_USE_GREENLAND_COMPILER
264 InitRuntimeEntryPoints(&runtime_entry_points_);
265#endif
Ian Rogers5d76c432011-10-31 21:42:49 -0700266 InitCardTable();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700267
Elliott Hughes462c9442012-03-23 18:47:50 -0700268 Runtime* runtime = Runtime::Current();
269 CHECK(runtime != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700270 if (runtime->IsShuttingDown()) {
271 UNIMPLEMENTED(WARNING) << "Thread attaching whilst runtime is shutting down";
272 }
Elliott Hughes462c9442012-03-23 18:47:50 -0700273 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Elliott Hughes0d39c122012-06-06 16:41:17 -0700274 pthread_self_ = pthread_self();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700275
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700276 InitTid();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700277 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700278
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700279 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700280
Elliott Hughes93e74e82011-09-13 11:07:03 -0700281 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700282
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700283 runtime->GetThreadList()->Register(this);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700284}
285
Ian Rogers365c1022012-06-22 15:05:28 -0700286Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group) {
Ian Rogers52673ff2012-06-27 23:25:34 -0700287 Thread* self = new Thread(as_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700288 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700289
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700290 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700291 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700292 CHECK_NE(self->GetState(), kRunnable);
293 self->SetState(kNative);
294 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700295
Elliott Hughescac6cc72011-11-03 20:31:21 -0700296 // If we're the main thread, ClassLinker won't be created until after we're attached,
297 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800298 // In the compiler, all threads need this hack, because no-one's going to be getting
299 // a native peer!
300 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700301 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800302 } else {
303 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700304 if (thread_name != NULL) {
305 self->name_->assign(thread_name);
306 ::art::SetThreadName(thread_name);
307 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700308 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700309
310 self->GetJniEnv()->locals.AssertEmpty();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700311 return self;
312}
313
Ian Rogers365c1022012-06-22 15:05:28 -0700314void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
315 Runtime* runtime = Runtime::Current();
316 CHECK(runtime->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700317 JNIEnv* env = jni_env_;
318
Elliott Hughes462c9442012-03-23 18:47:50 -0700319 if (thread_group == NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -0700320 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700321 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700322 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700323 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700324 jboolean thread_is_daemon = as_daemon;
325
Elliott Hugheseac76672012-05-24 21:56:51 -0700326 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700327 {
328 ScopedObjectAccess soa(env);
329 peer_ = DecodeJObject(peer.get());
330 if (peer_ == NULL) {
331 CHECK(IsExceptionPending());
332 return;
333 }
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700334 }
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);
342 SetVmData(soa, peer_, Thread::Current());
343 SirtRef<String> peer_thread_name(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700344 if (peer_thread_name.get() == NULL) {
345 // The Thread constructor should have set the Thread.name to a
346 // non-null value. However, because we can run without code
347 // available (in the compiler, in tests), we manually assign the
348 // fields the constructor should have set.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700349 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->SetBoolean(peer_, thread_is_daemon);
350 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->SetObject(peer_, soa.Decode<Object*>(thread_group));
351 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->SetObject(peer_, soa.Decode<Object*>(thread_name.get()));
352 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->SetInt(peer_, thread_priority);
353 peer_thread_name.reset(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700354 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700355 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Brian Carlstrom00fae582011-10-28 01:16:28 -0700356 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800357 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700358 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700359}
360
Elliott Hughes899e7892012-01-24 14:57:32 -0800361void Thread::SetThreadName(const char* name) {
362 name_->assign(name);
363 ::art::SetThreadName(name);
364 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
365}
366
Elliott Hughesbe759c62011-09-08 19:38:21 -0700367void Thread::InitStackHwm() {
Elliott Hughese1884192012-04-23 12:38:15 -0700368 void* stack_base;
369 size_t stack_size;
370 GetThreadStack(stack_base, stack_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700371
372 // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
Elliott Hughese1884192012-04-23 12:38:15 -0700373 VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
374
375 stack_begin_ = reinterpret_cast<byte*>(stack_base);
376 stack_size_ = stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700377
Ian Rogers932746a2011-09-22 18:57:50 -0700378 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800379 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700380 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700381
Elliott Hughese1884192012-04-23 12:38:15 -0700382 // TODO: move this into the Linux GetThreadStack implementation.
383#if !defined(__APPLE__)
Elliott Hughes36ecb782012-04-17 16:55:45 -0700384 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
385 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
386 // will be broken because we'll die long before we get close to 2GB.
387 if (thin_lock_id_ == 1) {
388 rlimit stack_limit;
389 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
390 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
391 }
392 if (stack_limit.rlim_cur == RLIM_INFINITY) {
393 // Find the default stack size for new threads...
394 pthread_attr_t default_attributes;
395 size_t default_stack_size;
396 CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
397 CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
398 "default stack size query");
399 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
400
401 // ...and use that as our limit.
402 size_t old_stack_size = stack_size_;
403 stack_size_ = default_stack_size;
404 stack_begin_ += (old_stack_size - stack_size_);
Elliott Hughesfaf4ba02012-05-02 16:12:19 -0700405 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
406 << " to " << PrettySize(stack_size_)
407 << " with base " << reinterpret_cast<void*>(stack_begin_);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700408 }
409 }
Elliott Hughese1884192012-04-23 12:38:15 -0700410#endif
Elliott Hughes36ecb782012-04-17 16:55:45 -0700411
Ian Rogers932746a2011-09-22 18:57:50 -0700412 // Set stack_end_ to the bottom of the stack saving space of stack overflows
413 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700414
415 // Sanity check.
416 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700417 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700418}
419
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420void Thread::ShortDump(std::ostream& os) const {
421 os << "Thread[";
422 if (GetThinLockId() != 0) {
423 // If we're in kStarting, we won't have a thin lock id or tid yet.
424 os << GetThinLockId()
425 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700426 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 os << GetStateUnsafe()
428 << ",Thread*=" << this
429 << ",peer=" << peer_
430 << ",\"" << *name_ << "\""
431 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700432}
433
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700434void Thread::Dump(std::ostream& os) const {
435 DumpState(os);
436 DumpStack(os);
437}
438
439String* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
440 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700441 return (peer_ != NULL) ? reinterpret_cast<String*>(f->GetObject(peer_)) : NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700442}
443
Elliott Hughesffb465f2012-03-01 18:46:05 -0800444void Thread::GetThreadName(std::string& name) const {
445 name.assign(*name_);
446}
447
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448// Attempt to rectify locks so that we dump thread list with required locks before exiting.
449static void UnsafeLogFatalForSuspendCount(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700450 Locks::thread_suspend_count_lock_->Unlock();
451 Locks::mutator_lock_->SharedTryLock();
452 if (!Locks::mutator_lock_->IsSharedHeld()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
454 }
Ian Rogersb726dcb2012-09-05 08:57:23 -0700455 Locks::thread_list_lock_->TryLock();
456 if (!Locks::thread_list_lock_->IsExclusiveHeld()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
458 }
459 std::ostringstream ss;
460 Runtime::Current()->GetThreadList()->DumpLocked(ss);
461 LOG(FATAL) << self << " suspend count already zero.\n" << ss.str();
462}
463
464void Thread::ModifySuspendCount(int delta, bool for_debugger) {
465 DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
466 << delta << " " << debug_suspend_count_ << " " << this;
467 DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
Ian Rogersb726dcb2012-09-05 08:57:23 -0700468 Locks::thread_suspend_count_lock_->AssertHeld();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469
470 if (delta == -1 && suspend_count_ <= 0) {
471 // This is expected if you attach a thread during a GC.
472 if (UNLIKELY(!IsStillStarting())) {
473 UnsafeLogFatalForSuspendCount(this);
474 }
475 return;
476 }
477 suspend_count_ += delta;
478 if (for_debugger) {
479 debug_suspend_count_ += delta;
480 }
481}
482
483void Thread::FullSuspendCheck() {
484 VLOG(threads) << this << " self-suspending";
485 // Make thread appear suspended to other threads, release mutator_lock_.
486 TransitionFromRunnableToSuspended(kSuspended);
487 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
488 TransitionFromSuspendedToRunnable();
489 VLOG(threads) << this << " self-reviving";
490}
491
492void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
493 AssertThreadSuspensionIsAllowable();
494 CHECK_NE(new_state, kRunnable);
495 CHECK_EQ(this, Thread::Current());
Ian Rogersc747cff2012-08-31 18:20:08 -0700496 // Change to non-runnable state, thereby appearing suspended to the system.
497 ThreadState old_state = SetStateUnsafe(new_state);
498 CHECK_EQ(old_state, kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 // Release share on mutator_lock_.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700500 Locks::mutator_lock_->SharedUnlock();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700501}
502
503ThreadState Thread::TransitionFromSuspendedToRunnable() {
504 bool done = false;
Ian Rogersc747cff2012-08-31 18:20:08 -0700505 ThreadState old_state = GetStateUnsafe();
506 DCHECK_NE(old_state, kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 do {
Ian Rogersc747cff2012-08-31 18:20:08 -0700508 // Do a racy unsafe check of the suspend count to see if a wait is necessary. Any race that
509 // may occur is covered by the second check after we acquire a share of the mutator_lock_.
510 if (GetSuspendCountUnsafe() > 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 // Wait while our suspend count is non-zero.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700512 MutexLock mu(*Locks::thread_suspend_count_lock_);
513 Locks::mutator_lock_->AssertNotHeld(); // Otherwise we starve GC..
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700514 while (GetSuspendCount() != 0) {
515 // Re-check when Thread::resume_cond_ is notified.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700516 Thread::resume_cond_->Wait(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517 }
518 }
519 // Re-acquire shared mutator_lock_ access.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700520 Locks::mutator_lock_->SharedLock();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700521 // Holding the mutator_lock_, synchronize with any thread trying to raise the suspend count
522 // and change state to Runnable if no suspend is pending.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700523 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700524 if (GetSuspendCount() == 0) {
525 SetState(kRunnable);
526 done = true;
527 } else {
528 // Release shared mutator_lock_ access and try again.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700529 Locks::mutator_lock_->SharedUnlock();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700530 }
531 } while (!done);
532 return old_state;
533}
534
535Thread* Thread::SuspendForDebugger(jobject peer, bool request_suspension, bool* timeout) {
536 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
537 useconds_t total_delay_us = 0;
538 useconds_t delay_us = 0;
539 bool did_suspend_request = false;
540 *timeout = false;
541 while (true) {
542 Thread* thread;
543 {
544 ScopedObjectAccess soa(Thread::Current());
Ian Rogersb726dcb2012-09-05 08:57:23 -0700545 MutexLock mu(*Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546 thread = Thread::FromManagedThread(soa, peer);
547 if (thread == NULL) {
548 LOG(WARNING) << "No such thread for suspend: " << peer;
549 return NULL;
550 }
551 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700552 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700553 if (request_suspension) {
554 thread->ModifySuspendCount(+1, true /* for_debugger */);
555 request_suspension = false;
556 did_suspend_request = true;
557 }
558 // IsSuspended on the current thread will fail as the current thread is changed into
559 // Runnable above. As the suspend count is now raised if this is the current thread
560 // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
561 // to just explicitly handle the current thread in the callers to this code.
562 CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
563 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
564 // count, or else we've waited and it has self suspended) or is the current thread, we're
565 // done.
566 if (thread->IsSuspended()) {
567 return thread;
568 }
569 if (total_delay_us >= kTimeoutUs) {
570 LOG(ERROR) << "Thread suspension timed out: " << peer;
571 if (did_suspend_request) {
572 thread->ModifySuspendCount(-1, true /* for_debugger */);
573 }
574 *timeout = true;
575 return NULL;
576 }
577 }
578 // Release locks and come out of runnable state.
579 }
580 for (int i = kMaxMutexLevel; i >= 0; --i) {
581 BaseMutex* held_mutex = Thread::Current()->GetHeldMutex(static_cast<MutexLevel>(i));
582 if (held_mutex != NULL) {
583 LOG(FATAL) << "Holding " << held_mutex->GetName()
584 << " while sleeping for thread suspension";
585 }
586 }
587 {
588 useconds_t new_delay_us = delay_us * 2;
589 CHECK_GE(new_delay_us, delay_us);
590 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
591 delay_us = new_delay_us;
592 }
593 }
594 if (delay_us == 0) {
595 sched_yield();
596 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
597 delay_us = 500;
598 } else {
599 usleep(delay_us);
600 total_delay_us += delay_us;
601 }
602 }
603}
604
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700605void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700606 std::string group_name;
607 int priority;
608 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700609
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700610 if (thread != NULL && thread->peer_ != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700611 ScopedObjectAccess soa(Thread::Current());
612 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(thread->peer_);
613 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(thread->peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700614
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700615 Object* thread_group = thread->GetThreadGroup(soa);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700616 if (thread_group != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700617 Field* group_name_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700618 String* group_name_string = reinterpret_cast<String*>(group_name_field->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700619 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
620 }
621 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700622 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700623 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700624
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700625 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700626 if (scheduler_group_name.empty()) {
627 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700628 }
629
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700630 if (thread != NULL) {
631 os << '"' << *thread->name_ << '"';
632 if (is_daemon) {
633 os << " daemon";
634 }
Ian Rogersb726dcb2012-09-05 08:57:23 -0700635 MutexLock mu(*Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700636 os << " prio=" << priority
637 << " tid=" << thread->GetThinLockId()
638 << " " << thread->GetState() << "\n";
639 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700640 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700641 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700642 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700643 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700644
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700645 if (thread != NULL) {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700646 MutexLock mu(*Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700647 os << " | group=\"" << group_name << "\""
648 << " sCount=" << thread->suspend_count_
649 << " dsCount=" << thread->debug_suspend_count_
650 << " obj=" << reinterpret_cast<void*>(thread->peer_)
651 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
652 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700653
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700654 os << " | sysTid=" << tid
655 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700656 << " cgrp=" << scheduler_group_name;
657 if (thread != NULL) {
658 int policy;
659 sched_param sp;
660 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
661 os << " sched=" << policy << "/" << sp.sched_priority
662 << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
663 }
664 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700665
666 // Grab the scheduler stats for this thread.
667 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700668 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700669 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
670 } else {
671 scheduler_stats = "0 0 0";
672 }
673
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700674 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700675 int utime = 0;
676 int stime = 0;
677 int task_cpu = 0;
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700678 GetTaskStats(tid, native_thread_state, utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700679
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700680 os << " | state=" << native_thread_state
681 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700682 << " utm=" << utime
683 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700684 << " core=" << task_cpu
685 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
686 if (thread != NULL) {
687 os << " | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
688 << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
689 }
690}
691
692void Thread::DumpState(std::ostream& os) const {
693 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700694}
695
Ian Rogers0399dde2012-06-06 17:09:28 -0700696struct StackDumpVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700697 StackDumpVisitor(std::ostream& os, const Thread* thread, Context* context, bool can_allocate)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700698 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700699 : StackVisitor(thread->GetManagedStack(), thread->GetTraceStack(), context),
700 os(os), thread(thread), can_allocate(can_allocate),
701 last_method(NULL), last_line_number(0), repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700702 }
703
Ian Rogersbdb03912011-09-14 00:55:44 -0700704 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700705 if (frame_count == 0) {
706 os << " (no managed stack frames)\n";
707 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700708 }
709
Ian Rogersb726dcb2012-09-05 08:57:23 -0700710 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700711 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700712 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700713 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700714 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700715 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700716 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700717 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800718 const DexCache* dex_cache = c->GetDexCache();
719 int line_number = -1;
720 if (dex_cache != NULL) { // be tolerant of bad input
721 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
Ian Rogers0399dde2012-06-06 17:09:28 -0700722 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Ian Rogersb861dc02011-11-14 17:00:05 -0800723 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700724 if (line_number == last_line_number && last_method == m) {
725 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700726 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700727 if (repetition_count >= kMaxRepetition) {
728 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
729 }
730 repetition_count = 0;
731 last_line_number = line_number;
732 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700733 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700734 if (repetition_count < kMaxRepetition) {
735 os << " at " << PrettyMethod(m, false);
736 if (m->IsNative()) {
737 os << "(Native method)";
738 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800739 mh.ChangeMethod(m);
740 const char* source_file(mh.GetDeclaringClassSourceFile());
741 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700742 << ":" << line_number << ")";
743 }
744 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700745 if (frame_count == 0) {
746 Monitor::DescribeWait(os, thread);
747 }
748 if (can_allocate) {
749 Monitor::DescribeLocks(os, this);
750 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700751 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700752
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700753 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700754 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700755 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700756 std::ostream& os;
757 const Thread* thread;
758 bool can_allocate;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800759 MethodHelper mh;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700760 AbstractMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700761 int last_line_number;
762 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700763 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700764};
765
Elliott Hughesd92bec42011-09-02 17:04:36 -0700766void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800767 // If we're currently in native code, dump that stack before dumping the managed stack.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700768 ThreadState state;
769 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700770 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700771 state = GetState();
772 }
773 if (state == kNative) {
Elliott Hughes46e251b2012-05-22 15:10:45 -0700774 DumpKernelStack(os, GetTid(), " kernel: ", false);
775 DumpNativeStack(os, GetTid(), " native: ", false);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800776 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700777 UniquePtr<Context> context(Context::Create());
778 StackDumpVisitor dumper(os, this, context.get(), !throwing_OutOfMemoryError_);
Ian Rogers0399dde2012-06-06 17:09:28 -0700779 dumper.WalkStack();
Elliott Hughese27955c2011-08-26 15:21:24 -0700780}
781
Elliott Hughesbe759c62011-09-08 19:38:21 -0700782void Thread::ThreadExitCallback(void* arg) {
783 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700784 if (self->thread_exit_check_count_ == 0) {
785 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
786 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
787 self->thread_exit_check_count_ = 1;
788 } else {
789 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
790 }
Carl Shapirob5573532011-07-12 18:22:59 -0700791}
792
Elliott Hughesbe759c62011-09-08 19:38:21 -0700793void Thread::Startup() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700794 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700795 MutexLock mu(*Locks::thread_suspend_count_lock_); // Keep GCC happy.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700796 resume_cond_ = new ConditionVariable("Thread resumption condition variable");
797 }
798
Carl Shapirob5573532011-07-12 18:22:59 -0700799 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700800 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700801
802 // Double-check the TLS slot allocation.
803 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800804 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700805 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700806}
Carl Shapirob5573532011-07-12 18:22:59 -0700807
Elliott Hughes038a8062011-09-18 14:12:41 -0700808void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -0700809 Runtime* runtime = Runtime::Current();
810 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700811
Elliott Hughes01158d72011-09-19 19:47:10 -0700812 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700813 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700814 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500815
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700816 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700817}
818
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700819void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700820 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700821}
822
Ian Rogers52673ff2012-06-27 23:25:34 -0700823Thread::Thread(bool daemon)
Ian Rogers0399dde2012-06-06 17:09:28 -0700824 : suspend_count_(0),
825 card_table_(NULL),
826 exception_(NULL),
827 stack_end_(NULL),
828 managed_stack_(),
829 jni_env_(NULL),
830 self_(NULL),
831 state_(kNative),
Elliott Hughes47179f72011-10-27 16:44:39 -0700832 peer_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700833 stack_begin_(NULL),
834 stack_size_(0),
835 thin_lock_id_(0),
836 tid_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700837 wait_mutex_(new Mutex("a thread wait mutex")),
838 wait_cond_(new ConditionVariable("a thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700839 wait_monitor_(NULL),
840 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700841 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700842 monitor_enter_object_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700843 top_sirt_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700844 runtime_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700845 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700846 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700847 throwing_OutOfMemoryError_(false),
Ian Rogers0399dde2012-06-06 17:09:28 -0700848 debug_suspend_count_(0),
jeffhaoe343b762011-12-05 16:36:44 -0800849 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800850 trace_stack_(new std::vector<TraceStackFrame>),
Ian Rogers0399dde2012-06-06 17:09:28 -0700851 name_(new std::string(kThreadNameDuringStartup)),
Ian Rogers52673ff2012-06-27 23:25:34 -0700852 daemon_(daemon),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700853 pthread_self_(0),
Ian Rogers52673ff2012-06-27 23:25:34 -0700854 no_thread_suspension_(0),
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700855 last_no_thread_suspension_cause_(NULL),
856 thread_exit_check_count_(0) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700857 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800858 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700859}
860
Elliott Hughes7dc51662012-05-16 14:48:43 -0700861bool Thread::IsStillStarting() const {
862 // You might think you can check whether the state is kStarting, but for much of thread startup,
863 // the thread might also be in kVmWait.
864 // You might think you can check whether the peer is NULL, but the peer is actually created and
865 // assigned fairly early on, and needs to be.
866 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
867 // this thread _ever_ entered kRunnable".
868 return (*name_ == kThreadNameDuringStartup);
869}
870
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871void Thread::AssertNoPendingException() const {
872 if (UNLIKELY(IsExceptionPending())) {
873 ScopedObjectAccess soa(Thread::Current());
874 Throwable* exception = GetException();
875 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
876 }
877}
878
879static void MonitorExitVisitor(const Object* object, void* arg) NO_THREAD_SAFETY_ANALYSIS {
880 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700881 Object* entered_monitor = const_cast<Object*>(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700882 if (self->HoldsLock(entered_monitor)) {
883 LOG(WARNING) << "Calling MonitorExit on object "
884 << object << " (" << PrettyTypeOf(object) << ")"
885 << " left locked by native thread "
886 << *Thread::Current() << " which is detaching";
887 entered_monitor->MonitorExit(self);
888 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700889}
890
Elliott Hughesc0f09332012-03-26 13:27:06 -0700891void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700892 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700893 if (jni_env_ != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700894 jni_env_->monitors.VisitRoots(MonitorExitVisitor, Thread::Current());
Elliott Hughes93e74e82011-09-13 11:07:03 -0700895 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700896
Elliott Hughes93e74e82011-09-13 11:07:03 -0700897 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700898 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700899
Elliott Hughes534da072012-03-27 15:17:42 -0700900 // We may need to call user-supplied managed code.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700901 ScopedObjectAccess soa(this);
Elliott Hughes534da072012-03-27 15:17:42 -0700902
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700903 HandleUncaughtExceptions(soa);
904 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -0700905
Elliott Hughes29f27422011-09-18 16:02:18 -0700906 // this.vmData = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700907 SetVmData(soa, peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700908
Elliott Hughesc0f09332012-03-26 13:27:06 -0700909 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700910
Elliott Hughes29f27422011-09-18 16:02:18 -0700911 // Thread.join() is implemented as an Object.wait() on the Thread.lock
912 // object. Signal anyone who is waiting.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700913 Object* lock = soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(peer_);
Elliott Hughes038a8062011-09-18 14:12:41 -0700914 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700915 if (lock != NULL) {
916 lock->MonitorEnter(self);
917 lock->NotifyAll();
918 lock->MonitorExit(self);
919 }
920 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700921}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700922
Elliott Hughesc0f09332012-03-26 13:27:06 -0700923Thread::~Thread() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700924 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700925 jni_env_ = NULL;
926
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700927 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700928 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700929 CHECK_NE(GetState(), kRunnable);
930 SetState(kTerminated);
931 }
Elliott Hughes85d15452011-09-16 17:33:01 -0700932
933 delete wait_cond_;
934 delete wait_mutex_;
935
Ian Rogers776ac1f2012-04-13 23:36:36 -0700936#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -0700937 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -0700938#endif
Elliott Hughes475fc232011-10-25 15:00:35 -0700939
940 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800941 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800942 delete name_;
Elliott Hughesd8af1592012-04-16 20:40:15 -0700943
944 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700945}
946
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700947void Thread::HandleUncaughtExceptions(const ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700948 if (!IsExceptionPending()) {
949 return;
950 }
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700951 // Get and clear the exception.
952 Object* exception = GetException();
953 ClearException();
954
955 // If the thread has its own handler, use that.
Ian Rogers365c1022012-06-22 15:05:28 -0700956 Object* handler =
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700957 soa.DecodeField(WellKnownClasses::java_lang_Thread_uncaughtHandler)->GetObject(peer_);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700958 if (handler == NULL) {
959 // Otherwise use the thread group's default handler.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700960 handler = GetThreadGroup(soa);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700961 }
962
963 // Call the handler.
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700964 jmethodID mid = WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700965 AbstractMethod* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Elliott Hughes77405792012-03-15 15:22:12 -0700966 JValue args[2];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700967 args[0].SetL(peer_);
968 args[1].SetL(exception);
Elliott Hughes77405792012-03-15 15:22:12 -0700969 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700970
971 // If the handler threw, clear that exception too.
972 ClearException();
973}
974
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700975Object* Thread::GetThreadGroup(const ScopedObjectAccessUnchecked& soa) const {
976 return soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(peer_);
Elliott Hughesa2155262011-11-16 16:26:58 -0800977}
978
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700979void Thread::RemoveFromThreadGroup(const ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700980 // this.group.removeThread(this);
981 // group can be null if we're in the compiler or a test.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700982 Object* group = GetThreadGroup(soa);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700983 if (group != NULL) {
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700984 jmethodID mid = WellKnownClasses::java_lang_ThreadGroup_removeThread;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700985 AbstractMethod* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Elliott Hughes77405792012-03-15 15:22:12 -0700986 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700987 args[0].SetL(peer_);
Elliott Hughes77405792012-03-15 15:22:12 -0700988 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700989 }
990}
991
Ian Rogers408f79a2011-08-23 18:22:33 -0700992size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700993 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700994 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700995 count += cur->NumberOfReferences();
996 }
997 return count;
998}
999
Ian Rogers408f79a2011-08-23 18:22:33 -07001000bool Thread::SirtContains(jobject obj) {
1001 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001002 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1003 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001004 return true;
1005 }
1006 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001007 // JNI code invoked from portable code uses shadow frames rather than the SIRT.
1008 return managed_stack_.ShadowFramesContain(sirt_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001009}
1010
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001011void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001012 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001013 size_t num_refs = cur->NumberOfReferences();
1014 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001015 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001016 if (object != NULL) {
1017 visitor(object, arg);
1018 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001019 }
1020 }
1021}
1022
Ian Rogers408f79a2011-08-23 18:22:33 -07001023Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001024 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001025 if (obj == NULL) {
1026 return NULL;
1027 }
1028 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1029 IndirectRefKind kind = GetIndirectRefKind(ref);
1030 Object* result;
1031 switch (kind) {
1032 case kLocal:
1033 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001034 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001035 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001036 break;
1037 }
1038 case kGlobal:
1039 {
1040 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1041 IndirectReferenceTable& globals = vm->globals;
1042 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001043 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001044 break;
1045 }
1046 case kWeakGlobal:
1047 {
1048 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1049 IndirectReferenceTable& weak_globals = vm->weak_globals;
1050 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001051 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001052 if (result == kClearedJniWeakGlobal) {
1053 // This is a special case where it's okay to return NULL.
1054 return NULL;
1055 }
1056 break;
1057 }
1058 case kSirtOrInvalid:
1059 default:
1060 // TODO: make stack indirect reference table lookup more efficient
1061 // Check if this is a local reference in the SIRT
Ian Rogers0399dde2012-06-06 17:09:28 -07001062 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001063 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001064 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001065 // Assume an invalid local reference is actually a direct pointer.
1066 result = reinterpret_cast<Object*>(obj);
1067 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001068 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001069 }
1070 }
1071
1072 if (result == NULL) {
Elliott Hughes3f6635a2012-06-19 13:37:49 -07001073 JniAbortF(NULL, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
Elliott Hughesa2501992011-08-26 19:39:54 -07001074 } else {
1075 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001076 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001077 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001078 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001079 return result;
1080}
1081
Ian Rogers0399dde2012-06-06 17:09:28 -07001082class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001083 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001084 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001085 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001086 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001087 : StackVisitor(stack, trace_stack, NULL),
1088 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001089
Ian Rogersb726dcb2012-09-05 08:57:23 -07001090 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001091 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001092 // Note we also skip the frame if it doesn't have a method (namely the callee
1093 // save frame)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001094 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001095 if (skipping_ && !m->IsRuntimeMethod() &&
1096 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001097 skipping_ = false;
1098 }
1099 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001100 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001101 ++depth_;
1102 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001103 } else {
1104 ++skip_depth_;
1105 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001106 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001107 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001108
1109 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001110 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001111 }
1112
Elliott Hughes29f27422011-09-18 16:02:18 -07001113 int GetSkipDepth() const {
1114 return skip_depth_;
1115 }
1116
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001117 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001118 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001119 uint32_t skip_depth_;
1120 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001121};
1122
Ian Rogers0399dde2012-06-06 17:09:28 -07001123class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001124 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001125 explicit BuildInternalStackTraceVisitor(const ManagedStack* stack,
1126 const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001127 int skip_depth)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001128 : StackVisitor(stack, trace_stack, NULL),
1129 skip_depth_(skip_depth), count_(0), dex_pc_trace_(NULL), method_trace_(NULL) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001130
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001131 bool Init(int depth, const ScopedObjectAccess& soa)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001133 // Allocate method trace with an extra slot that will hold the PC trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001134 SirtRef<ObjectArray<Object> >
1135 method_trace(Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1));
1136 if (method_trace.get() == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001137 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001138 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001139 IntArray* dex_pc_trace = IntArray::Alloc(depth);
1140 if (dex_pc_trace == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001141 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001142 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001143 // Save PC trace in last element of method trace, also places it into the
1144 // object graph.
Ian Rogers0399dde2012-06-06 17:09:28 -07001145 method_trace->Set(depth, dex_pc_trace);
1146 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001147 const char* last_no_suspend_cause =
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001148 soa.Self()->StartAssertNoThreadSuspension("Building internal stack trace");
Ian Rogers52673ff2012-06-27 23:25:34 -07001149 CHECK(last_no_suspend_cause == NULL) << last_no_suspend_cause;
Ian Rogers0399dde2012-06-06 17:09:28 -07001150 method_trace_ = method_trace.get();
1151 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001152 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001153 }
1154
Ian Rogers0399dde2012-06-06 17:09:28 -07001155 virtual ~BuildInternalStackTraceVisitor() {
Ian Rogers52673ff2012-06-27 23:25:34 -07001156 if (method_trace_ != NULL) {
1157 Thread::Current()->EndAssertNoThreadSuspension(NULL);
1158 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001159 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001160
Ian Rogersb726dcb2012-09-05 08:57:23 -07001161 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001162 if (method_trace_ == NULL || dex_pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001163 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001164 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001165 if (skip_depth_ > 0) {
1166 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001167 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001168 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001169 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001170 if (m->IsRuntimeMethod()) {
1171 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001172 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001173 method_trace_->Set(count_, m);
1174 dex_pc_trace_->Set(count_, GetDexPc());
Ian Rogersaaa20802011-09-11 21:47:37 -07001175 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001176 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001177 }
1178
Ian Rogers0399dde2012-06-06 17:09:28 -07001179 ObjectArray<Object>* GetInternalStackTrace() const {
1180 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001181 }
1182
1183 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001184 // How many more frames to skip.
1185 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001186 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001187 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001188 // Array of dex PC values.
1189 IntArray* dex_pc_trace_;
1190 // 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 -07001191 ObjectArray<Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001192};
1193
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001194void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1195 sirt->SetLink(top_sirt_);
1196 top_sirt_ = sirt;
1197}
1198
1199StackIndirectReferenceTable* Thread::PopSirt() {
1200 CHECK(top_sirt_ != NULL);
1201 StackIndirectReferenceTable* sirt = top_sirt_;
1202 top_sirt_ = top_sirt_->GetLink();
1203 return sirt;
1204}
1205
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001206jobject Thread::CreateInternalStackTrace(const ScopedObjectAccess& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001207 // Compute depth of stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001208 CountStackDepthVisitor count_visitor(GetManagedStack(), GetTraceStack());
1209 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001210 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001211 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001212
Ian Rogersaaa20802011-09-11 21:47:37 -07001213 // Build internal stack trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001214 BuildInternalStackTraceVisitor build_trace_visitor(GetManagedStack(), GetTraceStack(),
1215 skip_depth);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001216 if (!build_trace_visitor.Init(depth, soa)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001217 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001218 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001219 build_trace_visitor.WalkStack();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001220 return soa.AddLocalReference<jobjectArray>(build_trace_visitor.GetInternalStackTrace());
Ian Rogersaaa20802011-09-11 21:47:37 -07001221}
1222
Elliott Hughes01158d72011-09-19 19:47:10 -07001223jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1224 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001225 // Transition into runnable state to work on Object*/Array*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001226 ScopedObjectAccess soa(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001227 // Decode the internal stack trace into the depth, method trace and PC trace
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001228 ObjectArray<Object>* method_trace = soa.Decode<ObjectArray<Object>*>(internal);
Ian Rogers9074b992011-10-26 17:41:55 -07001229 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001230 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1231
1232 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1233
Elliott Hughes01158d72011-09-19 19:47:10 -07001234 jobjectArray result;
1235 ObjectArray<StackTraceElement>* java_traces;
1236 if (output_array != NULL) {
1237 // Reuse the array we were given.
1238 result = output_array;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001239 java_traces = soa.Decode<ObjectArray<StackTraceElement>*>(output_array);
Elliott Hughes01158d72011-09-19 19:47:10 -07001240 // ...adjusting the number of frames we'll write to not exceed the array length.
1241 depth = std::min(depth, java_traces->GetLength());
1242 } else {
1243 // Create java_trace array and place in local reference table
1244 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001245 if (java_traces == NULL) {
1246 return NULL;
1247 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001248 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001249 }
1250
1251 if (stack_depth != NULL) {
1252 *stack_depth = depth;
1253 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001254
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001255 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001256 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001257 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001258 AbstractMethod* method = down_cast<AbstractMethod*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001259 mh.ChangeMethod(method);
Ian Rogers0399dde2012-06-06 17:09:28 -07001260 uint32_t dex_pc = pc_trace->Get(i);
1261 int32_t line_number = mh.GetLineNumFromDexPC(dex_pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001262 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001263 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001264 const char* descriptor = mh.GetDeclaringClassDescriptor();
1265 CHECK(descriptor != NULL);
1266 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001267 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1268 if (class_name_object.get() == NULL) {
1269 return NULL;
1270 }
Ian Rogers48601312011-12-07 16:45:19 -08001271 const char* method_name = mh.GetName();
1272 CHECK(method_name != NULL);
1273 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001274 if (method_name_object.get() == NULL) {
1275 return NULL;
1276 }
Ian Rogers48601312011-12-07 16:45:19 -08001277 const char* source_file = mh.GetDeclaringClassSourceFile();
1278 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001279 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001280 method_name_object.get(),
1281 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001282 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001283 if (obj == NULL) {
1284 return NULL;
1285 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001286#ifdef MOVING_GARBAGE_COLLECTOR
1287 // Re-read after potential GC
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001288 java_traces = Decode<ObjectArray<Object>*>(soa.Env(), result);
1289 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(soa.Env(), internal));
Ian Rogersaaa20802011-09-11 21:47:37 -07001290 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1291#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001292 java_traces->Set(i, obj);
1293 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001294 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001295}
1296
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001297void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001298 va_list args;
1299 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001300 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001301 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001302}
1303
1304void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1305 std::string msg;
1306 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001307 ThrowNewException(exception_class_descriptor, msg.c_str());
1308}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001309
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001310void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001311 AssertNoPendingException(); // Callers should either clear or call ThrowNewWrappedException.
Elliott Hughesa4f94742012-05-29 16:28:38 -07001312 ThrowNewWrappedException(exception_class_descriptor, msg);
1313}
1314
1315void Thread::ThrowNewWrappedException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001316 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001317 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001318 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001319 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001320 descriptor.erase(descriptor.length() - 1);
1321
1322 JNIEnv* env = GetJniEnv();
Elliott Hughesa4f94742012-05-29 16:28:38 -07001323 jobject cause = env->ExceptionOccurred();
1324 env->ExceptionClear();
1325
Elliott Hughes726079d2011-10-07 18:43:44 -07001326 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001327 if (exception_class.get() == NULL) {
1328 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1329 << PrettyTypeOf(GetException());
1330 CHECK(IsExceptionPending());
1331 return;
1332 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001333 if (!Runtime::Current()->IsStarted()) {
1334 // Something is trying to throw an exception without a started
1335 // runtime, which is the common case in the compiler. We won't be
1336 // able to invoke the constructor of the exception, so use
1337 // AllocObject which will not invoke a constructor.
1338 ScopedLocalRef<jthrowable> exception(
1339 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1340 if (exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001341 ScopedObjectAccessUnchecked soa(env);
1342 Throwable* t = reinterpret_cast<Throwable*>(soa.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001343 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001344 soa.Self()->SetException(t);
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001345 } else {
1346 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1347 << PrettyTypeOf(GetException());
1348 CHECK(IsExceptionPending());
1349 }
1350 return;
1351 }
Elliott Hughesa4f94742012-05-29 16:28:38 -07001352 int rc = ::art::ThrowNewException(env, exception_class.get(), msg, cause);
Elliott Hughes30646832011-10-13 16:59:46 -07001353 if (rc != JNI_OK) {
1354 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1355 << PrettyTypeOf(GetException());
1356 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001357 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001358}
1359
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001360void Thread::ThrowOutOfMemoryError(const char* msg) {
1361 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1362 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001363 if (!throwing_OutOfMemoryError_) {
1364 throwing_OutOfMemoryError_ = true;
Elliott Hughes57aba862012-06-20 14:00:47 -07001365 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001366 } else {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001367 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
1368 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001369 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001370 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001371}
1372
Elliott Hughes498508c2011-10-17 14:58:22 -07001373Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001374 return Thread::Current();
1375}
1376
1377void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001378 std::ostringstream ss;
1379 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001380 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001381 // log to stderr for debugging command line processes
1382 std::cerr << str;
1383#ifdef HAVE_ANDROID_OS
1384 // log to logcat for debugging frameworks processes
1385 LOG(INFO) << str;
1386#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001387}
1388
Elliott Hughes98e20172012-04-24 15:38:13 -07001389struct EntryPointInfo {
1390 uint32_t offset;
1391 const char* name;
1392};
1393#define ENTRY_POINT_INFO(x) { ENTRYPOINT_OFFSET(x), #x }
1394static const EntryPointInfo gThreadEntryPointInfo[] = {
1395 ENTRY_POINT_INFO(pAllocArrayFromCode),
1396 ENTRY_POINT_INFO(pAllocArrayFromCodeWithAccessCheck),
1397 ENTRY_POINT_INFO(pAllocObjectFromCode),
1398 ENTRY_POINT_INFO(pAllocObjectFromCodeWithAccessCheck),
1399 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCode),
1400 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCodeWithAccessCheck),
1401 ENTRY_POINT_INFO(pInstanceofNonTrivialFromCode),
1402 ENTRY_POINT_INFO(pCanPutArrayElementFromCode),
1403 ENTRY_POINT_INFO(pCheckCastFromCode),
1404 ENTRY_POINT_INFO(pDebugMe),
1405 ENTRY_POINT_INFO(pUpdateDebuggerFromCode),
1406 ENTRY_POINT_INFO(pInitializeStaticStorage),
1407 ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccessFromCode),
1408 ENTRY_POINT_INFO(pInitializeTypeFromCode),
1409 ENTRY_POINT_INFO(pResolveStringFromCode),
1410 ENTRY_POINT_INFO(pSet32Instance),
1411 ENTRY_POINT_INFO(pSet32Static),
1412 ENTRY_POINT_INFO(pSet64Instance),
1413 ENTRY_POINT_INFO(pSet64Static),
1414 ENTRY_POINT_INFO(pSetObjInstance),
1415 ENTRY_POINT_INFO(pSetObjStatic),
1416 ENTRY_POINT_INFO(pGet32Instance),
1417 ENTRY_POINT_INFO(pGet32Static),
1418 ENTRY_POINT_INFO(pGet64Instance),
1419 ENTRY_POINT_INFO(pGet64Static),
1420 ENTRY_POINT_INFO(pGetObjInstance),
1421 ENTRY_POINT_INFO(pGetObjStatic),
1422 ENTRY_POINT_INFO(pHandleFillArrayDataFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001423 ENTRY_POINT_INFO(pFindNativeMethod),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001424 ENTRY_POINT_INFO(pJniMethodStart),
1425 ENTRY_POINT_INFO(pJniMethodStartSynchronized),
1426 ENTRY_POINT_INFO(pJniMethodEnd),
1427 ENTRY_POINT_INFO(pJniMethodEndSynchronized),
1428 ENTRY_POINT_INFO(pJniMethodEndWithReference),
1429 ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
Elliott Hughes98e20172012-04-24 15:38:13 -07001430 ENTRY_POINT_INFO(pLockObjectFromCode),
1431 ENTRY_POINT_INFO(pUnlockObjectFromCode),
1432 ENTRY_POINT_INFO(pCmpgDouble),
1433 ENTRY_POINT_INFO(pCmpgFloat),
1434 ENTRY_POINT_INFO(pCmplDouble),
1435 ENTRY_POINT_INFO(pCmplFloat),
1436 ENTRY_POINT_INFO(pDadd),
1437 ENTRY_POINT_INFO(pDdiv),
1438 ENTRY_POINT_INFO(pDmul),
1439 ENTRY_POINT_INFO(pDsub),
1440 ENTRY_POINT_INFO(pF2d),
1441 ENTRY_POINT_INFO(pFmod),
Ian Rogers0183dd72012-09-17 23:06:51 -07001442 ENTRY_POINT_INFO(pSqrt),
Elliott Hughes98e20172012-04-24 15:38:13 -07001443 ENTRY_POINT_INFO(pI2d),
1444 ENTRY_POINT_INFO(pL2d),
1445 ENTRY_POINT_INFO(pD2f),
1446 ENTRY_POINT_INFO(pFadd),
1447 ENTRY_POINT_INFO(pFdiv),
1448 ENTRY_POINT_INFO(pFmodf),
1449 ENTRY_POINT_INFO(pFmul),
1450 ENTRY_POINT_INFO(pFsub),
1451 ENTRY_POINT_INFO(pI2f),
1452 ENTRY_POINT_INFO(pL2f),
1453 ENTRY_POINT_INFO(pD2iz),
1454 ENTRY_POINT_INFO(pF2iz),
1455 ENTRY_POINT_INFO(pIdivmod),
1456 ENTRY_POINT_INFO(pD2l),
1457 ENTRY_POINT_INFO(pF2l),
1458 ENTRY_POINT_INFO(pLdiv),
1459 ENTRY_POINT_INFO(pLdivmod),
1460 ENTRY_POINT_INFO(pLmul),
1461 ENTRY_POINT_INFO(pShlLong),
1462 ENTRY_POINT_INFO(pShrLong),
1463 ENTRY_POINT_INFO(pUshrLong),
1464 ENTRY_POINT_INFO(pIndexOf),
1465 ENTRY_POINT_INFO(pMemcmp16),
1466 ENTRY_POINT_INFO(pStringCompareTo),
1467 ENTRY_POINT_INFO(pMemcpy),
1468 ENTRY_POINT_INFO(pUnresolvedDirectMethodTrampolineFromCode),
1469 ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
1470 ENTRY_POINT_INFO(pInvokeInterfaceTrampoline),
1471 ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
1472 ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
1473 ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
1474 ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
1475 ENTRY_POINT_INFO(pCheckSuspendFromCode),
1476 ENTRY_POINT_INFO(pTestSuspendFromCode),
1477 ENTRY_POINT_INFO(pDeliverException),
1478 ENTRY_POINT_INFO(pThrowAbstractMethodErrorFromCode),
1479 ENTRY_POINT_INFO(pThrowArrayBoundsFromCode),
1480 ENTRY_POINT_INFO(pThrowDivZeroFromCode),
1481 ENTRY_POINT_INFO(pThrowNoSuchMethodFromCode),
1482 ENTRY_POINT_INFO(pThrowNullPointerFromCode),
1483 ENTRY_POINT_INFO(pThrowStackOverflowFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001484};
1485#undef ENTRY_POINT_INFO
1486
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001487void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1488 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes98e20172012-04-24 15:38:13 -07001489
1490#define DO_THREAD_OFFSET(x) if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { os << # x; return; }
1491 DO_THREAD_OFFSET(card_table_);
1492 DO_THREAD_OFFSET(exception_);
1493 DO_THREAD_OFFSET(jni_env_);
1494 DO_THREAD_OFFSET(self_);
1495 DO_THREAD_OFFSET(stack_end_);
1496 DO_THREAD_OFFSET(state_);
1497 DO_THREAD_OFFSET(suspend_count_);
1498 DO_THREAD_OFFSET(thin_lock_id_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001499 //DO_THREAD_OFFSET(top_of_managed_stack_);
1500 //DO_THREAD_OFFSET(top_of_managed_stack_pc_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001501 DO_THREAD_OFFSET(top_sirt_);
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001502#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001503
1504 size_t entry_point_count = arraysize(gThreadEntryPointInfo);
1505 CHECK_EQ(entry_point_count * size_of_pointers, sizeof(EntryPoints));
1506 uint32_t expected_offset = OFFSETOF_MEMBER(Thread, entrypoints_);
1507 for (size_t i = 0; i < entry_point_count; ++i) {
1508 CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset);
1509 expected_offset += size_of_pointers;
1510 if (gThreadEntryPointInfo[i].offset == offset) {
1511 os << gThreadEntryPointInfo[i].name;
1512 return;
1513 }
1514 }
1515 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001516}
1517
Ian Rogers0399dde2012-06-06 17:09:28 -07001518static const bool kDebugExceptionDelivery = false;
1519class CatchBlockStackVisitor : public StackVisitor {
Ian Rogersbdb03912011-09-14 00:55:44 -07001520 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001521 CatchBlockStackVisitor(Thread* self, Throwable* exception)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001522 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers0399dde2012-06-06 17:09:28 -07001523 : StackVisitor(self->GetManagedStack(), self->GetTraceStack(), self->GetLongJumpContext()),
1524 self_(self), exception_(exception), to_find_(exception->GetClass()), throw_method_(NULL),
1525 throw_frame_id_(0), throw_dex_pc_(0), handler_quick_frame_(NULL),
1526 handler_quick_frame_pc_(0), handler_dex_pc_(0), native_method_count_(0),
Ian Rogers57b86d42012-03-27 16:05:41 -07001527 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers52673ff2012-06-27 23:25:34 -07001528 // Exception not in root sets, can't allow GC.
1529 last_no_assert_suspension_cause_ = self->StartAssertNoThreadSuspension("Finding catch block");
1530 }
1531
1532 ~CatchBlockStackVisitor() {
1533 LOG(FATAL) << "UNREACHABLE"; // Expected to take long jump.
Ian Rogers67375ac2011-09-14 00:55:44 -07001534 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001535
Ian Rogersb726dcb2012-09-05 08:57:23 -07001536 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1537 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001538 AbstractMethod* method = GetMethod();
Elliott Hughes530fa002012-03-12 11:44:49 -07001539 if (method == NULL) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001540 // This is the upcall, we remember the frame and last pc so that we may long jump to them.
1541 handler_quick_frame_pc_ = GetCurrentQuickFramePc();
1542 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001543 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001544 }
1545 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001546 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001547 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001548 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001549 } else {
Ian Rogers0399dde2012-06-06 17:09:28 -07001550 if (throw_method_ == NULL) {
1551 throw_method_ = method;
1552 throw_frame_id_ = GetFrameId();
1553 throw_dex_pc_ = GetDexPc();
Ian Rogers67375ac2011-09-14 00:55:44 -07001554 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001555 if (method->IsNative()) {
1556 native_method_count_++;
1557 } else {
1558 // Unwind stack when an exception occurs during method tracing
1559 if (UNLIKELY(method_tracing_active_ && IsTraceExitPc(GetCurrentQuickFramePc()))) {
buzbee8320f382012-09-11 16:29:42 -07001560 uintptr_t pc = TraceMethodUnwindFromCode(Thread::Current());
Ian Rogers0c7abda2012-09-19 13:33:42 -07001561 dex_pc = method->ToDexPc(pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001562 } else {
1563 dex_pc = GetDexPc();
1564 }
1565 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001566 }
1567 if (dex_pc != DexFile::kDexNoIndex) {
1568 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1569 if (found_dex_pc != DexFile::kDexNoIndex) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001570 handler_dex_pc_ = found_dex_pc;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001571 handler_quick_frame_pc_ = method->ToNativePc(found_dex_pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001572 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001573 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001574 }
1575 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001576 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001577 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001578
Ian Rogersb726dcb2012-09-05 08:57:23 -07001579 void DoLongJump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001580 AbstractMethod* catch_method = *handler_quick_frame_;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001581 Dbg::PostException(self_, throw_frame_id_, throw_method_, throw_dex_pc_,
Ian Rogers0399dde2012-06-06 17:09:28 -07001582 catch_method, handler_dex_pc_, exception_);
1583 if (kDebugExceptionDelivery) {
1584 if (catch_method == NULL) {
1585 LOG(INFO) << "Handler is upcall";
1586 } else {
1587 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1588 const DexFile& dex_file =
1589 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1590 int line_number = dex_file.GetLineNumFromPC(catch_method, handler_dex_pc_);
1591 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
1592 }
1593 }
Ian Rogers52673ff2012-06-27 23:25:34 -07001594 self_->SetException(exception_); // Exception back in root set.
1595 self_->EndAssertNoThreadSuspension(last_no_assert_suspension_cause_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001596 // Place context back on thread so it will be available when we continue.
1597 self_->ReleaseLongJumpContext(context_);
1598 context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
1599 CHECK_NE(handler_quick_frame_pc_, 0u);
1600 context_->SetPC(handler_quick_frame_pc_);
1601 context_->SmashCallerSaves();
1602 context_->DoLongJump();
1603 }
1604
1605 private:
1606 Thread* self_;
1607 Throwable* exception_;
1608 // The type of the exception catch block to find.
Ian Rogersbdb03912011-09-14 00:55:44 -07001609 Class* to_find_;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001610 AbstractMethod* throw_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001611 JDWP::FrameId throw_frame_id_;
1612 uint32_t throw_dex_pc_;
1613 // Quick frame with found handler or last frame if no handler found.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001614 AbstractMethod** handler_quick_frame_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001615 // PC to branch to for the handler.
1616 uintptr_t handler_quick_frame_pc_;
1617 // Associated dex PC.
1618 uint32_t handler_dex_pc_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001619 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1620 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001621 // Is method tracing active?
1622 const bool method_tracing_active_;
Ian Rogers52673ff2012-06-27 23:25:34 -07001623 // Support for nesting no thread suspension checks.
1624 const char* last_no_assert_suspension_cause_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001625};
1626
Ian Rogersff1ed472011-09-20 13:46:24 -07001627void Thread::DeliverException() {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001628 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001629 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001630 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001631 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001632 ClearException();
1633 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001634 String* msg = exception->GetDetailMessage();
1635 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1636 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
Elliott Hughesc073b072012-05-24 19:29:17 -07001637 << ": " << str_msg << "\n");
Ian Rogers28ad40d2011-10-27 15:19:26 -07001638 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001639 CatchBlockStackVisitor catch_finder(this, exception);
1640 catch_finder.WalkStack(true);
1641 catch_finder.DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001642 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001643}
1644
Ian Rogersbdb03912011-09-14 00:55:44 -07001645Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001646 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001647 if (result == NULL) {
1648 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07001649 } else {
1650 long_jump_context_ = NULL; // Avoid context being shared.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001651 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001652 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001653}
1654
Mathieu Chartier66f19252012-09-18 08:57:04 -07001655AbstractMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, size_t* frame_id) const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001656 struct CurrentMethodVisitor : public StackVisitor {
1657 CurrentMethodVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001658 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001659 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001660 : StackVisitor(stack, trace_stack, NULL), method_(NULL), dex_pc_(0), frame_id_(0) {}
Elliott Hughes8be2d402012-02-23 14:22:41 -08001661
Ian Rogersb726dcb2012-09-05 08:57:23 -07001662 virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001663 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001664 if (m->IsRuntimeMethod()) {
1665 // Continue if this is a runtime method.
1666 return true;
1667 }
1668 method_ = m;
1669 dex_pc_ = GetDexPc();
1670 frame_id_ = GetFrameId();
1671 return false;
1672 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001673 AbstractMethod* method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001674 uint32_t dex_pc_;
1675 size_t frame_id_;
1676 };
1677
1678 CurrentMethodVisitor visitor(GetManagedStack(), GetTraceStack());
1679 visitor.WalkStack(false);
1680 if (dex_pc != NULL) {
1681 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001682 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001683 if (frame_id != NULL) {
1684 *frame_id = visitor.frame_id_;
jeffhao33dc7712011-11-09 17:54:24 -08001685 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001686 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08001687}
1688
Elliott Hughes5f791332011-09-15 17:45:30 -07001689bool Thread::HoldsLock(Object* object) {
1690 if (object == NULL) {
1691 return false;
1692 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001693 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001694}
1695
Ian Rogers0399dde2012-06-06 17:09:28 -07001696class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001697 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001698 ReferenceMapVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001699 Context* context, Heap::RootVisitor* root_visitor, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001700 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersca190662012-06-26 15:45:57 -07001701 : StackVisitor(stack, trace_stack, context), root_visitor_(root_visitor), arg_(arg) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07001702
Ian Rogersb726dcb2012-09-05 08:57:23 -07001703 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001704 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001705 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
1706 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001707 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001708 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
1709 if (shadow_frame != NULL) {
1710 shadow_frame->VisitRoots(root_visitor_, arg_);
1711 } else {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001712 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001713 // Process register map (which native and runtime methods don't have)
Ian Rogers640495b2012-06-22 15:15:47 -07001714 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001715 const uint8_t* native_gc_map = m->GetNativeGcMap();
1716 CHECK(native_gc_map != NULL) << PrettyMethod(m);
1717 mh_.ChangeMethod(m);
1718 const DexFile::CodeItem* code_item = mh_.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001719 DCHECK(code_item != NULL) << PrettyMethod(m); // Can't be NULL or how would we compile its instructions?
Ian Rogers0c7abda2012-09-19 13:33:42 -07001720 NativePcOffsetToReferenceMap map(native_gc_map);
Ian Rogers0399dde2012-06-06 17:09:28 -07001721 size_t num_regs = std::min(map.RegWidth() * 8,
1722 static_cast<size_t>(code_item->registers_size_));
Ian Rogers0c7abda2012-09-19 13:33:42 -07001723 if (num_regs > 0) {
1724 const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
1725 DCHECK(reg_bitmap != NULL);
1726 const VmapTable vmap_table(m->GetVmapTableRaw());
1727 uint32_t core_spills = m->GetCoreSpillMask();
1728 uint32_t fp_spills = m->GetFpSpillMask();
1729 size_t frame_size = m->GetFrameSizeInBytes();
1730 // For all dex registers in the bitmap
Mathieu Chartier66f19252012-09-18 08:57:04 -07001731 AbstractMethod** cur_quick_frame = GetCurrentQuickFrame();
Ian Rogers0c7abda2012-09-19 13:33:42 -07001732 DCHECK(cur_quick_frame != NULL);
1733 for (size_t reg = 0; reg < num_regs; ++reg) {
1734 // Does this register hold a reference?
1735 if (TestBitmap(reg, reg_bitmap)) {
1736 uint32_t vmap_offset;
1737 Object* ref;
1738 if (vmap_table.IsInContext(reg, vmap_offset)) {
1739 // Compute the register we need to load from the context
1740 uint32_t spill_mask = core_spills;
1741 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1742 uint32_t matches = 0;
1743 uint32_t spill_shifts = 0;
1744 while (matches != (vmap_offset + 1)) {
1745 DCHECK_NE(spill_mask, 0u);
1746 matches += spill_mask & 1; // Add 1 if the low bit is set
1747 spill_mask >>= 1;
1748 spill_shifts++;
1749 }
1750 spill_shifts--; // wind back one as we want the last match
1751 ref = reinterpret_cast<Object*>(GetGPR(spill_shifts));
1752 } else {
1753 ref = reinterpret_cast<Object*>(GetVReg(cur_quick_frame, code_item, core_spills,
1754 fp_spills, frame_size, reg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001755 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07001756 if (ref != NULL) {
1757 root_visitor_(ref, arg_);
1758 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001759 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001760 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001761 }
1762 }
1763 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001764 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001765 }
1766
1767 private:
1768 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1769 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1770 }
1771
Ian Rogers0c7abda2012-09-19 13:33:42 -07001772 // Call-back when we visit a root.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001773 Heap::RootVisitor* root_visitor_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001774 // Argument to call-back.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001775 void* arg_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001776 // A method helper we keep around to avoid dex file/cache re-computations.
1777 MethodHelper mh_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001778};
1779
1780void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001781 if (exception_ != NULL) {
1782 visitor(exception_, arg);
1783 }
1784 if (peer_ != NULL) {
1785 visitor(peer_, arg);
1786 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001787 if (class_loader_override_ != NULL) {
1788 visitor(class_loader_override_, arg);
1789 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001790 jni_env_->locals.VisitRoots(visitor, arg);
1791 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001792
1793 SirtVisitRoots(visitor, arg);
1794
Ian Rogersd6b1f612011-09-27 13:38:14 -07001795 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001796 Context* context = GetLongJumpContext();
1797 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context, visitor, arg);
1798 mapper.WalkStack();
1799 ReleaseLongJumpContext(context);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001800}
1801
jeffhao25045522012-03-13 19:34:37 -07001802#if VERIFY_OBJECT_ENABLED
Ian Rogers0399dde2012-06-06 17:09:28 -07001803static void VerifyObject(const Object* obj, void* arg) {
1804 Heap* heap = reinterpret_cast<Heap*>(arg);
1805 heap->VerifyObject(obj);
jeffhao25045522012-03-13 19:34:37 -07001806}
1807
1808void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07001809 UniquePtr<Context> context(Context::Create());
Ian Rogers67054b52012-06-26 16:02:10 -07001810 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context.get(), VerifyObject,
Ian Rogers0399dde2012-06-06 17:09:28 -07001811 Runtime::Current()->GetHeap());
1812 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07001813}
1814#endif
1815
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816// Set the stack end to that to be used during a stack overflow
1817void Thread::SetStackEndForStackOverflow() {
1818 // During stack overflow we allow use of the full stack
1819 if (stack_end_ == stack_begin_) {
1820 DumpStack(std::cerr);
1821 LOG(FATAL) << "Need to increase kStackOverflowReservedBytes (currently "
1822 << kStackOverflowReservedBytes << ")";
1823 }
1824
1825 stack_end_ = stack_begin_;
1826}
1827
Elliott Hughes330304d2011-08-12 14:28:05 -07001828std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07001830 return os;
1831}
1832
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833#ifndef NDEBUG
1834void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
1835 CHECK_EQ(0u, no_thread_suspension_) << last_no_thread_suspension_cause_;
1836 if (check_locks) {
1837 bool bad_mutexes_held = false;
1838 for (int i = kMaxMutexLevel; i >= 0; --i) {
1839 // We expect no locks except the mutator_lock_.
1840 if (i != kMutatorLock) {
1841 BaseMutex* held_mutex = GetHeldMutex(static_cast<MutexLevel>(i));
1842 if (held_mutex != NULL) {
1843 LOG(ERROR) << "holding \"" << held_mutex->GetName()
1844 << "\" at point where thread suspension is expected";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001845 bad_mutexes_held = true;
1846 }
1847 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001848 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001849 CHECK(!bad_mutexes_held);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001850 }
1851}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001852#endif
Elliott Hughesa4060e52012-03-02 16:51:35 -08001853
Elliott Hughes8daa0922011-09-11 13:46:25 -07001854} // namespace art