blob: 5d1afe1a0d8d4a2408425ca24b56b7306043f839 [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
Elliott Hughes2acf36d2012-04-17 13:30:13 -070021#include <signal.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/resource.h>
23#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070024
Carl Shapirob5573532011-07-12 18:22:59 -070025#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070026#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070027#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070028#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070029#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070030
Elliott Hughesa5b897e2011-08-16 11:33:06 -070031#include "class_linker.h"
Brian Carlstromdf143242011-10-10 18:05:34 -070032#include "class_loader.h"
Ian Rogers474b6da2012-09-25 00:20:38 -070033#include "cutils/atomic.h"
34#include "cutils/atomic-inline.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070035#include "debugger.h"
Ian Rogers0c7abda2012-09-19 13:33:42 -070036#include "gc_map.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070037#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070038#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070039#include "monitor.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070040#include "mutex.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070041#include "oat/runtime/context.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070042#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080043#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050044#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070045#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070046#include "runtime_support.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070047#include "scoped_thread_state_change.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070048#include "ScopedLocalRef.h"
Ian Rogers30fab402012-01-23 15:43:46 -080049#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070050#include "stack.h"
51#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070052#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070053#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070055
56namespace art {
57
58pthread_key_t Thread::pthread_key_self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059ConditionVariable* Thread::resume_cond_;
Carl Shapirob5573532011-07-12 18:22:59 -070060
Elliott Hughes7dc51662012-05-16 14:48:43 -070061static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
62
Ian Rogers5d76c432011-10-31 21:42:49 -070063void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080064 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070065}
66
Elliott Hughes99250ba2012-04-17 11:09:17 -070067#if !defined(__APPLE__)
Elliott Hughes3ea0f422012-04-16 17:01:43 -070068static void UnimplementedEntryPoint() {
69 UNIMPLEMENTED(FATAL);
70}
Elliott Hughes99250ba2012-04-17 11:09:17 -070071#endif
Elliott Hughes3ea0f422012-04-16 17:01:43 -070072
buzbee3ea4ec52011-08-22 17:37:19 -070073void Thread::InitFunctionPointers() {
Elliott Hughes99250ba2012-04-17 11:09:17 -070074#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
Elliott Hughes3ea0f422012-04-16 17:01:43 -070075 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
76 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
77 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
78 for (uintptr_t* it = begin; it != end; ++it) {
79 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
80 }
Elliott Hughes99250ba2012-04-17 11:09:17 -070081#endif
Ian Rogers57b86d42012-03-27 16:05:41 -070082 InitEntryPoints(&entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -070083}
84
85void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
86 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers776ac1f2012-04-13 23:36:36 -070087#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070088 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
Ian Rogers776ac1f2012-04-13 23:36:36 -070089#else
90 UNIMPLEMENTED(FATAL);
91#endif
buzbee3ea4ec52011-08-22 17:37:19 -070092}
93
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070094void Thread::InitTid() {
95 tid_ = ::art::GetTid();
96}
97
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070098void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -070099 // One thread (us) survived the fork, but we have a new tid so we need to
100 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700101 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700102}
103
Brian Carlstrom78128a62011-09-15 17:21:19 -0700104void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700105 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700106 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700107
Elliott Hughes47179f72011-10-27 16:44:39 -0700108 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700109 ScopedObjectAccess soa(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700110 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700111 SirtRef<String> thread_name(self->GetThreadName(soa));
Ian Rogers365c1022012-06-22 15:05:28 -0700112 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
113 }
114
115 Dbg::PostThreadStart(self);
116
117 // Invoke the 'run' method of our java.lang.Thread.
118 CHECK(self->peer_ != NULL);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700119 Object* receiver = soa.Decode<Object*>(self->peer_);
Ian Rogers365c1022012-06-22 15:05:28 -0700120 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700121 AbstractMethod* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Ian Rogers365c1022012-06-22 15:05:28 -0700122 m->Invoke(self, receiver, NULL, NULL);
Elliott Hughes47179f72011-10-27 16:44:39 -0700123 }
124
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700125 // Detach and delete self.
126 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700127
Carl Shapirob5573532011-07-12 18:22:59 -0700128 return NULL;
129}
130
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700131static void SetVmData(const ScopedObjectAccess& soa, Object* managed_thread,
132 Thread* native_thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700135 f->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700136}
137
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, Object* thread_peer) {
139 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
140 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetInt(thread_peer)));
141 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
142 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700143 if (kIsDebugBuild) {
144 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
145 if (result != NULL && !result->IsSuspended()) {
146 Locks::thread_list_lock_->AssertHeld(soa.Self());
147 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700148 }
149 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800150}
151
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
153 return FromManagedThread(soa, soa.Decode<Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700154}
155
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700156static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700157 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700158 if (stack_size == 0) {
159 stack_size = Runtime::Current()->GetDefaultStackSize();
160 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700161
Brian Carlstrom6414a972012-04-14 14:20:04 -0700162 // Dalvik used the bionic pthread default stack size for native threads,
163 // so include that here to support apps that expect large native stacks.
164 stack_size += 1 * MB;
165
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700166 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
167 if (stack_size < PTHREAD_STACK_MIN) {
168 stack_size = PTHREAD_STACK_MIN;
169 }
170
171 // It's likely that callers are trying to ensure they have at least a certain amount of
172 // stack space, so we should add our reserved space on top of what they requested, rather
173 // than implicitly take it away from them.
174 stack_size += Thread::kStackOverflowReservedBytes;
175
176 // Some systems require the stack size to be a multiple of the system page size, so round up.
177 stack_size = RoundUp(stack_size, kPageSize);
178
179 return stack_size;
180}
181
Elliott Hughesd8af1592012-04-16 20:40:15 -0700182static void SigAltStack(stack_t* new_stack, stack_t* old_stack) {
183 if (sigaltstack(new_stack, old_stack) == -1) {
184 PLOG(FATAL) << "sigaltstack failed";
185 }
186}
187
188static void SetUpAlternateSignalStack() {
189 // Create and set an alternate signal stack.
190 stack_t ss;
191 ss.ss_sp = new uint8_t[SIGSTKSZ];
192 ss.ss_size = SIGSTKSZ;
193 ss.ss_flags = 0;
194 CHECK(ss.ss_sp != NULL);
195 SigAltStack(&ss, NULL);
196
197 // Double-check that it worked.
198 ss.ss_sp = NULL;
199 SigAltStack(NULL, &ss);
200 VLOG(threads) << "Alternate signal stack is " << PrettySize(ss.ss_size) << " at " << ss.ss_sp;
201}
202
203static void TearDownAlternateSignalStack() {
204 // Get the pointer so we can free the memory.
205 stack_t ss;
206 SigAltStack(NULL, &ss);
207 uint8_t* allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
208
209 // Tell the kernel to stop using it.
210 ss.ss_sp = NULL;
211 ss.ss_flags = SS_DISABLE;
Elliott Hughes4c5231d2012-04-18 16:54:31 -0700212 ss.ss_size = SIGSTKSZ; // Avoid ENOMEM failure with Mac OS' buggy libc.
Elliott Hughesd8af1592012-04-16 20:40:15 -0700213 SigAltStack(&ss, NULL);
214
215 // Free it.
216 delete[] allocated_signal_stack;
217}
218
Ian Rogers52673ff2012-06-27 23:25:34 -0700219void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool daemon) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700220 CHECK(java_peer != NULL);
221
Ian Rogers52673ff2012-06-27 23:25:34 -0700222 Thread* native_thread = new Thread(daemon);
Elliott Hughes47179f72011-10-27 16:44:39 -0700223 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 ScopedObjectAccess soa(env);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700225 // Use global JNI ref to hold peer live whilst child thread starts.
226 native_thread->peer_ = env->NewGlobalRef(java_peer);
Ian Rogers365c1022012-06-22 15:05:28 -0700227 stack_size = FixStackSize(stack_size);
228
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 // Thread.start is synchronized, so we know that vmData is 0, and know that we're not racing to
230 // assign it.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700231 Object* peer = soa.Decode<Object*>(native_thread->peer_);
232 CHECK(peer != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700233 SetVmData(soa, peer, native_thread);
Elliott Hughes47179f72011-10-27 16:44:39 -0700234 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700235
236 pthread_t new_pthread;
237 pthread_attr_t attr;
238 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
239 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
240 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
241 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, native_thread);
242 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
243
244 if (UNLIKELY(pthread_create_result != 0)) {
245 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700246 {
247 ScopedObjectAccess soa(env);
248 Object* peer = soa.Decode<Object*>(java_peer);
249 SetVmData(soa, peer, 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700250
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700251 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
252 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
253 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
254 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700255 // If we failed, manually delete the global reference since Thread::Init will not have been run.
256 env->DeleteGlobalRef(native_thread->peer_);
257 native_thread->peer_ = NULL;
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700258 delete native_thread;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700259 return;
260 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700261}
262
Elliott Hughes462c9442012-03-23 18:47:50 -0700263void Thread::Init() {
264 // This function does all the initialization that must be run by the native thread it applies to.
265 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
266 // we can handshake with the corresponding native thread when it's ready.) Check this native
267 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700268 CHECK(Thread::Current() == NULL);
269
Elliott Hughesd8af1592012-04-16 20:40:15 -0700270 SetUpAlternateSignalStack();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700271 InitCpu();
272 InitFunctionPointers();
Shih-wei Liao21d28f52012-06-12 05:55:00 -0700273#ifdef ART_USE_GREENLAND_COMPILER
274 InitRuntimeEntryPoints(&runtime_entry_points_);
275#endif
Ian Rogers5d76c432011-10-31 21:42:49 -0700276 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700277 InitTid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700278
Elliott Hughes462c9442012-03-23 18:47:50 -0700279 Runtime* runtime = Runtime::Current();
280 CHECK(runtime != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700281 if (runtime->IsShuttingDown()) {
282 UNIMPLEMENTED(WARNING) << "Thread attaching whilst runtime is shutting down";
283 }
Elliott Hughes462c9442012-03-23 18:47:50 -0700284 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Elliott Hughes0d39c122012-06-06 16:41:17 -0700285 pthread_self_ = pthread_self();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700286
Elliott Hughes93e74e82011-09-13 11:07:03 -0700287 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700288
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700289 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700290
Elliott Hughes93e74e82011-09-13 11:07:03 -0700291 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700292
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700293 runtime->GetThreadList()->Register(this);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700294}
295
Ian Rogers365c1022012-06-22 15:05:28 -0700296Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group) {
Ian Rogers52673ff2012-06-27 23:25:34 -0700297 Thread* self = new Thread(as_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700298 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700299
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700300 CHECK_NE(self->GetState(), kRunnable);
301 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700302
Elliott Hughescac6cc72011-11-03 20:31:21 -0700303 // If we're the main thread, ClassLinker won't be created until after we're attached,
304 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800305 // In the compiler, all threads need this hack, because no-one's going to be getting
306 // a native peer!
307 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700308 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800309 } else {
310 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700311 if (thread_name != NULL) {
312 self->name_->assign(thread_name);
313 ::art::SetThreadName(thread_name);
314 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700315 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700316
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700317 return self;
318}
319
Ian Rogers365c1022012-06-22 15:05:28 -0700320void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
321 Runtime* runtime = Runtime::Current();
322 CHECK(runtime->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700323 JNIEnv* env = jni_env_;
324
Elliott Hughes462c9442012-03-23 18:47:50 -0700325 if (thread_group == NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -0700326 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700327 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700328 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700329 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700330 jboolean thread_is_daemon = as_daemon;
331
Elliott Hugheseac76672012-05-24 21:56:51 -0700332 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700333 if (peer.get() == NULL) {
334 CHECK(IsExceptionPending());
335 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700336 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700337 peer_ = env->NewGlobalRef(peer.get());
Elliott Hugheseac76672012-05-24 21:56:51 -0700338 env->CallNonvirtualVoidMethod(peer.get(),
339 WellKnownClasses::java_lang_Thread,
340 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700341 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700343
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700344 ScopedObjectAccess soa(this);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700345 Object* native_peer = soa.Decode<Object*>(peer.get());
346 SetVmData(soa, native_peer, Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700347 SirtRef<String> peer_thread_name(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700348 if (peer_thread_name.get() == NULL) {
349 // The Thread constructor should have set the Thread.name to a
350 // non-null value. However, because we can run without code
351 // available (in the compiler, in tests), we manually assign the
352 // fields the constructor should have set.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700353 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
354 SetBoolean(native_peer, thread_is_daemon);
355 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
356 SetObject(native_peer, soa.Decode<Object*>(thread_group));
357 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
358 SetObject(native_peer, soa.Decode<Object*>(thread_name.get()));
359 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
360 SetInt(native_peer, thread_priority);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700361 peer_thread_name.reset(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700362 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700363 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Brian Carlstrom00fae582011-10-28 01:16:28 -0700364 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800365 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700366 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700367}
368
Elliott Hughes899e7892012-01-24 14:57:32 -0800369void Thread::SetThreadName(const char* name) {
370 name_->assign(name);
371 ::art::SetThreadName(name);
372 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
373}
374
Elliott Hughesbe759c62011-09-08 19:38:21 -0700375void Thread::InitStackHwm() {
Elliott Hughese1884192012-04-23 12:38:15 -0700376 void* stack_base;
377 size_t stack_size;
378 GetThreadStack(stack_base, stack_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700379
380 // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
Elliott Hughese1884192012-04-23 12:38:15 -0700381 VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
382
383 stack_begin_ = reinterpret_cast<byte*>(stack_base);
384 stack_size_ = stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700385
Ian Rogers932746a2011-09-22 18:57:50 -0700386 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800387 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700388 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700389
Elliott Hughese1884192012-04-23 12:38:15 -0700390 // TODO: move this into the Linux GetThreadStack implementation.
391#if !defined(__APPLE__)
Elliott Hughes36ecb782012-04-17 16:55:45 -0700392 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
393 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
394 // will be broken because we'll die long before we get close to 2GB.
395 if (thin_lock_id_ == 1) {
396 rlimit stack_limit;
397 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
398 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
399 }
400 if (stack_limit.rlim_cur == RLIM_INFINITY) {
401 // Find the default stack size for new threads...
402 pthread_attr_t default_attributes;
403 size_t default_stack_size;
404 CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
405 CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
406 "default stack size query");
407 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
408
409 // ...and use that as our limit.
410 size_t old_stack_size = stack_size_;
411 stack_size_ = default_stack_size;
412 stack_begin_ += (old_stack_size - stack_size_);
Elliott Hughesfaf4ba02012-05-02 16:12:19 -0700413 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
414 << " to " << PrettySize(stack_size_)
415 << " with base " << reinterpret_cast<void*>(stack_begin_);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700416 }
417 }
Elliott Hughese1884192012-04-23 12:38:15 -0700418#endif
Elliott Hughes36ecb782012-04-17 16:55:45 -0700419
Ian Rogers932746a2011-09-22 18:57:50 -0700420 // Set stack_end_ to the bottom of the stack saving space of stack overflows
421 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700422
423 // Sanity check.
424 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700425 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700426}
427
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428void Thread::ShortDump(std::ostream& os) const {
429 os << "Thread[";
430 if (GetThinLockId() != 0) {
431 // If we're in kStarting, we won't have a thin lock id or tid yet.
432 os << GetThinLockId()
433 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700434 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700435 os << GetState()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700436 << ",Thread*=" << this
437 << ",peer=" << peer_
438 << ",\"" << *name_ << "\""
439 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700440}
441
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442void Thread::Dump(std::ostream& os) const {
443 DumpState(os);
444 DumpStack(os);
445}
446
447String* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
448 Field* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700449 Object* native_peer = soa.Decode<Object*>(peer_);
450 return (peer_ != NULL) ? reinterpret_cast<String*>(f->GetObject(native_peer)) : NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700451}
452
Elliott Hughesffb465f2012-03-01 18:46:05 -0800453void Thread::GetThreadName(std::string& name) const {
454 name.assign(*name_);
455}
456
Ian Rogers474b6da2012-09-25 00:20:38 -0700457void Thread::AtomicSetFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700458 android_atomic_or(flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700459}
460
461void Thread::AtomicClearFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700462 android_atomic_and(-1 ^ flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700463}
464
465ThreadState Thread::SetState(ThreadState new_state) {
466 // Cannot use this code to change into Runnable as changing to Runnable should fail if
467 // old_state_and_flags.suspend_request is true.
468 DCHECK_NE(new_state, kRunnable);
469 DCHECK_EQ(this, Thread::Current());
Ian Rogers30e173f2012-09-26 14:35:03 -0700470 union StateAndFlags old_state_and_flags = state_and_flags_;
471 state_and_flags_.as_struct.state = new_state;
472 return static_cast<ThreadState>(old_state_and_flags.as_struct.state);
Ian Rogers474b6da2012-09-25 00:20:38 -0700473}
474
Ian Rogers01ae5802012-09-28 16:14:01 -0700475// Attempt to rectify locks so that we dump thread list with required locks before exiting.
476static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
477 Locks::thread_suspend_count_lock_->Unlock(self);
478 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
479 Locks::mutator_lock_->SharedTryLock(self);
480 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
481 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
482 }
483 }
484 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
485 Locks::thread_list_lock_->TryLock(self);
486 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
487 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
488 }
489 }
490 std::ostringstream ss;
491 Runtime::Current()->GetThreadList()->DumpLocked(ss);
492 LOG(FATAL) << *thread << " suspend count already zero.\n" << ss.str();
493}
494
495void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
497 << delta << " " << debug_suspend_count_ << " " << this;
498 DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
Ian Rogers01ae5802012-09-28 16:14:01 -0700499 Locks::thread_suspend_count_lock_->AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500
Ian Rogers01ae5802012-09-28 16:14:01 -0700501 if (UNLIKELY(delta < 0 && suspend_count_ <= 0)) {
502 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700503 return;
504 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700505
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506 suspend_count_ += delta;
507 if (for_debugger) {
508 debug_suspend_count_ += delta;
509 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700510
Ian Rogers474b6da2012-09-25 00:20:38 -0700511 if (suspend_count_ == 0) {
512 AtomicClearFlag(kSuspendRequest);
513 } else {
514 AtomicSetFlag(kSuspendRequest);
515 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516}
517
518void Thread::FullSuspendCheck() {
519 VLOG(threads) << this << " self-suspending";
520 // Make thread appear suspended to other threads, release mutator_lock_.
521 TransitionFromRunnableToSuspended(kSuspended);
522 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
523 TransitionFromSuspendedToRunnable();
524 VLOG(threads) << this << " self-reviving";
525}
526
527void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
528 AssertThreadSuspensionIsAllowable();
Ian Rogers474b6da2012-09-25 00:20:38 -0700529 DCHECK_NE(new_state, kRunnable);
530 DCHECK_EQ(this, Thread::Current());
Ian Rogersc747cff2012-08-31 18:20:08 -0700531 // Change to non-runnable state, thereby appearing suspended to the system.
Ian Rogers474b6da2012-09-25 00:20:38 -0700532 DCHECK_EQ(GetState(), kRunnable);
Ian Rogers30e173f2012-09-26 14:35:03 -0700533 state_and_flags_.as_struct.state = new_state;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700534 // Release share on mutator_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -0700535 Locks::mutator_lock_->SharedUnlock(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700536}
537
538ThreadState Thread::TransitionFromSuspendedToRunnable() {
539 bool done = false;
Ian Rogers01ae5802012-09-28 16:14:01 -0700540 union StateAndFlags old_state_and_flags = state_and_flags_;
541 int16_t old_state = old_state_and_flags.as_struct.state;
542 DCHECK_NE(static_cast<ThreadState>(old_state), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543 do {
Ian Rogers81d425b2012-09-27 16:03:43 -0700544 Locks::mutator_lock_->AssertNotHeld(this); // Otherwise we starve GC..
Ian Rogers01ae5802012-09-28 16:14:01 -0700545 old_state_and_flags = state_and_flags_;
546 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
547 if ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700548 // Wait while our suspend count is non-zero.
Ian Rogers81d425b2012-09-27 16:03:43 -0700549 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
Ian Rogers01ae5802012-09-28 16:14:01 -0700550 old_state_and_flags = state_and_flags_;
551 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
552 while ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700553 // Re-check when Thread::resume_cond_ is notified.
Ian Rogers81d425b2012-09-27 16:03:43 -0700554 Thread::resume_cond_->Wait(this, *Locks::thread_suspend_count_lock_);
Ian Rogers01ae5802012-09-28 16:14:01 -0700555 old_state_and_flags = state_and_flags_;
556 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700557 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700558 DCHECK_EQ(GetSuspendCount(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700559 }
560 // Re-acquire shared mutator_lock_ access.
Ian Rogers81d425b2012-09-27 16:03:43 -0700561 Locks::mutator_lock_->SharedLock(this);
Ian Rogers474b6da2012-09-25 00:20:38 -0700562 // Atomically change from suspended to runnable if no suspend request pending.
Ian Rogers01ae5802012-09-28 16:14:01 -0700563 old_state_and_flags = state_and_flags_;
564 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
565 if ((old_state_and_flags.as_struct.flags & kSuspendRequest) == 0) {
566 union StateAndFlags new_state_and_flags = old_state_and_flags;
567 new_state_and_flags.as_struct.state = kRunnable;
568 done = android_atomic_cmpxchg(old_state_and_flags.as_int, new_state_and_flags.as_int,
Ian Rogers81d425b2012-09-27 16:03:43 -0700569 &state_and_flags_.as_int)
Ian Rogers474b6da2012-09-25 00:20:38 -0700570 == 0;
571 }
572 if (!done) {
573 // Failed to transition to Runnable. Release shared mutator_lock_ access and try again.
Ian Rogers81d425b2012-09-27 16:03:43 -0700574 Locks::mutator_lock_->SharedUnlock(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700575 }
576 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700577 return static_cast<ThreadState>(old_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700578}
579
580Thread* Thread::SuspendForDebugger(jobject peer, bool request_suspension, bool* timeout) {
581 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
582 useconds_t total_delay_us = 0;
583 useconds_t delay_us = 0;
584 bool did_suspend_request = false;
585 *timeout = false;
586 while (true) {
587 Thread* thread;
588 {
589 ScopedObjectAccess soa(Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700590 MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700591 thread = Thread::FromManagedThread(soa, peer);
592 if (thread == NULL) {
593 LOG(WARNING) << "No such thread for suspend: " << peer;
594 return NULL;
595 }
596 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700597 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700598 if (request_suspension) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700599 thread->ModifySuspendCount(soa.Self(), +1, true /* for_debugger */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600 request_suspension = false;
601 did_suspend_request = true;
602 }
603 // IsSuspended on the current thread will fail as the current thread is changed into
604 // Runnable above. As the suspend count is now raised if this is the current thread
605 // it will self suspend on transition to Runnable, making it hard to work with. Its simpler
606 // to just explicitly handle the current thread in the callers to this code.
607 CHECK_NE(thread, soa.Self()) << "Attempt to suspend for debugger the current thread";
608 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
609 // count, or else we've waited and it has self suspended) or is the current thread, we're
610 // done.
611 if (thread->IsSuspended()) {
612 return thread;
613 }
614 if (total_delay_us >= kTimeoutUs) {
615 LOG(ERROR) << "Thread suspension timed out: " << peer;
616 if (did_suspend_request) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700617 thread->ModifySuspendCount(soa.Self(), -1, true /* for_debugger */);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700618 }
619 *timeout = true;
620 return NULL;
621 }
622 }
623 // Release locks and come out of runnable state.
624 }
625 for (int i = kMaxMutexLevel; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700626 BaseMutex* held_mutex = Thread::Current()->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700627 if (held_mutex != NULL) {
628 LOG(FATAL) << "Holding " << held_mutex->GetName()
629 << " while sleeping for thread suspension";
630 }
631 }
632 {
633 useconds_t new_delay_us = delay_us * 2;
634 CHECK_GE(new_delay_us, delay_us);
635 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
636 delay_us = new_delay_us;
637 }
638 }
639 if (delay_us == 0) {
640 sched_yield();
641 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
642 delay_us = 500;
643 } else {
644 usleep(delay_us);
645 total_delay_us += delay_us;
646 }
647 }
648}
649
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700650void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700651 std::string group_name;
652 int priority;
653 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700654 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700655
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700656 if (thread != NULL && thread->peer_ != NULL) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700657 ScopedObjectAccess soa(self);
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700658 Object* native_peer = soa.Decode<Object*>(thread->peer_);
659 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(native_peer);
660 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(native_peer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700661
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 Object* thread_group = thread->GetThreadGroup(soa);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700663 if (thread_group != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 Field* group_name_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700665 String* group_name_string = reinterpret_cast<String*>(group_name_field->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700666 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
667 }
668 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700669 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700670 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700671
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700672 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700673 if (scheduler_group_name.empty()) {
674 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700675 }
676
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700677 if (thread != NULL) {
678 os << '"' << *thread->name_ << '"';
679 if (is_daemon) {
680 os << " daemon";
681 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700682 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700683 os << " prio=" << priority
684 << " tid=" << thread->GetThinLockId()
685 << " " << thread->GetState() << "\n";
686 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700687 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700688 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700689 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700690 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700691
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700692 if (thread != NULL) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700693 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700694 os << " | group=\"" << group_name << "\""
695 << " sCount=" << thread->suspend_count_
696 << " dsCount=" << thread->debug_suspend_count_
697 << " obj=" << reinterpret_cast<void*>(thread->peer_)
698 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
699 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700700
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700701 os << " | sysTid=" << tid
702 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700703 << " cgrp=" << scheduler_group_name;
704 if (thread != NULL) {
705 int policy;
706 sched_param sp;
707 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
708 os << " sched=" << policy << "/" << sp.sched_priority
709 << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
710 }
711 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700712
713 // Grab the scheduler stats for this thread.
714 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700715 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700716 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
717 } else {
718 scheduler_stats = "0 0 0";
719 }
720
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700721 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700722 int utime = 0;
723 int stime = 0;
724 int task_cpu = 0;
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700725 GetTaskStats(tid, native_thread_state, utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700726
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700727 os << " | state=" << native_thread_state
728 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700729 << " utm=" << utime
730 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700731 << " core=" << task_cpu
732 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
733 if (thread != NULL) {
734 os << " | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
735 << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
736 }
737}
738
739void Thread::DumpState(std::ostream& os) const {
740 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700741}
742
Ian Rogers0399dde2012-06-06 17:09:28 -0700743struct StackDumpVisitor : public StackVisitor {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700744 StackDumpVisitor(std::ostream& os, const Thread* thread, Context* context, bool can_allocate)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700745 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700746 : StackVisitor(thread->GetManagedStack(), thread->GetTraceStack(), context),
747 os(os), thread(thread), can_allocate(can_allocate),
748 last_method(NULL), last_line_number(0), repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700749 }
750
Ian Rogersbdb03912011-09-14 00:55:44 -0700751 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700752 if (frame_count == 0) {
753 os << " (no managed stack frames)\n";
754 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700755 }
756
Ian Rogersb726dcb2012-09-05 08:57:23 -0700757 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700758 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700759 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700760 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700761 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700762 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700763 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700764 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800765 const DexCache* dex_cache = c->GetDexCache();
766 int line_number = -1;
767 if (dex_cache != NULL) { // be tolerant of bad input
768 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
Ian Rogers0399dde2012-06-06 17:09:28 -0700769 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Ian Rogersb861dc02011-11-14 17:00:05 -0800770 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700771 if (line_number == last_line_number && last_method == m) {
772 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700773 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700774 if (repetition_count >= kMaxRepetition) {
775 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
776 }
777 repetition_count = 0;
778 last_line_number = line_number;
779 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700780 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700781 if (repetition_count < kMaxRepetition) {
782 os << " at " << PrettyMethod(m, false);
783 if (m->IsNative()) {
784 os << "(Native method)";
785 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800786 mh.ChangeMethod(m);
787 const char* source_file(mh.GetDeclaringClassSourceFile());
788 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700789 << ":" << line_number << ")";
790 }
791 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700792 if (frame_count == 0) {
793 Monitor::DescribeWait(os, thread);
794 }
795 if (can_allocate) {
796 Monitor::DescribeLocks(os, this);
797 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700798 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700799
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700800 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700801 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700802 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700803 std::ostream& os;
804 const Thread* thread;
805 bool can_allocate;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800806 MethodHelper mh;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700807 AbstractMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700808 int last_line_number;
809 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700810 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700811};
812
Elliott Hughesd92bec42011-09-02 17:04:36 -0700813void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800814 // If we're currently in native code, dump that stack before dumping the managed stack.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700815 if (GetState() == kNative) {
Elliott Hughes46e251b2012-05-22 15:10:45 -0700816 DumpKernelStack(os, GetTid(), " kernel: ", false);
817 DumpNativeStack(os, GetTid(), " native: ", false);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800818 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700819 UniquePtr<Context> context(Context::Create());
820 StackDumpVisitor dumper(os, this, context.get(), !throwing_OutOfMemoryError_);
Ian Rogers0399dde2012-06-06 17:09:28 -0700821 dumper.WalkStack();
Elliott Hughese27955c2011-08-26 15:21:24 -0700822}
823
Elliott Hughesbe759c62011-09-08 19:38:21 -0700824void Thread::ThreadExitCallback(void* arg) {
825 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700826 if (self->thread_exit_check_count_ == 0) {
827 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
828 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
829 self->thread_exit_check_count_ = 1;
830 } else {
831 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
832 }
Carl Shapirob5573532011-07-12 18:22:59 -0700833}
834
Elliott Hughesbe759c62011-09-08 19:38:21 -0700835void Thread::Startup() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700836 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700837 MutexLock mu(*Locks::thread_suspend_count_lock_); // Keep GCC happy.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 resume_cond_ = new ConditionVariable("Thread resumption condition variable");
839 }
840
Carl Shapirob5573532011-07-12 18:22:59 -0700841 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700842 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700843
844 // Double-check the TLS slot allocation.
845 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800846 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700847 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700848}
Carl Shapirob5573532011-07-12 18:22:59 -0700849
Elliott Hughes038a8062011-09-18 14:12:41 -0700850void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -0700851 Runtime* runtime = Runtime::Current();
852 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700853
Elliott Hughes01158d72011-09-19 19:47:10 -0700854 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700855 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700856 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500857
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700858 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700859}
860
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700861void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700862 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700863}
864
Ian Rogers52673ff2012-06-27 23:25:34 -0700865Thread::Thread(bool daemon)
Ian Rogers0399dde2012-06-06 17:09:28 -0700866 : suspend_count_(0),
867 card_table_(NULL),
868 exception_(NULL),
869 stack_end_(NULL),
870 managed_stack_(),
871 jni_env_(NULL),
872 self_(NULL),
Elliott Hughes47179f72011-10-27 16:44:39 -0700873 peer_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700874 stack_begin_(NULL),
875 stack_size_(0),
876 thin_lock_id_(0),
877 tid_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700878 wait_mutex_(new Mutex("a thread wait mutex")),
879 wait_cond_(new ConditionVariable("a thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700880 wait_monitor_(NULL),
881 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700882 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700883 monitor_enter_object_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700884 top_sirt_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700885 runtime_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700886 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700887 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700888 throwing_OutOfMemoryError_(false),
Ian Rogers0399dde2012-06-06 17:09:28 -0700889 debug_suspend_count_(0),
jeffhaoe343b762011-12-05 16:36:44 -0800890 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800891 trace_stack_(new std::vector<TraceStackFrame>),
Ian Rogers0399dde2012-06-06 17:09:28 -0700892 name_(new std::string(kThreadNameDuringStartup)),
Ian Rogers52673ff2012-06-27 23:25:34 -0700893 daemon_(daemon),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700894 pthread_self_(0),
Ian Rogers52673ff2012-06-27 23:25:34 -0700895 no_thread_suspension_(0),
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700896 last_no_thread_suspension_cause_(NULL),
897 thread_exit_check_count_(0) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700898 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Ian Rogers30e173f2012-09-26 14:35:03 -0700899 state_and_flags_.as_struct.flags = 0;
900 state_and_flags_.as_struct.state = kNative;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800901 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700902}
903
Elliott Hughes7dc51662012-05-16 14:48:43 -0700904bool Thread::IsStillStarting() const {
905 // You might think you can check whether the state is kStarting, but for much of thread startup,
906 // the thread might also be in kVmWait.
907 // You might think you can check whether the peer is NULL, but the peer is actually created and
908 // assigned fairly early on, and needs to be.
909 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
910 // this thread _ever_ entered kRunnable".
911 return (*name_ == kThreadNameDuringStartup);
912}
913
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700914void Thread::AssertNoPendingException() const {
915 if (UNLIKELY(IsExceptionPending())) {
916 ScopedObjectAccess soa(Thread::Current());
917 Throwable* exception = GetException();
918 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
919 }
920}
921
922static void MonitorExitVisitor(const Object* object, void* arg) NO_THREAD_SAFETY_ANALYSIS {
923 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700924 Object* entered_monitor = const_cast<Object*>(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700925 if (self->HoldsLock(entered_monitor)) {
926 LOG(WARNING) << "Calling MonitorExit on object "
927 << object << " (" << PrettyTypeOf(object) << ")"
928 << " left locked by native thread "
929 << *Thread::Current() << " which is detaching";
930 entered_monitor->MonitorExit(self);
931 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700932}
933
Elliott Hughesc0f09332012-03-26 13:27:06 -0700934void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700935 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700936 if (jni_env_ != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700937 jni_env_->monitors.VisitRoots(MonitorExitVisitor, Thread::Current());
Elliott Hughes93e74e82011-09-13 11:07:03 -0700938 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700939
Elliott Hughes93e74e82011-09-13 11:07:03 -0700940 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700941 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700942
Elliott Hughes534da072012-03-27 15:17:42 -0700943 // We may need to call user-supplied managed code.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700944 ScopedObjectAccess soa(this);
Elliott Hughes534da072012-03-27 15:17:42 -0700945
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700946 HandleUncaughtExceptions(soa);
947 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -0700948
Elliott Hughes29f27422011-09-18 16:02:18 -0700949 // this.vmData = 0;
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700950 SetVmData(soa, soa.Decode<Object*>(peer_), NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700951
Elliott Hughesc0f09332012-03-26 13:27:06 -0700952 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700953
Elliott Hughes29f27422011-09-18 16:02:18 -0700954 // Thread.join() is implemented as an Object.wait() on the Thread.lock
955 // object. Signal anyone who is waiting.
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700956 Object* lock = soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->
957 GetObject(soa.Decode<Object*>(peer_));
Elliott Hughes038a8062011-09-18 14:12:41 -0700958 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700959 if (lock != NULL) {
960 lock->MonitorEnter(self);
961 lock->NotifyAll();
962 lock->MonitorExit(self);
963 }
964 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700965}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700966
Elliott Hughesc0f09332012-03-26 13:27:06 -0700967Thread::~Thread() {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700968 if (jni_env_ != NULL && peer_ != NULL) {
969 // If pthread_create fails we don't have a jni env here.
970 jni_env_->DeleteGlobalRef(peer_);
971 }
972 peer_ = NULL;
973
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700974 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700975 jni_env_ = NULL;
976
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700977 CHECK_NE(GetState(), kRunnable);
978 // We may be deleting a still born thread.
979 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700980
981 delete wait_cond_;
982 delete wait_mutex_;
983
Ian Rogers776ac1f2012-04-13 23:36:36 -0700984#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -0700985 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -0700986#endif
Elliott Hughes475fc232011-10-25 15:00:35 -0700987
988 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800989 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800990 delete name_;
Elliott Hughesd8af1592012-04-16 20:40:15 -0700991
992 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700993}
994
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700995void Thread::HandleUncaughtExceptions(const ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700996 if (!IsExceptionPending()) {
997 return;
998 }
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700999 // Get and clear the exception.
1000 Object* exception = GetException();
1001 ClearException();
1002
1003 // If the thread has its own handler, use that.
Ian Rogers365c1022012-06-22 15:05:28 -07001004 Object* handler =
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001005 soa.DecodeField(WellKnownClasses::java_lang_Thread_uncaughtHandler)->
1006 GetObject(soa.Decode<Object*>(peer_));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001007 if (handler == NULL) {
1008 // Otherwise use the thread group's default handler.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001009 handler = GetThreadGroup(soa);
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001010 }
1011
1012 // Call the handler.
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001013 jmethodID mid = WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001014 AbstractMethod* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Elliott Hughes77405792012-03-15 15:22:12 -07001015 JValue args[2];
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001016 args[0].SetL(soa.Decode<Object*>(peer_));
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001017 args[1].SetL(exception);
Elliott Hughes77405792012-03-15 15:22:12 -07001018 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001019
1020 // If the handler threw, clear that exception too.
1021 ClearException();
1022}
1023
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001024Object* Thread::GetThreadGroup(const ScopedObjectAccessUnchecked& soa) const {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001025 return soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
1026 GetObject(soa.Decode<Object*>(peer_));
Elliott Hughesa2155262011-11-16 16:26:58 -08001027}
1028
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001029void Thread::RemoveFromThreadGroup(const ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001030 // this.group.removeThread(this);
1031 // group can be null if we're in the compiler or a test.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001032 Object* group = GetThreadGroup(soa);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001033 if (group != NULL) {
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001034 jmethodID mid = WellKnownClasses::java_lang_ThreadGroup_removeThread;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001035 AbstractMethod* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(soa.DecodeMethod(mid));
Elliott Hughes77405792012-03-15 15:22:12 -07001036 JValue args[1];
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001037 args[0].SetL(soa.Decode<Object*>(peer_));
Elliott Hughes77405792012-03-15 15:22:12 -07001038 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001039 }
1040}
1041
Ian Rogers408f79a2011-08-23 18:22:33 -07001042size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001043 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001044 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001045 count += cur->NumberOfReferences();
1046 }
1047 return count;
1048}
1049
Ian Rogers408f79a2011-08-23 18:22:33 -07001050bool Thread::SirtContains(jobject obj) {
1051 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001052 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1053 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001054 return true;
1055 }
1056 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001057 // JNI code invoked from portable code uses shadow frames rather than the SIRT.
1058 return managed_stack_.ShadowFramesContain(sirt_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001059}
1060
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001061void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001062 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001063 size_t num_refs = cur->NumberOfReferences();
1064 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001065 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001066 if (object != NULL) {
1067 visitor(object, arg);
1068 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001069 }
1070 }
1071}
1072
Ian Rogers408f79a2011-08-23 18:22:33 -07001073Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001074 Locks::mutator_lock_->AssertSharedHeld(this);
Ian Rogers408f79a2011-08-23 18:22:33 -07001075 if (obj == NULL) {
1076 return NULL;
1077 }
1078 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1079 IndirectRefKind kind = GetIndirectRefKind(ref);
1080 Object* result;
1081 switch (kind) {
1082 case kLocal:
1083 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001084 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001085 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001086 break;
1087 }
1088 case kGlobal:
1089 {
1090 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1091 IndirectReferenceTable& globals = vm->globals;
Ian Rogers81d425b2012-09-27 16:03:43 -07001092 MutexLock mu(this, vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001093 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001094 break;
1095 }
1096 case kWeakGlobal:
1097 {
1098 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1099 IndirectReferenceTable& weak_globals = vm->weak_globals;
Ian Rogers81d425b2012-09-27 16:03:43 -07001100 MutexLock mu(this, vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001101 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001102 if (result == kClearedJniWeakGlobal) {
1103 // This is a special case where it's okay to return NULL.
1104 return NULL;
1105 }
1106 break;
1107 }
1108 case kSirtOrInvalid:
1109 default:
1110 // TODO: make stack indirect reference table lookup more efficient
1111 // Check if this is a local reference in the SIRT
Ian Rogers0399dde2012-06-06 17:09:28 -07001112 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001113 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001114 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001115 // Assume an invalid local reference is actually a direct pointer.
1116 result = reinterpret_cast<Object*>(obj);
1117 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001118 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001119 }
1120 }
1121
1122 if (result == NULL) {
Elliott Hughes3f6635a2012-06-19 13:37:49 -07001123 JniAbortF(NULL, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
Elliott Hughesa2501992011-08-26 19:39:54 -07001124 } else {
1125 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001126 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001127 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001128 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001129 return result;
1130}
1131
Ian Rogers81d425b2012-09-27 16:03:43 -07001132// Implements java.lang.Thread.interrupted.
1133bool Thread::Interrupted() {
1134 MutexLock mu(*wait_mutex_);
1135 bool interrupted = interrupted_;
1136 interrupted_ = false;
1137 return interrupted;
1138}
1139
1140// Implements java.lang.Thread.isInterrupted.
1141bool Thread::IsInterrupted() {
1142 MutexLock mu(*wait_mutex_);
1143 return interrupted_;
1144}
1145
1146void Thread::Interrupt() {
1147 MutexLock mu(*wait_mutex_);
1148 if (interrupted_) {
1149 return;
1150 }
1151 interrupted_ = true;
1152 NotifyLocked();
1153}
1154
1155void Thread::Notify() {
1156 MutexLock mu(*wait_mutex_);
1157 NotifyLocked();
1158}
1159
1160void Thread::NotifyLocked() {
1161 if (wait_monitor_ != NULL) {
1162 wait_cond_->Signal();
1163 }
1164}
1165
Ian Rogers0399dde2012-06-06 17:09:28 -07001166class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001167 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001168 CountStackDepthVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001169 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001170 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001171 : StackVisitor(stack, trace_stack, NULL),
1172 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001173
Ian Rogersb726dcb2012-09-05 08:57:23 -07001174 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001175 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001176 // Note we also skip the frame if it doesn't have a method (namely the callee
1177 // save frame)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001178 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001179 if (skipping_ && !m->IsRuntimeMethod() &&
1180 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001181 skipping_ = false;
1182 }
1183 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001184 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001185 ++depth_;
1186 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001187 } else {
1188 ++skip_depth_;
1189 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001190 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001191 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001192
1193 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001194 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001195 }
1196
Elliott Hughes29f27422011-09-18 16:02:18 -07001197 int GetSkipDepth() const {
1198 return skip_depth_;
1199 }
1200
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001201 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001202 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001203 uint32_t skip_depth_;
1204 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001205};
1206
Ian Rogers0399dde2012-06-06 17:09:28 -07001207class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001208 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001209 explicit BuildInternalStackTraceVisitor(const ManagedStack* stack,
1210 const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001211 int skip_depth)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001212 : StackVisitor(stack, trace_stack, NULL),
1213 skip_depth_(skip_depth), count_(0), dex_pc_trace_(NULL), method_trace_(NULL) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001214
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001215 bool Init(int depth, const ScopedObjectAccess& soa)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001216 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001217 // Allocate method trace with an extra slot that will hold the PC trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001218 SirtRef<ObjectArray<Object> >
1219 method_trace(Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1));
1220 if (method_trace.get() == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001221 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001222 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001223 IntArray* dex_pc_trace = IntArray::Alloc(depth);
1224 if (dex_pc_trace == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001225 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001226 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001227 // Save PC trace in last element of method trace, also places it into the
1228 // object graph.
Ian Rogers0399dde2012-06-06 17:09:28 -07001229 method_trace->Set(depth, dex_pc_trace);
1230 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001231 const char* last_no_suspend_cause =
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001232 soa.Self()->StartAssertNoThreadSuspension("Building internal stack trace");
Ian Rogers52673ff2012-06-27 23:25:34 -07001233 CHECK(last_no_suspend_cause == NULL) << last_no_suspend_cause;
Ian Rogers0399dde2012-06-06 17:09:28 -07001234 method_trace_ = method_trace.get();
1235 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001236 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001237 }
1238
Ian Rogers0399dde2012-06-06 17:09:28 -07001239 virtual ~BuildInternalStackTraceVisitor() {
Ian Rogers52673ff2012-06-27 23:25:34 -07001240 if (method_trace_ != NULL) {
1241 Thread::Current()->EndAssertNoThreadSuspension(NULL);
1242 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001243 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001244
Ian Rogersb726dcb2012-09-05 08:57:23 -07001245 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001246 if (method_trace_ == NULL || dex_pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001247 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001248 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001249 if (skip_depth_ > 0) {
1250 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001251 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001252 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001253 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001254 if (m->IsRuntimeMethod()) {
1255 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001256 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001257 method_trace_->Set(count_, m);
1258 dex_pc_trace_->Set(count_, GetDexPc());
Ian Rogersaaa20802011-09-11 21:47:37 -07001259 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001260 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001261 }
1262
Ian Rogers0399dde2012-06-06 17:09:28 -07001263 ObjectArray<Object>* GetInternalStackTrace() const {
1264 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001265 }
1266
1267 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001268 // How many more frames to skip.
1269 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001270 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001271 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001272 // Array of dex PC values.
1273 IntArray* dex_pc_trace_;
1274 // 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 -07001275 ObjectArray<Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001276};
1277
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001278void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1279 sirt->SetLink(top_sirt_);
1280 top_sirt_ = sirt;
1281}
1282
1283StackIndirectReferenceTable* Thread::PopSirt() {
1284 CHECK(top_sirt_ != NULL);
1285 StackIndirectReferenceTable* sirt = top_sirt_;
1286 top_sirt_ = top_sirt_->GetLink();
1287 return sirt;
1288}
1289
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001290jobject Thread::CreateInternalStackTrace(const ScopedObjectAccess& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001291 // Compute depth of stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001292 CountStackDepthVisitor count_visitor(GetManagedStack(), GetTraceStack());
1293 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001294 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001295 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001296
Ian Rogersaaa20802011-09-11 21:47:37 -07001297 // Build internal stack trace
Ian Rogers0399dde2012-06-06 17:09:28 -07001298 BuildInternalStackTraceVisitor build_trace_visitor(GetManagedStack(), GetTraceStack(),
1299 skip_depth);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001300 if (!build_trace_visitor.Init(depth, soa)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001301 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001302 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001303 build_trace_visitor.WalkStack();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001304 return soa.AddLocalReference<jobjectArray>(build_trace_visitor.GetInternalStackTrace());
Ian Rogersaaa20802011-09-11 21:47:37 -07001305}
1306
Elliott Hughes01158d72011-09-19 19:47:10 -07001307jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1308 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001309 // Transition into runnable state to work on Object*/Array*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001310 ScopedObjectAccess soa(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001311 // Decode the internal stack trace into the depth, method trace and PC trace
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001312 ObjectArray<Object>* method_trace = soa.Decode<ObjectArray<Object>*>(internal);
Ian Rogers9074b992011-10-26 17:41:55 -07001313 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001314 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1315
1316 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1317
Elliott Hughes01158d72011-09-19 19:47:10 -07001318 jobjectArray result;
1319 ObjectArray<StackTraceElement>* java_traces;
1320 if (output_array != NULL) {
1321 // Reuse the array we were given.
1322 result = output_array;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001323 java_traces = soa.Decode<ObjectArray<StackTraceElement>*>(output_array);
Elliott Hughes01158d72011-09-19 19:47:10 -07001324 // ...adjusting the number of frames we'll write to not exceed the array length.
1325 depth = std::min(depth, java_traces->GetLength());
1326 } else {
1327 // Create java_trace array and place in local reference table
1328 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001329 if (java_traces == NULL) {
1330 return NULL;
1331 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001332 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001333 }
1334
1335 if (stack_depth != NULL) {
1336 *stack_depth = depth;
1337 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001338
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001339 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001340 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001341 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartier66f19252012-09-18 08:57:04 -07001342 AbstractMethod* method = down_cast<AbstractMethod*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001343 mh.ChangeMethod(method);
Ian Rogers0399dde2012-06-06 17:09:28 -07001344 uint32_t dex_pc = pc_trace->Get(i);
1345 int32_t line_number = mh.GetLineNumFromDexPC(dex_pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001346 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001347 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001348 const char* descriptor = mh.GetDeclaringClassDescriptor();
1349 CHECK(descriptor != NULL);
1350 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001351 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1352 if (class_name_object.get() == NULL) {
1353 return NULL;
1354 }
Ian Rogers48601312011-12-07 16:45:19 -08001355 const char* method_name = mh.GetName();
1356 CHECK(method_name != NULL);
1357 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001358 if (method_name_object.get() == NULL) {
1359 return NULL;
1360 }
Ian Rogers48601312011-12-07 16:45:19 -08001361 const char* source_file = mh.GetDeclaringClassSourceFile();
1362 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001363 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001364 method_name_object.get(),
1365 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001366 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001367 if (obj == NULL) {
1368 return NULL;
1369 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001370#ifdef MOVING_GARBAGE_COLLECTOR
1371 // Re-read after potential GC
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001372 java_traces = Decode<ObjectArray<Object>*>(soa.Env(), result);
1373 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(soa.Env(), internal));
Ian Rogersaaa20802011-09-11 21:47:37 -07001374 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1375#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001376 java_traces->Set(i, obj);
1377 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001378 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001379}
1380
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001381void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001382 va_list args;
1383 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001384 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001385 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001386}
1387
1388void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1389 std::string msg;
1390 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001391 ThrowNewException(exception_class_descriptor, msg.c_str());
1392}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001393
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001394void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001395 AssertNoPendingException(); // Callers should either clear or call ThrowNewWrappedException.
Elliott Hughesa4f94742012-05-29 16:28:38 -07001396 ThrowNewWrappedException(exception_class_descriptor, msg);
1397}
1398
1399void Thread::ThrowNewWrappedException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001400 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001401 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001402 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001403 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001404 descriptor.erase(descriptor.length() - 1);
1405
1406 JNIEnv* env = GetJniEnv();
Elliott Hughesa4f94742012-05-29 16:28:38 -07001407 jobject cause = env->ExceptionOccurred();
1408 env->ExceptionClear();
1409
Elliott Hughes726079d2011-10-07 18:43:44 -07001410 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001411 if (exception_class.get() == NULL) {
1412 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1413 << PrettyTypeOf(GetException());
1414 CHECK(IsExceptionPending());
1415 return;
1416 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001417 if (!Runtime::Current()->IsStarted()) {
1418 // Something is trying to throw an exception without a started
1419 // runtime, which is the common case in the compiler. We won't be
1420 // able to invoke the constructor of the exception, so use
1421 // AllocObject which will not invoke a constructor.
1422 ScopedLocalRef<jthrowable> exception(
1423 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1424 if (exception.get() != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001425 ScopedObjectAccessUnchecked soa(env);
1426 Throwable* t = reinterpret_cast<Throwable*>(soa.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001427 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001428 soa.Self()->SetException(t);
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001429 } else {
1430 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1431 << PrettyTypeOf(GetException());
1432 CHECK(IsExceptionPending());
1433 }
1434 return;
1435 }
Elliott Hughesa4f94742012-05-29 16:28:38 -07001436 int rc = ::art::ThrowNewException(env, exception_class.get(), msg, cause);
Elliott Hughes30646832011-10-13 16:59:46 -07001437 if (rc != JNI_OK) {
1438 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1439 << PrettyTypeOf(GetException());
1440 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001441 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001442}
1443
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001444void Thread::ThrowOutOfMemoryError(const char* msg) {
1445 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1446 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001447 if (!throwing_OutOfMemoryError_) {
1448 throwing_OutOfMemoryError_ = true;
Elliott Hughes57aba862012-06-20 14:00:47 -07001449 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001450 } else {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001451 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
1452 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001453 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001454 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001455}
1456
Elliott Hughes498508c2011-10-17 14:58:22 -07001457Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001458 return Thread::Current();
1459}
1460
1461void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001462 std::ostringstream ss;
1463 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001464 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001465 // log to stderr for debugging command line processes
1466 std::cerr << str;
1467#ifdef HAVE_ANDROID_OS
1468 // log to logcat for debugging frameworks processes
1469 LOG(INFO) << str;
1470#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001471}
1472
Elliott Hughes98e20172012-04-24 15:38:13 -07001473struct EntryPointInfo {
1474 uint32_t offset;
1475 const char* name;
1476};
1477#define ENTRY_POINT_INFO(x) { ENTRYPOINT_OFFSET(x), #x }
1478static const EntryPointInfo gThreadEntryPointInfo[] = {
1479 ENTRY_POINT_INFO(pAllocArrayFromCode),
1480 ENTRY_POINT_INFO(pAllocArrayFromCodeWithAccessCheck),
1481 ENTRY_POINT_INFO(pAllocObjectFromCode),
1482 ENTRY_POINT_INFO(pAllocObjectFromCodeWithAccessCheck),
1483 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCode),
1484 ENTRY_POINT_INFO(pCheckAndAllocArrayFromCodeWithAccessCheck),
1485 ENTRY_POINT_INFO(pInstanceofNonTrivialFromCode),
1486 ENTRY_POINT_INFO(pCanPutArrayElementFromCode),
1487 ENTRY_POINT_INFO(pCheckCastFromCode),
1488 ENTRY_POINT_INFO(pDebugMe),
1489 ENTRY_POINT_INFO(pUpdateDebuggerFromCode),
1490 ENTRY_POINT_INFO(pInitializeStaticStorage),
1491 ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccessFromCode),
1492 ENTRY_POINT_INFO(pInitializeTypeFromCode),
1493 ENTRY_POINT_INFO(pResolveStringFromCode),
Ian Rogers474b6da2012-09-25 00:20:38 -07001494 ENTRY_POINT_INFO(pGetAndClearException),
Elliott Hughes98e20172012-04-24 15:38:13 -07001495 ENTRY_POINT_INFO(pSet32Instance),
1496 ENTRY_POINT_INFO(pSet32Static),
1497 ENTRY_POINT_INFO(pSet64Instance),
1498 ENTRY_POINT_INFO(pSet64Static),
1499 ENTRY_POINT_INFO(pSetObjInstance),
1500 ENTRY_POINT_INFO(pSetObjStatic),
1501 ENTRY_POINT_INFO(pGet32Instance),
1502 ENTRY_POINT_INFO(pGet32Static),
1503 ENTRY_POINT_INFO(pGet64Instance),
1504 ENTRY_POINT_INFO(pGet64Static),
1505 ENTRY_POINT_INFO(pGetObjInstance),
1506 ENTRY_POINT_INFO(pGetObjStatic),
1507 ENTRY_POINT_INFO(pHandleFillArrayDataFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001508 ENTRY_POINT_INFO(pFindNativeMethod),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 ENTRY_POINT_INFO(pJniMethodStart),
1510 ENTRY_POINT_INFO(pJniMethodStartSynchronized),
1511 ENTRY_POINT_INFO(pJniMethodEnd),
1512 ENTRY_POINT_INFO(pJniMethodEndSynchronized),
1513 ENTRY_POINT_INFO(pJniMethodEndWithReference),
1514 ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
Elliott Hughes98e20172012-04-24 15:38:13 -07001515 ENTRY_POINT_INFO(pLockObjectFromCode),
1516 ENTRY_POINT_INFO(pUnlockObjectFromCode),
1517 ENTRY_POINT_INFO(pCmpgDouble),
1518 ENTRY_POINT_INFO(pCmpgFloat),
1519 ENTRY_POINT_INFO(pCmplDouble),
1520 ENTRY_POINT_INFO(pCmplFloat),
1521 ENTRY_POINT_INFO(pDadd),
1522 ENTRY_POINT_INFO(pDdiv),
1523 ENTRY_POINT_INFO(pDmul),
1524 ENTRY_POINT_INFO(pDsub),
1525 ENTRY_POINT_INFO(pF2d),
1526 ENTRY_POINT_INFO(pFmod),
Ian Rogers0183dd72012-09-17 23:06:51 -07001527 ENTRY_POINT_INFO(pSqrt),
Elliott Hughes98e20172012-04-24 15:38:13 -07001528 ENTRY_POINT_INFO(pI2d),
1529 ENTRY_POINT_INFO(pL2d),
1530 ENTRY_POINT_INFO(pD2f),
1531 ENTRY_POINT_INFO(pFadd),
1532 ENTRY_POINT_INFO(pFdiv),
1533 ENTRY_POINT_INFO(pFmodf),
1534 ENTRY_POINT_INFO(pFmul),
1535 ENTRY_POINT_INFO(pFsub),
1536 ENTRY_POINT_INFO(pI2f),
1537 ENTRY_POINT_INFO(pL2f),
1538 ENTRY_POINT_INFO(pD2iz),
1539 ENTRY_POINT_INFO(pF2iz),
1540 ENTRY_POINT_INFO(pIdivmod),
1541 ENTRY_POINT_INFO(pD2l),
1542 ENTRY_POINT_INFO(pF2l),
1543 ENTRY_POINT_INFO(pLdiv),
1544 ENTRY_POINT_INFO(pLdivmod),
1545 ENTRY_POINT_INFO(pLmul),
1546 ENTRY_POINT_INFO(pShlLong),
1547 ENTRY_POINT_INFO(pShrLong),
1548 ENTRY_POINT_INFO(pUshrLong),
1549 ENTRY_POINT_INFO(pIndexOf),
1550 ENTRY_POINT_INFO(pMemcmp16),
1551 ENTRY_POINT_INFO(pStringCompareTo),
1552 ENTRY_POINT_INFO(pMemcpy),
1553 ENTRY_POINT_INFO(pUnresolvedDirectMethodTrampolineFromCode),
1554 ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
1555 ENTRY_POINT_INFO(pInvokeInterfaceTrampoline),
1556 ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
1557 ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
1558 ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
1559 ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
1560 ENTRY_POINT_INFO(pCheckSuspendFromCode),
1561 ENTRY_POINT_INFO(pTestSuspendFromCode),
1562 ENTRY_POINT_INFO(pDeliverException),
1563 ENTRY_POINT_INFO(pThrowAbstractMethodErrorFromCode),
1564 ENTRY_POINT_INFO(pThrowArrayBoundsFromCode),
1565 ENTRY_POINT_INFO(pThrowDivZeroFromCode),
1566 ENTRY_POINT_INFO(pThrowNoSuchMethodFromCode),
1567 ENTRY_POINT_INFO(pThrowNullPointerFromCode),
1568 ENTRY_POINT_INFO(pThrowStackOverflowFromCode),
Elliott Hughes98e20172012-04-24 15:38:13 -07001569};
1570#undef ENTRY_POINT_INFO
1571
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001572void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1573 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes98e20172012-04-24 15:38:13 -07001574
1575#define DO_THREAD_OFFSET(x) if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { os << # x; return; }
Ian Rogers474b6da2012-09-25 00:20:38 -07001576 DO_THREAD_OFFSET(state_and_flags_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001577 DO_THREAD_OFFSET(card_table_);
1578 DO_THREAD_OFFSET(exception_);
1579 DO_THREAD_OFFSET(jni_env_);
1580 DO_THREAD_OFFSET(self_);
1581 DO_THREAD_OFFSET(stack_end_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001582 DO_THREAD_OFFSET(suspend_count_);
1583 DO_THREAD_OFFSET(thin_lock_id_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001584 //DO_THREAD_OFFSET(top_of_managed_stack_);
1585 //DO_THREAD_OFFSET(top_of_managed_stack_pc_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001586 DO_THREAD_OFFSET(top_sirt_);
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001587#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001588
1589 size_t entry_point_count = arraysize(gThreadEntryPointInfo);
1590 CHECK_EQ(entry_point_count * size_of_pointers, sizeof(EntryPoints));
1591 uint32_t expected_offset = OFFSETOF_MEMBER(Thread, entrypoints_);
1592 for (size_t i = 0; i < entry_point_count; ++i) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001593 CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset) << gThreadEntryPointInfo[i].name;
Elliott Hughes98e20172012-04-24 15:38:13 -07001594 expected_offset += size_of_pointers;
1595 if (gThreadEntryPointInfo[i].offset == offset) {
1596 os << gThreadEntryPointInfo[i].name;
1597 return;
1598 }
1599 }
1600 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001601}
1602
Ian Rogers0399dde2012-06-06 17:09:28 -07001603static const bool kDebugExceptionDelivery = false;
1604class CatchBlockStackVisitor : public StackVisitor {
Ian Rogersbdb03912011-09-14 00:55:44 -07001605 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001606 CatchBlockStackVisitor(Thread* self, Throwable* exception)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001607 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers0399dde2012-06-06 17:09:28 -07001608 : StackVisitor(self->GetManagedStack(), self->GetTraceStack(), self->GetLongJumpContext()),
1609 self_(self), exception_(exception), to_find_(exception->GetClass()), throw_method_(NULL),
1610 throw_frame_id_(0), throw_dex_pc_(0), handler_quick_frame_(NULL),
1611 handler_quick_frame_pc_(0), handler_dex_pc_(0), native_method_count_(0),
Ian Rogers57b86d42012-03-27 16:05:41 -07001612 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers52673ff2012-06-27 23:25:34 -07001613 // Exception not in root sets, can't allow GC.
1614 last_no_assert_suspension_cause_ = self->StartAssertNoThreadSuspension("Finding catch block");
1615 }
1616
1617 ~CatchBlockStackVisitor() {
1618 LOG(FATAL) << "UNREACHABLE"; // Expected to take long jump.
Ian Rogers67375ac2011-09-14 00:55:44 -07001619 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001620
Ian Rogersb726dcb2012-09-05 08:57:23 -07001621 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1622 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001623 AbstractMethod* method = GetMethod();
Elliott Hughes530fa002012-03-12 11:44:49 -07001624 if (method == NULL) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001625 // This is the upcall, we remember the frame and last pc so that we may long jump to them.
1626 handler_quick_frame_pc_ = GetCurrentQuickFramePc();
1627 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001628 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001629 }
1630 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001631 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001632 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001633 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001634 } else {
Ian Rogers0399dde2012-06-06 17:09:28 -07001635 if (throw_method_ == NULL) {
1636 throw_method_ = method;
1637 throw_frame_id_ = GetFrameId();
1638 throw_dex_pc_ = GetDexPc();
Ian Rogers67375ac2011-09-14 00:55:44 -07001639 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001640 if (method->IsNative()) {
1641 native_method_count_++;
1642 } else {
1643 // Unwind stack when an exception occurs during method tracing
1644 if (UNLIKELY(method_tracing_active_ && IsTraceExitPc(GetCurrentQuickFramePc()))) {
buzbee8320f382012-09-11 16:29:42 -07001645 uintptr_t pc = TraceMethodUnwindFromCode(Thread::Current());
Ian Rogers0c7abda2012-09-19 13:33:42 -07001646 dex_pc = method->ToDexPc(pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001647 } else {
1648 dex_pc = GetDexPc();
1649 }
1650 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001651 }
1652 if (dex_pc != DexFile::kDexNoIndex) {
1653 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1654 if (found_dex_pc != DexFile::kDexNoIndex) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001655 handler_dex_pc_ = found_dex_pc;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001656 handler_quick_frame_pc_ = method->ToNativePc(found_dex_pc);
Ian Rogers0399dde2012-06-06 17:09:28 -07001657 handler_quick_frame_ = GetCurrentQuickFrame();
Ian Rogers57b86d42012-03-27 16:05:41 -07001658 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001659 }
1660 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001661 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001662 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001663
Ian Rogersb726dcb2012-09-05 08:57:23 -07001664 void DoLongJump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001665 AbstractMethod* catch_method = *handler_quick_frame_;
Elliott Hughes6e9d22c2012-06-22 15:02:37 -07001666 Dbg::PostException(self_, throw_frame_id_, throw_method_, throw_dex_pc_,
Ian Rogers0399dde2012-06-06 17:09:28 -07001667 catch_method, handler_dex_pc_, exception_);
1668 if (kDebugExceptionDelivery) {
1669 if (catch_method == NULL) {
1670 LOG(INFO) << "Handler is upcall";
1671 } else {
1672 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1673 const DexFile& dex_file =
1674 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1675 int line_number = dex_file.GetLineNumFromPC(catch_method, handler_dex_pc_);
1676 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
1677 }
1678 }
Ian Rogers52673ff2012-06-27 23:25:34 -07001679 self_->SetException(exception_); // Exception back in root set.
1680 self_->EndAssertNoThreadSuspension(last_no_assert_suspension_cause_);
Ian Rogers0399dde2012-06-06 17:09:28 -07001681 // Place context back on thread so it will be available when we continue.
1682 self_->ReleaseLongJumpContext(context_);
1683 context_->SetSP(reinterpret_cast<uintptr_t>(handler_quick_frame_));
1684 CHECK_NE(handler_quick_frame_pc_, 0u);
1685 context_->SetPC(handler_quick_frame_pc_);
1686 context_->SmashCallerSaves();
1687 context_->DoLongJump();
1688 }
1689
1690 private:
1691 Thread* self_;
1692 Throwable* exception_;
1693 // The type of the exception catch block to find.
Ian Rogersbdb03912011-09-14 00:55:44 -07001694 Class* to_find_;
Mathieu Chartier66f19252012-09-18 08:57:04 -07001695 AbstractMethod* throw_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001696 JDWP::FrameId throw_frame_id_;
1697 uint32_t throw_dex_pc_;
1698 // Quick frame with found handler or last frame if no handler found.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001699 AbstractMethod** handler_quick_frame_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001700 // PC to branch to for the handler.
1701 uintptr_t handler_quick_frame_pc_;
1702 // Associated dex PC.
1703 uint32_t handler_dex_pc_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001704 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1705 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001706 // Is method tracing active?
1707 const bool method_tracing_active_;
Ian Rogers52673ff2012-06-27 23:25:34 -07001708 // Support for nesting no thread suspension checks.
1709 const char* last_no_assert_suspension_cause_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001710};
1711
Ian Rogersff1ed472011-09-20 13:46:24 -07001712void Thread::DeliverException() {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001713 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001714 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001715 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001716 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001717 ClearException();
1718 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001719 String* msg = exception->GetDetailMessage();
1720 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1721 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
Elliott Hughesc073b072012-05-24 19:29:17 -07001722 << ": " << str_msg << "\n");
Ian Rogers28ad40d2011-10-27 15:19:26 -07001723 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001724 CatchBlockStackVisitor catch_finder(this, exception);
1725 catch_finder.WalkStack(true);
1726 catch_finder.DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001727 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001728}
1729
Ian Rogersbdb03912011-09-14 00:55:44 -07001730Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001731 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001732 if (result == NULL) {
1733 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07001734 } else {
1735 long_jump_context_ = NULL; // Avoid context being shared.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001736 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001737 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001738}
1739
Mathieu Chartier66f19252012-09-18 08:57:04 -07001740AbstractMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, size_t* frame_id) const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001741 struct CurrentMethodVisitor : public StackVisitor {
1742 CurrentMethodVisitor(const ManagedStack* stack,
Ian Rogersca190662012-06-26 15:45:57 -07001743 const std::vector<TraceStackFrame>* trace_stack)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001744 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001745 : StackVisitor(stack, trace_stack, NULL), method_(NULL), dex_pc_(0), frame_id_(0) {}
Elliott Hughes8be2d402012-02-23 14:22:41 -08001746
Ian Rogersb726dcb2012-09-05 08:57:23 -07001747 virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001748 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001749 if (m->IsRuntimeMethod()) {
1750 // Continue if this is a runtime method.
1751 return true;
1752 }
1753 method_ = m;
1754 dex_pc_ = GetDexPc();
1755 frame_id_ = GetFrameId();
1756 return false;
1757 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001758 AbstractMethod* method_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001759 uint32_t dex_pc_;
1760 size_t frame_id_;
1761 };
1762
1763 CurrentMethodVisitor visitor(GetManagedStack(), GetTraceStack());
1764 visitor.WalkStack(false);
1765 if (dex_pc != NULL) {
1766 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001767 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001768 if (frame_id != NULL) {
1769 *frame_id = visitor.frame_id_;
jeffhao33dc7712011-11-09 17:54:24 -08001770 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001771 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08001772}
1773
Elliott Hughes5f791332011-09-15 17:45:30 -07001774bool Thread::HoldsLock(Object* object) {
1775 if (object == NULL) {
1776 return false;
1777 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001778 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001779}
1780
Ian Rogers0399dde2012-06-06 17:09:28 -07001781class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001782 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001783 ReferenceMapVisitor(const ManagedStack* stack, const std::vector<TraceStackFrame>* trace_stack,
Ian Rogersca190662012-06-26 15:45:57 -07001784 Context* context, Heap::RootVisitor* root_visitor, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001785 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogersca190662012-06-26 15:45:57 -07001786 : StackVisitor(stack, trace_stack, context), root_visitor_(root_visitor), arg_(arg) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07001787
Ian Rogersb726dcb2012-09-05 08:57:23 -07001788 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001789 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001790 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
1791 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001792 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001793 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
1794 if (shadow_frame != NULL) {
1795 shadow_frame->VisitRoots(root_visitor_, arg_);
1796 } else {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001797 AbstractMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001798 // Process register map (which native and runtime methods don't have)
Ian Rogers640495b2012-06-22 15:15:47 -07001799 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001800 const uint8_t* native_gc_map = m->GetNativeGcMap();
1801 CHECK(native_gc_map != NULL) << PrettyMethod(m);
1802 mh_.ChangeMethod(m);
1803 const DexFile::CodeItem* code_item = mh_.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001804 DCHECK(code_item != NULL) << PrettyMethod(m); // Can't be NULL or how would we compile its instructions?
Ian Rogers0c7abda2012-09-19 13:33:42 -07001805 NativePcOffsetToReferenceMap map(native_gc_map);
Ian Rogers0399dde2012-06-06 17:09:28 -07001806 size_t num_regs = std::min(map.RegWidth() * 8,
1807 static_cast<size_t>(code_item->registers_size_));
Ian Rogers0c7abda2012-09-19 13:33:42 -07001808 if (num_regs > 0) {
1809 const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
1810 DCHECK(reg_bitmap != NULL);
1811 const VmapTable vmap_table(m->GetVmapTableRaw());
1812 uint32_t core_spills = m->GetCoreSpillMask();
1813 uint32_t fp_spills = m->GetFpSpillMask();
1814 size_t frame_size = m->GetFrameSizeInBytes();
1815 // For all dex registers in the bitmap
Mathieu Chartier66f19252012-09-18 08:57:04 -07001816 AbstractMethod** cur_quick_frame = GetCurrentQuickFrame();
Ian Rogers0c7abda2012-09-19 13:33:42 -07001817 DCHECK(cur_quick_frame != NULL);
1818 for (size_t reg = 0; reg < num_regs; ++reg) {
1819 // Does this register hold a reference?
1820 if (TestBitmap(reg, reg_bitmap)) {
1821 uint32_t vmap_offset;
1822 Object* ref;
1823 if (vmap_table.IsInContext(reg, vmap_offset)) {
1824 // Compute the register we need to load from the context
1825 uint32_t spill_mask = core_spills;
1826 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1827 uint32_t matches = 0;
1828 uint32_t spill_shifts = 0;
1829 while (matches != (vmap_offset + 1)) {
1830 DCHECK_NE(spill_mask, 0u);
1831 matches += spill_mask & 1; // Add 1 if the low bit is set
1832 spill_mask >>= 1;
1833 spill_shifts++;
1834 }
1835 spill_shifts--; // wind back one as we want the last match
1836 ref = reinterpret_cast<Object*>(GetGPR(spill_shifts));
1837 } else {
1838 ref = reinterpret_cast<Object*>(GetVReg(cur_quick_frame, code_item, core_spills,
1839 fp_spills, frame_size, reg));
Ian Rogers0399dde2012-06-06 17:09:28 -07001840 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07001841 if (ref != NULL) {
1842 root_visitor_(ref, arg_);
1843 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001844 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001845 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001846 }
1847 }
1848 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001849 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001850 }
1851
1852 private:
1853 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1854 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1855 }
1856
Ian Rogers0c7abda2012-09-19 13:33:42 -07001857 // Call-back when we visit a root.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001858 Heap::RootVisitor* root_visitor_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001859 // Argument to call-back.
Ian Rogersd6b1f612011-09-27 13:38:14 -07001860 void* arg_;
Ian Rogers0c7abda2012-09-19 13:33:42 -07001861 // A method helper we keep around to avoid dex file/cache re-computations.
1862 MethodHelper mh_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001863};
1864
1865void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001866 if (exception_ != NULL) {
1867 visitor(exception_, arg);
1868 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001869 if (class_loader_override_ != NULL) {
1870 visitor(class_loader_override_, arg);
1871 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001872 jni_env_->locals.VisitRoots(visitor, arg);
1873 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001874
1875 SirtVisitRoots(visitor, arg);
1876
Ian Rogersd6b1f612011-09-27 13:38:14 -07001877 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07001878 Context* context = GetLongJumpContext();
1879 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context, visitor, arg);
1880 mapper.WalkStack();
1881 ReleaseLongJumpContext(context);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001882}
1883
jeffhao25045522012-03-13 19:34:37 -07001884#if VERIFY_OBJECT_ENABLED
Ian Rogers0399dde2012-06-06 17:09:28 -07001885static void VerifyObject(const Object* obj, void* arg) {
1886 Heap* heap = reinterpret_cast<Heap*>(arg);
1887 heap->VerifyObject(obj);
jeffhao25045522012-03-13 19:34:37 -07001888}
1889
1890void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07001891 UniquePtr<Context> context(Context::Create());
Ian Rogers67054b52012-06-26 16:02:10 -07001892 ReferenceMapVisitor mapper(GetManagedStack(), GetTraceStack(), context.get(), VerifyObject,
Ian Rogers0399dde2012-06-06 17:09:28 -07001893 Runtime::Current()->GetHeap());
1894 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07001895}
1896#endif
1897
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001898// Set the stack end to that to be used during a stack overflow
1899void Thread::SetStackEndForStackOverflow() {
1900 // During stack overflow we allow use of the full stack
1901 if (stack_end_ == stack_begin_) {
1902 DumpStack(std::cerr);
1903 LOG(FATAL) << "Need to increase kStackOverflowReservedBytes (currently "
1904 << kStackOverflowReservedBytes << ")";
1905 }
1906
1907 stack_end_ = stack_begin_;
1908}
1909
Elliott Hughes330304d2011-08-12 14:28:05 -07001910std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07001912 return os;
1913}
1914
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001915#ifndef NDEBUG
1916void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
1917 CHECK_EQ(0u, no_thread_suspension_) << last_no_thread_suspension_cause_;
1918 if (check_locks) {
1919 bool bad_mutexes_held = false;
1920 for (int i = kMaxMutexLevel; i >= 0; --i) {
1921 // We expect no locks except the mutator_lock_.
1922 if (i != kMutatorLock) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001923 BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001924 if (held_mutex != NULL) {
1925 LOG(ERROR) << "holding \"" << held_mutex->GetName()
1926 << "\" at point where thread suspension is expected";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001927 bad_mutexes_held = true;
1928 }
1929 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001930 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001931 CHECK(!bad_mutexes_held);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001932 }
1933}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001934#endif
Elliott Hughesa4060e52012-03-02 16:51:35 -08001935
Elliott Hughes8daa0922011-09-11 13:46:25 -07001936} // namespace art