blob: c50bf0a7ac7e0be5cca3365105f3ea5c70a3bd3b [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>
21#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070030#include "context.h"
Ian Rogersd6b1f612011-09-27 13:38:14 -070031#include "dex_verifier.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070032#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070033#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070034#include "monitor.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070035#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070037#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070038#include "scoped_jni_thread_state.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070039#include "stack.h"
40#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070041#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070042#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070043
44namespace art {
45
46pthread_key_t Thread::pthread_key_self_;
47
Elliott Hughes8e4aac52011-09-26 17:03:36 -070048static Class* gThreadLock = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070049static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070050static Field* gThread_daemon = NULL;
51static Field* gThread_group = NULL;
52static Field* gThread_lock = NULL;
53static Field* gThread_name = NULL;
54static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070055static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070056static Field* gThread_vmData = NULL;
57static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070058static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070059static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070060static Method* gThreadGroup_removeThread = NULL;
61static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070062
buzbeece302932011-10-04 14:32:18 -070063// TODO: flesh out and move to appropriate location
64String* ResolveStringFromCode(Method* method, int32_t string_idx) {
buzbee99f27232011-10-05 12:56:36 -070065 UNIMPLEMENTED(FATAL) << "Resolve string; handle OOM";
66 return NULL; // Must return valid string or if exception, doesn't return
67}
68
69// TODO: move to appropriate location
70static void ObjectInitFromCode(Object* o) {
71 Class* c = o->GetClass();
72 if (c->IsFinalizable()) {
Elliott Hughesadb460d2011-10-05 17:02:34 -070073 Heap::AddFinalizerReference(o);
buzbee99f27232011-10-05 12:56:36 -070074 }
75 /*
76 * NOTE: once debugger/profiler support is added, we'll need to check
77 * here and branch to actual compiled object.<init> to handle any
78 * breakpoint/logging activites if either is active.
79 */
buzbeece302932011-10-04 14:32:18 -070080}
81
buzbee3ea4ec52011-08-22 17:37:19 -070082void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070083#if defined(__arm__)
84 pShlLong = art_shl_long;
85 pShrLong = art_shr_long;
86 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070087 pIdiv = __aeabi_idiv;
88 pIdivmod = __aeabi_idivmod;
89 pI2f = __aeabi_i2f;
90 pF2iz = __aeabi_f2iz;
91 pD2f = __aeabi_d2f;
92 pF2d = __aeabi_f2d;
93 pD2iz = __aeabi_d2iz;
94 pL2f = __aeabi_l2f;
95 pL2d = __aeabi_l2d;
96 pFadd = __aeabi_fadd;
97 pFsub = __aeabi_fsub;
98 pFdiv = __aeabi_fdiv;
99 pFmul = __aeabi_fmul;
100 pFmodf = fmodf;
101 pDadd = __aeabi_dadd;
102 pDsub = __aeabi_dsub;
103 pDdiv = __aeabi_ddiv;
104 pDmul = __aeabi_dmul;
105 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700106 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700107 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700108 pAllocObjectFromCode = art_alloc_object_from_code;
Elliott Hughesb408de72011-10-04 14:35:05 -0700109 pAllocArrayFromCode = art_alloc_array_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700110 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Elliott Hughesb408de72011-10-04 14:35:05 -0700111 pCheckAndAllocArrayFromCode = art_check_and_alloc_array_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700112 pCheckCastFromCode = art_check_cast_from_code;
113 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700114 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700115 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700116 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700117 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
118 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700119 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
120 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700121 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700122 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700123 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700124 pLockObjectFromCode = art_lock_object_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700125 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700126#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700127 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700128 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Ian Rogersad25ac52011-10-04 19:13:33 -0700129 pUnresolvedDirectMethodTrampolineFromCode = UnresolvedDirectMethodTrampolineFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700130 pF2l = F2L;
131 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700132 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700133 pGet32Static = Field::Get32StaticFromCode;
134 pSet32Static = Field::Set32StaticFromCode;
135 pGet64Static = Field::Get64StaticFromCode;
136 pSet64Static = Field::Set64StaticFromCode;
137 pGetObjStatic = Field::GetObjStaticFromCode;
138 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700139 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700140 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee991e3ac2011-09-29 15:44:22 -0700141 pInstanceofNonTrivialFromCode = Class::IsAssignableFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700142 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700143 pCheckSuspendFromCode = artCheckSuspendFromJni;
Brian Carlstrom16192862011-09-12 17:50:06 -0700144 pFindNativeMethod = FindNativeMethod;
145 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbeece302932011-10-04 14:32:18 -0700146 pResolveStringFromCode = ResolveStringFromCode;
buzbee99f27232011-10-05 12:56:36 -0700147 pObjectInit = ObjectInitFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700148 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700149}
150
Brian Carlstrom78128a62011-09-15 17:21:19 -0700151void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700152 Thread* self = reinterpret_cast<Thread*>(arg);
153 Runtime* runtime = Runtime::Current();
154
155 self->Attach(runtime);
156
Elliott Hughes038a8062011-09-18 14:12:41 -0700157 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700158 if (thread_name != NULL) {
159 SetThreadName(thread_name->ToModifiedUtf8().c_str());
160 }
161
162 // Wait until it's safe to start running code. (There may have been a suspend-all
163 // in progress while we were starting up.)
164 runtime->GetThreadList()->WaitForGo();
165
166 // TODO: say "hi" to the debugger.
167 //if (gDvm.debuggerConnected) {
168 // dvmDbgPostThreadStart(self);
169 //}
170
171 // Invoke the 'run' method of our java.lang.Thread.
172 CHECK(self->peer_ != NULL);
173 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700174 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700175 m->Invoke(self, receiver, NULL, NULL);
176
177 // Detach.
178 runtime->GetThreadList()->Unregister();
179
Carl Shapirob5573532011-07-12 18:22:59 -0700180 return NULL;
181}
182
Elliott Hughes93e74e82011-09-13 11:07:03 -0700183void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700184 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700185}
186
Elliott Hughes01158d72011-09-19 19:47:10 -0700187Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
188 Object* thread = Decode<Object*>(env, java_thread);
189 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
190}
191
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700192size_t FixStackSize(size_t stack_size) {
193 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700194 if (stack_size == 0) {
195 stack_size = Runtime::Current()->GetDefaultStackSize();
196 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700197
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700198 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
199 if (stack_size < PTHREAD_STACK_MIN) {
200 stack_size = PTHREAD_STACK_MIN;
201 }
202
203 // It's likely that callers are trying to ensure they have at least a certain amount of
204 // stack space, so we should add our reserved space on top of what they requested, rather
205 // than implicitly take it away from them.
206 stack_size += Thread::kStackOverflowReservedBytes;
207
208 // Some systems require the stack size to be a multiple of the system page size, so round up.
209 stack_size = RoundUp(stack_size, kPageSize);
210
211 return stack_size;
212}
213
214void Thread::Create(Object* peer, size_t stack_size) {
215 CHECK(peer != NULL);
216
217 stack_size = FixStackSize(stack_size);
218
Elliott Hughes93e74e82011-09-13 11:07:03 -0700219 Thread* native_thread = new Thread;
220 native_thread->peer_ = peer;
221
222 // Thread.start is synchronized, so we know that vmData is 0,
223 // and know that we're not racing to assign it.
224 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700225
226 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700227 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
228 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
229 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
230 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
231 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700232
233 // Let the child know when it's safe to start running.
234 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700235}
236
Elliott Hughes93e74e82011-09-13 11:07:03 -0700237void Thread::Attach(const Runtime* runtime) {
238 InitCpu();
239 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700240
Elliott Hughes93e74e82011-09-13 11:07:03 -0700241 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700242
Elliott Hughes93e74e82011-09-13 11:07:03 -0700243 tid_ = ::art::GetTid();
244 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700245
Elliott Hughes93e74e82011-09-13 11:07:03 -0700246 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700247
Elliott Hughes8d768a92011-09-14 16:35:25 -0700248 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700249
Elliott Hughes93e74e82011-09-13 11:07:03 -0700250 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700251
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700252 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700253}
254
255Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
256 Thread* self = new Thread;
257 self->Attach(runtime);
258
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700259 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700260
261 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700262
263 // If we're the main thread, ClassLinker won't be created until after we're attached,
264 // so that thread needs a two-stage attach. Regular threads don't need this hack.
265 if (self->thin_lock_id_ != ThreadList::kMainId) {
266 self->CreatePeer(name, as_daemon);
267 }
268
269 return self;
270}
271
Elliott Hughesd369bb72011-09-12 14:41:14 -0700272jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
273 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
274 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
275 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
276 // This will be null in the compiler (and tests), but never in a running system.
277 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
278 return thread_group;
279}
280
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700281void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700282 JNIEnv* env = jni_env_;
283
Elliott Hughesd369bb72011-09-12 14:41:14 -0700284 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
285 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700286 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700287 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700288 jboolean thread_is_daemon = as_daemon;
289
290 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700291 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700292
Elliott Hughes8daa0922011-09-11 13:46:25 -0700293 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700294 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700295 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700296
297 // Because we mostly run without code available (in the compiler, in tests), we
298 // manually assign the fields the constructor should have set.
299 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700300 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
301 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
302 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
303 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700304}
305
Elliott Hughesbe759c62011-09-08 19:38:21 -0700306void Thread::InitStackHwm() {
307 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700308 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700309
Ian Rogers932746a2011-09-22 18:57:50 -0700310 void* temp_stack_base;
311 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
312 __FUNCTION__);
313 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700314
Ian Rogers932746a2011-09-22 18:57:50 -0700315 if (stack_size_ <= kStackOverflowReservedBytes) {
316 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700317 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700318
Ian Rogers932746a2011-09-22 18:57:50 -0700319 // Set stack_end_ to the bottom of the stack saving space of stack overflows
320 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700321
322 // Sanity check.
323 int stack_variable;
324 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700325
Elliott Hughes8d768a92011-09-14 16:35:25 -0700326 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700327}
328
Elliott Hughesa0957642011-09-02 14:27:33 -0700329void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700330 DumpState(os);
331 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700332}
333
Elliott Hughesd92bec42011-09-02 17:04:36 -0700334std::string GetSchedulerGroup(pid_t tid) {
335 // /proc/<pid>/group looks like this:
336 // 2:devices:/
337 // 1:cpuacct,cpu:/
338 // We want the third field from the line whose second field contains the "cpu" token.
339 std::string cgroup_file;
340 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
341 return "";
342 }
343 std::vector<std::string> cgroup_lines;
344 Split(cgroup_file, '\n', cgroup_lines);
345 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
346 std::vector<std::string> cgroup_fields;
347 Split(cgroup_lines[i], ':', cgroup_fields);
348 std::vector<std::string> cgroups;
349 Split(cgroup_fields[1], ',', cgroups);
350 for (size_t i = 0; i < cgroups.size(); ++i) {
351 if (cgroups[i] == "cpu") {
352 return cgroup_fields[2].substr(1); // Skip the leading slash.
353 }
354 }
355 }
356 return "";
357}
358
359void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700360 std::string thread_name("<native thread without managed peer>");
361 std::string group_name;
362 int priority;
363 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700364
Elliott Hughesd369bb72011-09-12 14:41:14 -0700365 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700366 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700367 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700368 priority = gThread_priority->GetInt(peer_);
369 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700370
Elliott Hughes038a8062011-09-18 14:12:41 -0700371 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700372 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700373 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700374 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
375 }
376 } else {
377 // This name may be truncated, but it's the best we can do in the absence of a managed peer.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700378 std::string stats;
379 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
380 size_t start = stats.find('(') + 1;
381 size_t end = stats.find(')') - start;
382 thread_name = stats.substr(start, end);
383 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700384 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700385 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700386
387 int policy;
388 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700389 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700390
391 std::string scheduler_group(GetSchedulerGroup(GetTid()));
392 if (scheduler_group.empty()) {
393 scheduler_group = "default";
394 }
395
Elliott Hughesd92bec42011-09-02 17:04:36 -0700396 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700397 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700398 os << " daemon";
399 }
400 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700401 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700402 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700403
Elliott Hughesd92bec42011-09-02 17:04:36 -0700404 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700405 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700406 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700407 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700408 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700409 << " self=" << reinterpret_cast<const void*>(this) << "\n";
410 os << " | sysTid=" << GetTid()
411 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
412 << " sched=" << policy << "/" << sp.sched_priority
413 << " cgrp=" << scheduler_group
414 << " handle=" << GetImpl() << "\n";
415
416 // Grab the scheduler stats for this thread.
417 std::string scheduler_stats;
418 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
419 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
420 } else {
421 scheduler_stats = "0 0 0";
422 }
423
424 int utime = 0;
425 int stime = 0;
426 int task_cpu = 0;
427 std::string stats;
428 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
429 // Skip the command, which may contain spaces.
430 stats = stats.substr(stats.find(')') + 2);
431 // Extract the three fields we care about.
432 std::vector<std::string> fields;
433 Split(stats, ' ', fields);
434 utime = strtoull(fields[11].c_str(), NULL, 10);
435 stime = strtoull(fields[12].c_str(), NULL, 10);
436 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
437 }
438
439 os << " | schedstat=( " << scheduler_stats << " )"
440 << " utm=" << utime
441 << " stm=" << stime
442 << " core=" << task_cpu
443 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
444}
445
Elliott Hughesd369bb72011-09-12 14:41:14 -0700446struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700447 StackDumpVisitor(std::ostream& os, const Thread* thread)
448 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700449 }
450
Ian Rogersbdb03912011-09-14 00:55:44 -0700451 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700452 }
453
Ian Rogersbdb03912011-09-14 00:55:44 -0700454 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700455 if (!frame.HasMethod()) {
456 return;
457 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700458
459 Method* m = frame.GetMethod();
460 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700461 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700462 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
463
464 os << " at " << PrettyMethod(m, false);
465 if (m->IsNative()) {
466 os << "(Native method)";
467 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700468 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700469 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
470 }
471 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700472
473 if (frame_count++ == 0) {
474 Monitor::DescribeWait(os, thread);
475 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700476 }
477
478 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700479 const Thread* thread;
480 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700481};
482
Elliott Hughesd92bec42011-09-02 17:04:36 -0700483void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700484 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700485 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700486}
487
Elliott Hughes8d768a92011-09-14 16:35:25 -0700488Thread::State Thread::SetState(Thread::State new_state) {
489 Thread::State old_state = state_;
490 if (old_state == new_state) {
491 return old_state;
492 }
493
494 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
495 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
496
497 if (new_state == Thread::kRunnable) {
498 /*
499 * Change our status to Thread::kRunnable. The transition requires
500 * that we check for pending suspension, because the VM considers
501 * us to be "asleep" in all other states, and another thread could
502 * be performing a GC now.
503 *
504 * The order of operations is very significant here. One way to
505 * do this wrong is:
506 *
507 * GCing thread Our thread (in kNative)
508 * ------------ ----------------------
509 * check suspend count (== 0)
510 * SuspendAllThreads()
511 * grab suspend-count lock
512 * increment all suspend counts
513 * release suspend-count lock
514 * check thread state (== kNative)
515 * all are suspended, begin GC
516 * set state to kRunnable
517 * (continue executing)
518 *
519 * We can correct this by grabbing the suspend-count lock and
520 * performing both of our operations (check suspend count, set
521 * state) while holding it, now we need to grab a mutex on every
522 * transition to kRunnable.
523 *
524 * What we do instead is change the order of operations so that
525 * the transition to kRunnable happens first. If we then detect
526 * that the suspend count is nonzero, we switch to kSuspended.
527 *
528 * Appropriate compiler and memory barriers are required to ensure
529 * that the operations are observed in the expected order.
530 *
531 * This does create a small window of opportunity where a GC in
532 * progress could observe what appears to be a running thread (if
533 * it happens to look between when we set to kRunnable and when we
534 * switch to kSuspended). At worst this only affects assertions
535 * and thread logging. (We could work around it with some sort
536 * of intermediate "pre-running" state that is generally treated
537 * as equivalent to running, but that doesn't seem worthwhile.)
538 *
539 * We can also solve this by combining the "status" and "suspend
540 * count" fields into a single 32-bit value. This trades the
541 * store/load barrier on transition to kRunnable for an atomic RMW
542 * op on all transitions and all suspend count updates (also, all
543 * accesses to status or the thread count require bit-fiddling).
544 * It also eliminates the brief transition through kRunnable when
545 * the thread is supposed to be suspended. This is possibly faster
546 * on SMP and slightly more correct, but less convenient.
547 */
548 android_atomic_acquire_store(new_state, addr);
549 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
550 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
551 }
552 } else {
553 /*
554 * Not changing to Thread::kRunnable. No additional work required.
555 *
556 * We use a releasing store to ensure that, if we were runnable,
557 * any updates we previously made to objects on the managed heap
558 * will be observed before the state change.
559 */
560 android_atomic_release_store(new_state, addr);
561 }
562
563 return old_state;
564}
565
566void Thread::WaitUntilSuspended() {
567 // TODO: dalvik dropped the waiting thread's priority after a while.
568 // TODO: dalvik timed out and aborted.
569 useconds_t delay = 0;
570 while (GetState() == Thread::kRunnable) {
571 useconds_t new_delay = delay * 2;
572 CHECK_GE(new_delay, delay);
573 delay = new_delay;
574 if (delay == 0) {
575 sched_yield();
576 delay = 10000;
577 } else {
578 usleep(delay);
579 }
580 }
581}
582
Elliott Hughesbe759c62011-09-08 19:38:21 -0700583void Thread::ThreadExitCallback(void* arg) {
584 Thread* self = reinterpret_cast<Thread*>(arg);
585 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700586}
587
Elliott Hughesbe759c62011-09-08 19:38:21 -0700588void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700589 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700590 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700591
592 // Double-check the TLS slot allocation.
593 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700594 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700595 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700596}
Carl Shapirob5573532011-07-12 18:22:59 -0700597
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700598// TODO: make more accessible?
599Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
600 Class* c = class_linker->FindPrimitiveClass(descriptor);
601 CHECK(c != NULL) << descriptor;
602 return c;
603}
604
605// TODO: make more accessible?
606Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
607 Class* c = class_linker->FindSystemClass(descriptor);
608 CHECK(c != NULL) << descriptor;
609 return c;
610}
611
612// TODO: make more accessible?
613Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
614 Field* f = c->FindDeclaredInstanceField(name, type);
615 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
616 return f;
617}
618
619// TODO: make more accessible?
620Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
621 Method* m = c->FindVirtualMethod(name, signature);
622 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
623 return m;
624}
625
Elliott Hughes038a8062011-09-18 14:12:41 -0700626void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700627 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
628 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700629
630 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
631 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
632 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
633 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
634 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
635 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
636 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
637 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
638
639 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
640 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
641 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
642 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
643 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
644 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
645 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
646 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
647 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
648
649 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
650 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
651 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
652 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700653
654 // Finish attaching the main thread.
655 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700656}
657
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700658void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700659 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700660}
661
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700662uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
663 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
664 return ThreadList::kInvalidId;
665 }
666 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
667 if (managed_thread == NULL) {
668 return ThreadList::kInvalidId;
669 }
670 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
671 Thread* thread = reinterpret_cast<Thread*>(vmData);
672 if (thread == NULL) {
673 return ThreadList::kInvalidId;
674 }
675 return thread->GetThinLockId();
676}
677
Elliott Hughesdcc24742011-09-07 14:02:44 -0700678Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700679 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700680 top_of_managed_stack_(),
681 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700682 wait_mutex_(new Mutex("Thread wait mutex")),
683 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700684 wait_monitor_(NULL),
685 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700686 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700687 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700688 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700689 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700690 native_to_managed_record_(NULL),
691 top_sirt_(NULL),
692 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700693 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700694 self_(NULL),
695 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700696 exception_(NULL),
697 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700698 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700699 long_jump_context_(NULL),
700 throwing_OOME_(false) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700701 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700702}
703
Elliott Hughes02b48d12011-09-07 17:15:51 -0700704void MonitorExitVisitor(const Object* object, void*) {
705 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700706 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700707}
708
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700709Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700710 SetState(Thread::kRunnable);
711
Elliott Hughes02b48d12011-09-07 17:15:51 -0700712 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700713 if (jni_env_ != NULL) {
714 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
715 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700716
Elliott Hughes93e74e82011-09-13 11:07:03 -0700717 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700718 Object* group = gThread_group->GetObject(peer_);
719
720 // Handle any pending exception.
721 if (IsExceptionPending()) {
722 // Get and clear the exception.
723 Object* exception = GetException();
724 ClearException();
725
726 // If the thread has its own handler, use that.
727 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
728 if (handler == NULL) {
729 // Otherwise use the thread group's default handler.
730 handler = group;
731 }
732
733 // Call the handler.
734 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
735 Object* args[2];
736 args[0] = peer_;
737 args[1] = exception;
738 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
739
740 // If the handler threw, clear that exception too.
741 ClearException();
742 }
743
744 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700745 // group can be null if we're in the compiler or a test.
746 if (group != NULL) {
747 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
748 Object* args = peer_;
749 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
750 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700751
752 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700753 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700754
Elliott Hughes29f27422011-09-18 16:02:18 -0700755 // TODO: say "bye" to the debugger.
756 //if (gDvm.debuggerConnected) {
757 // dvmDbgPostThreadDeath(self);
758 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700759
Elliott Hughes29f27422011-09-18 16:02:18 -0700760 // Thread.join() is implemented as an Object.wait() on the Thread.lock
761 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700762 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700763 Object* lock = gThread_lock->GetObject(peer_);
764 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700765 if (lock != NULL) {
766 lock->MonitorEnter(self);
767 lock->NotifyAll();
768 lock->MonitorExit(self);
769 }
770 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700771
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700772 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700773 jni_env_ = NULL;
774
775 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700776
777 delete wait_cond_;
778 delete wait_mutex_;
779
780 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700781}
782
Ian Rogers408f79a2011-08-23 18:22:33 -0700783size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700784 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700785 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700786 count += cur->NumberOfReferences();
787 }
788 return count;
789}
790
Ian Rogers408f79a2011-08-23 18:22:33 -0700791bool Thread::SirtContains(jobject obj) {
792 Object** sirt_entry = reinterpret_cast<Object**>(obj);
793 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700794 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700795 // A SIRT should always have a jobject/jclass as a native method is passed
796 // in a this pointer or a class
797 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700798 if ((&cur->References()[0] <= sirt_entry) &&
799 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700800 return true;
801 }
802 }
803 return false;
804}
805
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700806void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
807 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
808 size_t num_refs = cur->NumberOfReferences();
809 for (size_t j = 0; j < num_refs; j++) {
810 visitor(cur->References()[j], arg);
811 }
812 }
813}
814
Ian Rogers67375ac2011-09-14 00:55:44 -0700815void Thread::PopSirt() {
816 CHECK(top_sirt_ != NULL);
817 top_sirt_ = top_sirt_->Link();
818}
819
Ian Rogers408f79a2011-08-23 18:22:33 -0700820Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700821 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700822 if (obj == NULL) {
823 return NULL;
824 }
825 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
826 IndirectRefKind kind = GetIndirectRefKind(ref);
827 Object* result;
828 switch (kind) {
829 case kLocal:
830 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700831 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700832 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700833 break;
834 }
835 case kGlobal:
836 {
837 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
838 IndirectReferenceTable& globals = vm->globals;
839 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700840 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700841 break;
842 }
843 case kWeakGlobal:
844 {
845 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
846 IndirectReferenceTable& weak_globals = vm->weak_globals;
847 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700848 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700849 if (result == kClearedJniWeakGlobal) {
850 // This is a special case where it's okay to return NULL.
851 return NULL;
852 }
853 break;
854 }
855 case kSirtOrInvalid:
856 default:
857 // TODO: make stack indirect reference table lookup more efficient
858 // Check if this is a local reference in the SIRT
859 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700860 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700861 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700862 // Assume an invalid local reference is actually a direct pointer.
863 result = reinterpret_cast<Object*>(obj);
864 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700865 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700866 }
867 }
868
869 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700870 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
871 JniAbort(NULL);
872 } else {
873 if (result != kInvalidIndirectRefObject) {
874 Heap::VerifyObject(result);
875 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700876 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700877 return result;
878}
879
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700880class CountStackDepthVisitor : public Thread::StackVisitor {
881 public:
Elliott Hughes29f27422011-09-18 16:02:18 -0700882 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700883
Elliott Hughes29f27422011-09-18 16:02:18 -0700884 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
885 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -0700886 // Note we also skip the frame if it doesn't have a method (namely the callee
887 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -0700888 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -0700889 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700890 skipping_ = false;
891 }
892 if (!skipping_) {
893 ++depth_;
894 } else {
895 ++skip_depth_;
896 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700897 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700898
899 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700900 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700901 }
902
Elliott Hughes29f27422011-09-18 16:02:18 -0700903 int GetSkipDepth() const {
904 return skip_depth_;
905 }
906
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700907 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700908 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -0700909 uint32_t skip_depth_;
910 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700911};
912
Ian Rogersaaa20802011-09-11 21:47:37 -0700913class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700914 public:
Elliott Hughes29f27422011-09-18 16:02:18 -0700915 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
916 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700917 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -0700918 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -0700919 // Register a local reference as IntArray::Alloc may trigger GC
920 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
921 pc_trace_ = IntArray::Alloc(depth);
922#ifdef MOVING_GARBAGE_COLLECTOR
923 // Re-read after potential GC
924 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
925#endif
926 // Save PC trace in last element of method trace, also places it into the
927 // object graph.
928 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700929 }
930
Ian Rogersaaa20802011-09-11 21:47:37 -0700931 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700932
Ian Rogersbdb03912011-09-14 00:55:44 -0700933 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700934 if (skip_depth_ > 0) {
935 skip_depth_--;
936 return;
937 }
Ian Rogersaaa20802011-09-11 21:47:37 -0700938 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -0700939 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -0700940 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700941 }
942
Ian Rogersaaa20802011-09-11 21:47:37 -0700943 jobject GetInternalStackTrace() const {
944 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700945 }
946
947 private:
Elliott Hughes29f27422011-09-18 16:02:18 -0700948 // How many more frames to skip.
949 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -0700950 // Current position down stack trace
951 uint32_t count_;
952 // Array of return PC values
953 IntArray* pc_trace_;
954 // An array of the methods on the stack, the last entry is a reference to the
955 // PC trace
956 ObjectArray<Object>* method_trace_;
957 // Local indirect reference table entry for method trace
958 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700959};
960
Ian Rogersf57c47c2011-10-06 00:06:17 -0700961
Ian Rogersaaa20802011-09-11 21:47:37 -0700962void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700963 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -0700964 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700965 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
966 // CHECK(native_to_managed_record_ != NULL);
967 NativeToManagedRecord* record = native_to_managed_record_;
968
Ian Rogersbdb03912011-09-14 00:55:44 -0700969 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700970 for ( ; frame.GetMethod() != 0; frame.Next()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700971 // DCHECK(frame.GetMethod()->IsWithinCode(pc)); // TODO: restore IsWithinCode
Shih-wei Liao3ddac992011-10-07 00:48:09 -0700972 visitor->VisitFrame(frame, pc);
973 pc = frame.GetReturnPC();
Ian Rogersf57c47c2011-10-06 00:06:17 -0700974 // Move the PC back 2 bytes as a call will frequently terminate the
975 // decoding of a particular instruction and we want to make sure we
976 // get the Dex PC of the instruction with the call and not the
977 // instruction following.
Elliott Hughes418dfe72011-10-06 18:56:27 -0700978 if (pc > 0) { pc -= 2; }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700979 }
980 if (record == NULL) {
981 break;
982 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700983 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -0700984 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -0700985 pc = record->last_top_of_managed_stack_pc_;
986 record = record->link_;
987 }
988}
989
Ian Rogers67375ac2011-09-14 00:55:44 -0700990void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700991 Frame frame = GetTopOfStack();
992 uintptr_t pc = top_of_managed_stack_pc_;
993
994 if (frame.GetSP() != 0) {
995 for ( ; frame.GetMethod() != 0; frame.Next()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700996 // DCHECK(frame.GetMethod()->IsWithinCode(pc)); // TODO: restore IsWithinCode
Shih-wei Liao3ddac992011-10-07 00:48:09 -0700997 visitor->VisitFrame(frame, pc);
998 pc = frame.GetReturnPC();
Ian Rogersf57c47c2011-10-06 00:06:17 -0700999 // Move the PC back 2 bytes as a call will frequently terminate the
1000 // decoding of a particular instruction and we want to make sure we
1001 // get the Dex PC of the instruction with the call and not the
1002 // instruction following.
Elliott Hughes418dfe72011-10-06 18:56:27 -07001003 if (pc > 0) { pc -= 2; }
Ian Rogersbdb03912011-09-14 00:55:44 -07001004 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001005 if (include_upcall) {
1006 visitor->VisitFrame(frame, pc);
1007 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001008 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001009}
1010
Elliott Hughes01158d72011-09-19 19:47:10 -07001011jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001012 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001013 CountStackDepthVisitor count_visitor;
1014 WalkStack(&count_visitor);
1015 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001016 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001017
Ian Rogersaaa20802011-09-11 21:47:37 -07001018 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001019 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001020
1021 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001022 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001023 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001024
Ian Rogersaaa20802011-09-11 21:47:37 -07001025 return build_trace_visitor.GetInternalStackTrace();
1026}
1027
Elliott Hughes01158d72011-09-19 19:47:10 -07001028jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1029 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001030 // Transition into runnable state to work on Object*/Array*
1031 ScopedJniThreadState ts(env);
1032
1033 // Decode the internal stack trace into the depth, method trace and PC trace
1034 ObjectArray<Object>* method_trace =
1035 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1036 int32_t depth = method_trace->GetLength()-1;
1037 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1038
1039 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1040
Elliott Hughes01158d72011-09-19 19:47:10 -07001041 jobjectArray result;
1042 ObjectArray<StackTraceElement>* java_traces;
1043 if (output_array != NULL) {
1044 // Reuse the array we were given.
1045 result = output_array;
1046 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1047 output_array));
1048 // ...adjusting the number of frames we'll write to not exceed the array length.
1049 depth = std::min(depth, java_traces->GetLength());
1050 } else {
1051 // Create java_trace array and place in local reference table
1052 java_traces = class_linker->AllocStackTraceElementArray(depth);
1053 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1054 }
1055
1056 if (stack_depth != NULL) {
1057 *stack_depth = depth;
1058 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001059
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001060 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001061 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1062 Method* method = down_cast<Method*>(method_trace->Get(i));
1063 uint32_t native_pc = pc_trace->Get(i);
1064 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001065 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001066 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001067
Ian Rogersaaa20802011-09-11 21:47:37 -07001068 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001069 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001070 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001071 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001072 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001073 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001074 method->ToDexPC(native_pc)));
1075#ifdef MOVING_GARBAGE_COLLECTOR
1076 // Re-read after potential GC
1077 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1078 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1079 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1080#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001081 java_traces->Set(i, obj);
1082 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001083 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001084}
1085
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001086void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001087 va_list args;
1088 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001089 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001090 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001091}
1092
1093void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1094 std::string msg;
1095 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001096 ThrowNewException(exception_class_descriptor, msg.c_str());
1097}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001098
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001099void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001100 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001102 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001103 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001104 descriptor.erase(descriptor.length() - 1);
1105
1106 JNIEnv* env = GetJniEnv();
1107 jclass exception_class = env->FindClass(descriptor.c_str());
1108 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001109 int rc = env->ThrowNew(exception_class, msg);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001110 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001111 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001112}
1113
Elliott Hughes418dfe72011-10-06 18:56:27 -07001114void Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
1115 if (!throwing_OOME_) {
1116 throwing_OOME_ = true;
1117 ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
1118 LOG(ERROR) << "Failed to allocate a " << PrettyDescriptor(c->GetDescriptor()) << " (" << byte_count << " bytes)";
1119 } else {
1120 UNIMPLEMENTED(FATAL) << "throw one i prepared earlier...";
1121 }
1122 throwing_OOME_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001123}
1124
Ian Rogersbdb03912011-09-14 00:55:44 -07001125class CatchBlockStackVisitor : public Thread::StackVisitor {
1126 public:
1127 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001128 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1129#ifndef NDEBUG
1130 handler_pc_ = 0xEBADC0DE;
1131 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1132#endif
1133 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001134
Ian Rogersbdb03912011-09-14 00:55:44 -07001135 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1136 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001137 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001138 if (method == NULL) {
1139 // This is the upcall, we remember the frame and last_pc so that we may
1140 // long jump to them
Ian Rogersf57c47c2011-10-06 00:06:17 -07001141 handler_pc_ = pc + 2; // We want to return after the call instruction, wind forward 2 again
Ian Rogers67375ac2011-09-14 00:55:44 -07001142 handler_frame_ = fr;
1143 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001144 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001145 uint32_t dex_pc = DexFile::kDexNoIndex;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001146 if (method->IsCalleeSaveMethod()) {
Ian Rogers90865722011-09-19 11:11:44 -07001147 // ignore callee save method
1148 } else if (method->IsNative()) {
1149 native_method_count_++;
1150 } else {
Ian Rogers90865722011-09-19 11:11:44 -07001151 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001152 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001153 if (dex_pc != DexFile::kDexNoIndex) {
1154 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1155 if (found_dex_pc != DexFile::kDexNoIndex) {
1156 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001157 handler_pc_ = method->ToNativePC(found_dex_pc);
1158 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001159 }
1160 }
1161 if (!found_) {
1162 // Caller may be handler, fill in callee saves in context
1163 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001164 }
1165 }
1166 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001167
1168 // Did we find a catch block yet?
1169 bool found_;
1170 // The type of the exception catch block to find
1171 Class* to_find_;
1172 // Frame with found handler or last frame if no handler found
1173 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001174 // PC to branch to for the handler
1175 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001176 // Context that will be the target of the long jump
1177 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001178 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1179 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001180};
1181
Ian Rogersff1ed472011-09-20 13:46:24 -07001182void Thread::DeliverException() {
1183 Throwable *exception = GetException(); // Set exception on thread
1184 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001185
1186 Context* long_jump_context = GetLongJumpContext();
1187 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001188 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001189
Ian Rogers67375ac2011-09-14 00:55:44 -07001190 // Pop any SIRT
1191 if (catch_finder.native_method_count_ == 1) {
1192 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001193 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001194 // We only expect the stack crawl to have passed 1 native method as it's terminated
1195 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001196 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001197 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001198 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1199 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001200 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001201}
1202
Ian Rogersbdb03912011-09-14 00:55:44 -07001203Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001204 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001205 if (result == NULL) {
1206 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001207 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001208 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001209 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001210}
1211
Elliott Hughes5f791332011-09-15 17:45:30 -07001212bool Thread::HoldsLock(Object* object) {
1213 if (object == NULL) {
1214 return false;
1215 }
1216 return object->GetLockOwner() == thin_lock_id_;
1217}
1218
Elliott Hughes038a8062011-09-18 14:12:41 -07001219bool Thread::IsDaemon() {
1220 return gThread_daemon->GetBoolean(peer_);
1221}
1222
Ian Rogersd6b1f612011-09-27 13:38:14 -07001223class ReferenceMapVisitor : public Thread::StackVisitor {
1224 public:
1225 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1226 context_(context), root_visitor_(root_visitor), arg_(arg) {
1227 }
1228
1229 void VisitFrame(const Frame& frame, uintptr_t pc) {
1230 Method* m = frame.GetMethod();
Ian Rogersd6b1f612011-09-27 13:38:14 -07001231 // Process register map (which native and callee save methods don't have)
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001232 if (!m->IsNative() && !m->IsCalleeSaveMethod()) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001233 UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
Ian Rogersf57c47c2011-10-06 00:06:17 -07001234 const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(map.get(), m->ToDexPC(pc));
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001235 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
Ian Rogersf57c47c2011-10-06 00:06:17 -07001236 << "@ PC: " << m->ToDexPC(pc);
Ian Rogersd6b1f612011-09-27 13:38:14 -07001237 CHECK(reg_bitmap != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001238 const uint16_t* vmap = m->GetVmapTable();
Ian Rogersd6b1f612011-09-27 13:38:14 -07001239 // For all dex registers
1240 for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1241 // Does this register hold a reference?
1242 if (TestBitmap(reg, reg_bitmap)) {
1243 // Is the reference in the context or on the stack?
1244 bool in_context = false;
Ian Rogersf57c47c2011-10-06 00:06:17 -07001245 uint32_t vmap_offset = 0xEBAD0FF5;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001246 // TODO: take advantage of the registers being ordered
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001247 for (int i = 0; i < m->GetVmapTableLength(); i++) {
1248 if (vmap[i] == reg) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001249 in_context = true;
1250 vmap_offset = i;
1251 break;
1252 }
1253 }
1254 Object* ref;
1255 if (in_context) {
1256 // Compute the register we need to load from the context
1257 uint32_t spill_mask = m->GetCoreSpillMask();
Ian Rogersf57c47c2011-10-06 00:06:17 -07001258 uint32_t matches = 0;
1259 uint32_t spill_shifts = 0;
1260 while (matches != (vmap_offset + 1)) {
1261 CHECK_NE(spill_mask, 0u);
1262 matches += spill_mask & 1; // Add 1 if the low bit is set
1263 spill_mask >>= 1;
1264 spill_shifts++;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001265 }
Ian Rogersf57c47c2011-10-06 00:06:17 -07001266 spill_shifts--; // wind back one as we want the last match
1267 ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001268 } else {
1269 ref = reinterpret_cast<Object*>(frame.GetVReg(m ,reg));
1270 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001271 if (ref != NULL) {
1272 root_visitor_(ref, arg_);
1273 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001274 }
1275 }
1276 }
1277 context_->FillCalleeSaves(frame);
1278 }
1279
1280 private:
1281 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1282 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1283 }
1284
1285 // Context used to build up picture of callee saves
1286 Context* context_;
1287 // Call-back when we visit a root
1288 Heap::RootVisitor* root_visitor_;
1289 // Argument to call-back
1290 void* arg_;
1291};
1292
1293void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001294 if (exception_ != NULL) {
1295 visitor(exception_, arg);
1296 }
1297 if (peer_ != NULL) {
1298 visitor(peer_, arg);
1299 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001300 jni_env_->locals.VisitRoots(visitor, arg);
1301 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001302
1303 SirtVisitRoots(visitor, arg);
1304
Ian Rogersd6b1f612011-09-27 13:38:14 -07001305 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1306 // delivery.
1307 Context* context = GetLongJumpContext();
1308 // Visit roots on this thread's stack
1309 ReferenceMapVisitor mapper(context, visitor, arg);
1310 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001311}
1312
Ian Rogersb033c752011-07-20 12:22:35 -07001313static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001314 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001315 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001316 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001317 "Blocked",
1318 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001319 "Initializing",
1320 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001321 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001322 "VmWait",
1323 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001324};
1325std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001326 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001327 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1328 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001329 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001330 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001331 }
1332 return os;
1333}
1334
Elliott Hughes330304d2011-08-12 14:28:05 -07001335std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1336 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001337 << ",pthread_t=" << thread.GetImpl()
1338 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001339 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001340 << ",state=" << thread.GetState()
1341 << ",peer=" << thread.GetPeer()
1342 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001343 return os;
1344}
1345
Elliott Hughes8daa0922011-09-11 13:46:25 -07001346} // namespace art