blob: 78c877d1bf8ffee96839074ef8630d0f32245451 [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()) {
73 o->AddFinalizerReference();
74 }
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 Rogersff1ed472011-09-20 13:46:24 -0700124 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700125#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700126 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700127 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700128 pF2l = F2L;
129 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700130 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700131 pGet32Static = Field::Get32StaticFromCode;
132 pSet32Static = Field::Set32StaticFromCode;
133 pGet64Static = Field::Get64StaticFromCode;
134 pSet64Static = Field::Set64StaticFromCode;
135 pGetObjStatic = Field::GetObjStaticFromCode;
136 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700137 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700138 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee991e3ac2011-09-29 15:44:22 -0700139 pInstanceofNonTrivialFromCode = Class::IsAssignableFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700140 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700141 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700142 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700143 pFindNativeMethod = FindNativeMethod;
144 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbeece302932011-10-04 14:32:18 -0700145 pResolveStringFromCode = ResolveStringFromCode;
buzbee99f27232011-10-05 12:56:36 -0700146 pObjectInit = ObjectInitFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700147 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700148}
149
Brian Carlstrom78128a62011-09-15 17:21:19 -0700150void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700151 Thread* self = reinterpret_cast<Thread*>(arg);
152 Runtime* runtime = Runtime::Current();
153
154 self->Attach(runtime);
155
Elliott Hughes038a8062011-09-18 14:12:41 -0700156 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700157 if (thread_name != NULL) {
158 SetThreadName(thread_name->ToModifiedUtf8().c_str());
159 }
160
161 // Wait until it's safe to start running code. (There may have been a suspend-all
162 // in progress while we were starting up.)
163 runtime->GetThreadList()->WaitForGo();
164
165 // TODO: say "hi" to the debugger.
166 //if (gDvm.debuggerConnected) {
167 // dvmDbgPostThreadStart(self);
168 //}
169
170 // Invoke the 'run' method of our java.lang.Thread.
171 CHECK(self->peer_ != NULL);
172 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700173 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700174 m->Invoke(self, receiver, NULL, NULL);
175
176 // Detach.
177 runtime->GetThreadList()->Unregister();
178
Carl Shapirob5573532011-07-12 18:22:59 -0700179 return NULL;
180}
181
Elliott Hughes93e74e82011-09-13 11:07:03 -0700182void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700183 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700184}
185
Elliott Hughes01158d72011-09-19 19:47:10 -0700186Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
187 Object* thread = Decode<Object*>(env, java_thread);
188 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
189}
190
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700191size_t FixStackSize(size_t stack_size) {
192 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700193 if (stack_size == 0) {
194 stack_size = Runtime::Current()->GetDefaultStackSize();
195 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700196
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700197 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
198 if (stack_size < PTHREAD_STACK_MIN) {
199 stack_size = PTHREAD_STACK_MIN;
200 }
201
202 // It's likely that callers are trying to ensure they have at least a certain amount of
203 // stack space, so we should add our reserved space on top of what they requested, rather
204 // than implicitly take it away from them.
205 stack_size += Thread::kStackOverflowReservedBytes;
206
207 // Some systems require the stack size to be a multiple of the system page size, so round up.
208 stack_size = RoundUp(stack_size, kPageSize);
209
210 return stack_size;
211}
212
213void Thread::Create(Object* peer, size_t stack_size) {
214 CHECK(peer != NULL);
215
216 stack_size = FixStackSize(stack_size);
217
Elliott Hughes93e74e82011-09-13 11:07:03 -0700218 Thread* native_thread = new Thread;
219 native_thread->peer_ = peer;
220
221 // Thread.start is synchronized, so we know that vmData is 0,
222 // and know that we're not racing to assign it.
223 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700224
225 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700226 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
227 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
228 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
229 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
230 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700231
232 // Let the child know when it's safe to start running.
233 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700234}
235
Elliott Hughes93e74e82011-09-13 11:07:03 -0700236void Thread::Attach(const Runtime* runtime) {
237 InitCpu();
238 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700239
Elliott Hughes93e74e82011-09-13 11:07:03 -0700240 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700241
Elliott Hughes93e74e82011-09-13 11:07:03 -0700242 tid_ = ::art::GetTid();
243 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700244
Elliott Hughes93e74e82011-09-13 11:07:03 -0700245 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700246
Elliott Hughes8d768a92011-09-14 16:35:25 -0700247 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700248
Elliott Hughes93e74e82011-09-13 11:07:03 -0700249 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700250
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700251 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700252}
253
254Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
255 Thread* self = new Thread;
256 self->Attach(runtime);
257
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700258 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700259
260 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700261
262 // If we're the main thread, ClassLinker won't be created until after we're attached,
263 // so that thread needs a two-stage attach. Regular threads don't need this hack.
264 if (self->thin_lock_id_ != ThreadList::kMainId) {
265 self->CreatePeer(name, as_daemon);
266 }
267
268 return self;
269}
270
Elliott Hughesd369bb72011-09-12 14:41:14 -0700271jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
272 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
273 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
274 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
275 // This will be null in the compiler (and tests), but never in a running system.
276 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
277 return thread_group;
278}
279
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700280void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700281 JNIEnv* env = jni_env_;
282
Elliott Hughesd369bb72011-09-12 14:41:14 -0700283 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
284 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700285 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700286 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700287 jboolean thread_is_daemon = as_daemon;
288
289 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700290 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700291
Elliott Hughes8daa0922011-09-11 13:46:25 -0700292 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700293 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700294 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700295
296 // Because we mostly run without code available (in the compiler, in tests), we
297 // manually assign the fields the constructor should have set.
298 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700299 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
300 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
301 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
302 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700303}
304
Elliott Hughesbe759c62011-09-08 19:38:21 -0700305void Thread::InitStackHwm() {
306 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700307 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700308
Ian Rogers932746a2011-09-22 18:57:50 -0700309 void* temp_stack_base;
310 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
311 __FUNCTION__);
312 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700313
Ian Rogers932746a2011-09-22 18:57:50 -0700314 if (stack_size_ <= kStackOverflowReservedBytes) {
315 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700316 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700317
Ian Rogers932746a2011-09-22 18:57:50 -0700318 // Set stack_end_ to the bottom of the stack saving space of stack overflows
319 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700320
321 // Sanity check.
322 int stack_variable;
323 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700324
Elliott Hughes8d768a92011-09-14 16:35:25 -0700325 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700326}
327
Elliott Hughesa0957642011-09-02 14:27:33 -0700328void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700329 DumpState(os);
330 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700331}
332
Elliott Hughesd92bec42011-09-02 17:04:36 -0700333std::string GetSchedulerGroup(pid_t tid) {
334 // /proc/<pid>/group looks like this:
335 // 2:devices:/
336 // 1:cpuacct,cpu:/
337 // We want the third field from the line whose second field contains the "cpu" token.
338 std::string cgroup_file;
339 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
340 return "";
341 }
342 std::vector<std::string> cgroup_lines;
343 Split(cgroup_file, '\n', cgroup_lines);
344 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
345 std::vector<std::string> cgroup_fields;
346 Split(cgroup_lines[i], ':', cgroup_fields);
347 std::vector<std::string> cgroups;
348 Split(cgroup_fields[1], ',', cgroups);
349 for (size_t i = 0; i < cgroups.size(); ++i) {
350 if (cgroups[i] == "cpu") {
351 return cgroup_fields[2].substr(1); // Skip the leading slash.
352 }
353 }
354 }
355 return "";
356}
357
358void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700359 std::string thread_name("<native thread without managed peer>");
360 std::string group_name;
361 int priority;
362 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700363
Elliott Hughesd369bb72011-09-12 14:41:14 -0700364 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700365 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700366 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700367 priority = gThread_priority->GetInt(peer_);
368 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700369
Elliott Hughes038a8062011-09-18 14:12:41 -0700370 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700371 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700372 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700373 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
374 }
375 } else {
376 // 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 -0700377 std::string stats;
378 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
379 size_t start = stats.find('(') + 1;
380 size_t end = stats.find(')') - start;
381 thread_name = stats.substr(start, end);
382 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700383 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700384 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700385
386 int policy;
387 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700388 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700389
390 std::string scheduler_group(GetSchedulerGroup(GetTid()));
391 if (scheduler_group.empty()) {
392 scheduler_group = "default";
393 }
394
Elliott Hughesd92bec42011-09-02 17:04:36 -0700395 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700396 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700397 os << " daemon";
398 }
399 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700400 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700401 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700402
Elliott Hughesd92bec42011-09-02 17:04:36 -0700403 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700404 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700405 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700406 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700407 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700408 << " self=" << reinterpret_cast<const void*>(this) << "\n";
409 os << " | sysTid=" << GetTid()
410 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
411 << " sched=" << policy << "/" << sp.sched_priority
412 << " cgrp=" << scheduler_group
413 << " handle=" << GetImpl() << "\n";
414
415 // Grab the scheduler stats for this thread.
416 std::string scheduler_stats;
417 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
418 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
419 } else {
420 scheduler_stats = "0 0 0";
421 }
422
423 int utime = 0;
424 int stime = 0;
425 int task_cpu = 0;
426 std::string stats;
427 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
428 // Skip the command, which may contain spaces.
429 stats = stats.substr(stats.find(')') + 2);
430 // Extract the three fields we care about.
431 std::vector<std::string> fields;
432 Split(stats, ' ', fields);
433 utime = strtoull(fields[11].c_str(), NULL, 10);
434 stime = strtoull(fields[12].c_str(), NULL, 10);
435 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
436 }
437
438 os << " | schedstat=( " << scheduler_stats << " )"
439 << " utm=" << utime
440 << " stm=" << stime
441 << " core=" << task_cpu
442 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
443}
444
Elliott Hughesd369bb72011-09-12 14:41:14 -0700445struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700446 StackDumpVisitor(std::ostream& os, const Thread* thread)
447 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700448 }
449
Ian Rogersbdb03912011-09-14 00:55:44 -0700450 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700451 }
452
Ian Rogersbdb03912011-09-14 00:55:44 -0700453 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700454 if (!frame.HasMethod()) {
455 return;
456 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700457
458 Method* m = frame.GetMethod();
459 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700460 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700461 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
462
463 os << " at " << PrettyMethod(m, false);
464 if (m->IsNative()) {
465 os << "(Native method)";
466 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700467 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700468 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
469 }
470 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700471
472 if (frame_count++ == 0) {
473 Monitor::DescribeWait(os, thread);
474 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700475 }
476
477 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700478 const Thread* thread;
479 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700480};
481
Elliott Hughesd92bec42011-09-02 17:04:36 -0700482void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700483 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700484 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700485}
486
Elliott Hughes8d768a92011-09-14 16:35:25 -0700487Thread::State Thread::SetState(Thread::State new_state) {
488 Thread::State old_state = state_;
489 if (old_state == new_state) {
490 return old_state;
491 }
492
493 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
494 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
495
496 if (new_state == Thread::kRunnable) {
497 /*
498 * Change our status to Thread::kRunnable. The transition requires
499 * that we check for pending suspension, because the VM considers
500 * us to be "asleep" in all other states, and another thread could
501 * be performing a GC now.
502 *
503 * The order of operations is very significant here. One way to
504 * do this wrong is:
505 *
506 * GCing thread Our thread (in kNative)
507 * ------------ ----------------------
508 * check suspend count (== 0)
509 * SuspendAllThreads()
510 * grab suspend-count lock
511 * increment all suspend counts
512 * release suspend-count lock
513 * check thread state (== kNative)
514 * all are suspended, begin GC
515 * set state to kRunnable
516 * (continue executing)
517 *
518 * We can correct this by grabbing the suspend-count lock and
519 * performing both of our operations (check suspend count, set
520 * state) while holding it, now we need to grab a mutex on every
521 * transition to kRunnable.
522 *
523 * What we do instead is change the order of operations so that
524 * the transition to kRunnable happens first. If we then detect
525 * that the suspend count is nonzero, we switch to kSuspended.
526 *
527 * Appropriate compiler and memory barriers are required to ensure
528 * that the operations are observed in the expected order.
529 *
530 * This does create a small window of opportunity where a GC in
531 * progress could observe what appears to be a running thread (if
532 * it happens to look between when we set to kRunnable and when we
533 * switch to kSuspended). At worst this only affects assertions
534 * and thread logging. (We could work around it with some sort
535 * of intermediate "pre-running" state that is generally treated
536 * as equivalent to running, but that doesn't seem worthwhile.)
537 *
538 * We can also solve this by combining the "status" and "suspend
539 * count" fields into a single 32-bit value. This trades the
540 * store/load barrier on transition to kRunnable for an atomic RMW
541 * op on all transitions and all suspend count updates (also, all
542 * accesses to status or the thread count require bit-fiddling).
543 * It also eliminates the brief transition through kRunnable when
544 * the thread is supposed to be suspended. This is possibly faster
545 * on SMP and slightly more correct, but less convenient.
546 */
547 android_atomic_acquire_store(new_state, addr);
548 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
549 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
550 }
551 } else {
552 /*
553 * Not changing to Thread::kRunnable. No additional work required.
554 *
555 * We use a releasing store to ensure that, if we were runnable,
556 * any updates we previously made to objects on the managed heap
557 * will be observed before the state change.
558 */
559 android_atomic_release_store(new_state, addr);
560 }
561
562 return old_state;
563}
564
565void Thread::WaitUntilSuspended() {
566 // TODO: dalvik dropped the waiting thread's priority after a while.
567 // TODO: dalvik timed out and aborted.
568 useconds_t delay = 0;
569 while (GetState() == Thread::kRunnable) {
570 useconds_t new_delay = delay * 2;
571 CHECK_GE(new_delay, delay);
572 delay = new_delay;
573 if (delay == 0) {
574 sched_yield();
575 delay = 10000;
576 } else {
577 usleep(delay);
578 }
579 }
580}
581
Elliott Hughesbe759c62011-09-08 19:38:21 -0700582void Thread::ThreadExitCallback(void* arg) {
583 Thread* self = reinterpret_cast<Thread*>(arg);
584 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700585}
586
Elliott Hughesbe759c62011-09-08 19:38:21 -0700587void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700588 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700589 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700590
591 // Double-check the TLS slot allocation.
592 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700593 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700594 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700595}
Carl Shapirob5573532011-07-12 18:22:59 -0700596
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700597// TODO: make more accessible?
598Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
599 Class* c = class_linker->FindPrimitiveClass(descriptor);
600 CHECK(c != NULL) << descriptor;
601 return c;
602}
603
604// TODO: make more accessible?
605Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
606 Class* c = class_linker->FindSystemClass(descriptor);
607 CHECK(c != NULL) << descriptor;
608 return c;
609}
610
611// TODO: make more accessible?
612Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
613 Field* f = c->FindDeclaredInstanceField(name, type);
614 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
615 return f;
616}
617
618// TODO: make more accessible?
619Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
620 Method* m = c->FindVirtualMethod(name, signature);
621 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
622 return m;
623}
624
Elliott Hughes038a8062011-09-18 14:12:41 -0700625void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700626 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
627 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700628
629 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
630 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
631 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
632 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
633 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
634 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
635 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
636 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
637
638 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
639 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
640 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
641 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
642 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
643 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
644 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
645 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
646 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
647
648 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
649 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
650 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
651 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700652
653 // Finish attaching the main thread.
654 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700655}
656
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700657void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700658 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700659}
660
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700661uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
662 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
663 return ThreadList::kInvalidId;
664 }
665 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
666 if (managed_thread == NULL) {
667 return ThreadList::kInvalidId;
668 }
669 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
670 Thread* thread = reinterpret_cast<Thread*>(vmData);
671 if (thread == NULL) {
672 return ThreadList::kInvalidId;
673 }
674 return thread->GetThinLockId();
675}
676
Elliott Hughesdcc24742011-09-07 14:02:44 -0700677Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700678 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700679 top_of_managed_stack_(),
680 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700681 wait_mutex_(new Mutex("Thread wait mutex")),
682 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700683 wait_monitor_(NULL),
684 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700685 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700686 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700687 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700688 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700689 native_to_managed_record_(NULL),
690 top_sirt_(NULL),
691 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700692 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700693 self_(NULL),
694 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700695 exception_(NULL),
696 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700697 class_loader_override_(NULL),
698 long_jump_context_(NULL) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700699 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700700}
701
Elliott Hughes02b48d12011-09-07 17:15:51 -0700702void MonitorExitVisitor(const Object* object, void*) {
703 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700704 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700705}
706
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700707Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700708 SetState(Thread::kRunnable);
709
Elliott Hughes02b48d12011-09-07 17:15:51 -0700710 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700711 if (jni_env_ != NULL) {
712 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
713 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700714
Elliott Hughes93e74e82011-09-13 11:07:03 -0700715 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700716 Object* group = gThread_group->GetObject(peer_);
717
718 // Handle any pending exception.
719 if (IsExceptionPending()) {
720 // Get and clear the exception.
721 Object* exception = GetException();
722 ClearException();
723
724 // If the thread has its own handler, use that.
725 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
726 if (handler == NULL) {
727 // Otherwise use the thread group's default handler.
728 handler = group;
729 }
730
731 // Call the handler.
732 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
733 Object* args[2];
734 args[0] = peer_;
735 args[1] = exception;
736 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
737
738 // If the handler threw, clear that exception too.
739 ClearException();
740 }
741
742 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700743 // group can be null if we're in the compiler or a test.
744 if (group != NULL) {
745 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
746 Object* args = peer_;
747 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
748 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700749
750 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700751 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700752
Elliott Hughes29f27422011-09-18 16:02:18 -0700753 // TODO: say "bye" to the debugger.
754 //if (gDvm.debuggerConnected) {
755 // dvmDbgPostThreadDeath(self);
756 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700757
Elliott Hughes29f27422011-09-18 16:02:18 -0700758 // Thread.join() is implemented as an Object.wait() on the Thread.lock
759 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700760 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700761 Object* lock = gThread_lock->GetObject(peer_);
762 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700763 if (lock != NULL) {
764 lock->MonitorEnter(self);
765 lock->NotifyAll();
766 lock->MonitorExit(self);
767 }
768 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700769
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700770 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700771 jni_env_ = NULL;
772
773 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700774
775 delete wait_cond_;
776 delete wait_mutex_;
777
778 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700779}
780
Ian Rogers408f79a2011-08-23 18:22:33 -0700781size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700782 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700783 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700784 count += cur->NumberOfReferences();
785 }
786 return count;
787}
788
Ian Rogers408f79a2011-08-23 18:22:33 -0700789bool Thread::SirtContains(jobject obj) {
790 Object** sirt_entry = reinterpret_cast<Object**>(obj);
791 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700792 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700793 // A SIRT should always have a jobject/jclass as a native method is passed
794 // in a this pointer or a class
795 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700796 if ((&cur->References()[0] <= sirt_entry) &&
797 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700798 return true;
799 }
800 }
801 return false;
802}
803
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700804void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
805 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
806 size_t num_refs = cur->NumberOfReferences();
807 for (size_t j = 0; j < num_refs; j++) {
808 visitor(cur->References()[j], arg);
809 }
810 }
811}
812
Ian Rogers67375ac2011-09-14 00:55:44 -0700813void Thread::PopSirt() {
814 CHECK(top_sirt_ != NULL);
815 top_sirt_ = top_sirt_->Link();
816}
817
Ian Rogers408f79a2011-08-23 18:22:33 -0700818Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700819 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700820 if (obj == NULL) {
821 return NULL;
822 }
823 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
824 IndirectRefKind kind = GetIndirectRefKind(ref);
825 Object* result;
826 switch (kind) {
827 case kLocal:
828 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700829 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700830 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700831 break;
832 }
833 case kGlobal:
834 {
835 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
836 IndirectReferenceTable& globals = vm->globals;
837 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700838 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700839 break;
840 }
841 case kWeakGlobal:
842 {
843 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
844 IndirectReferenceTable& weak_globals = vm->weak_globals;
845 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700846 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700847 if (result == kClearedJniWeakGlobal) {
848 // This is a special case where it's okay to return NULL.
849 return NULL;
850 }
851 break;
852 }
853 case kSirtOrInvalid:
854 default:
855 // TODO: make stack indirect reference table lookup more efficient
856 // Check if this is a local reference in the SIRT
857 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700858 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700859 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700860 // Assume an invalid local reference is actually a direct pointer.
861 result = reinterpret_cast<Object*>(obj);
862 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700863 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700864 }
865 }
866
867 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700868 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
869 JniAbort(NULL);
870 } else {
871 if (result != kInvalidIndirectRefObject) {
872 Heap::VerifyObject(result);
873 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700874 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700875 return result;
876}
877
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700878class CountStackDepthVisitor : public Thread::StackVisitor {
879 public:
Elliott Hughes29f27422011-09-18 16:02:18 -0700880 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700881
Elliott Hughes29f27422011-09-18 16:02:18 -0700882 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
883 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -0700884 // Note we also skip the frame if it doesn't have a method (namely the callee
885 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -0700886 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -0700887 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700888 skipping_ = false;
889 }
890 if (!skipping_) {
891 ++depth_;
892 } else {
893 ++skip_depth_;
894 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700895 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700896
897 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700898 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700899 }
900
Elliott Hughes29f27422011-09-18 16:02:18 -0700901 int GetSkipDepth() const {
902 return skip_depth_;
903 }
904
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700905 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700906 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -0700907 uint32_t skip_depth_;
908 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700909};
910
Ian Rogersaaa20802011-09-11 21:47:37 -0700911class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700912 public:
Elliott Hughes29f27422011-09-18 16:02:18 -0700913 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
914 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700915 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -0700916 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -0700917 // Register a local reference as IntArray::Alloc may trigger GC
918 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
919 pc_trace_ = IntArray::Alloc(depth);
920#ifdef MOVING_GARBAGE_COLLECTOR
921 // Re-read after potential GC
922 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
923#endif
924 // Save PC trace in last element of method trace, also places it into the
925 // object graph.
926 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700927 }
928
Ian Rogersaaa20802011-09-11 21:47:37 -0700929 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700930
Ian Rogersbdb03912011-09-14 00:55:44 -0700931 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700932 if (skip_depth_ > 0) {
933 skip_depth_--;
934 return;
935 }
Ian Rogersaaa20802011-09-11 21:47:37 -0700936 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -0700937 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -0700938 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700939 }
940
Ian Rogersaaa20802011-09-11 21:47:37 -0700941 jobject GetInternalStackTrace() const {
942 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700943 }
944
945 private:
Elliott Hughes29f27422011-09-18 16:02:18 -0700946 // How many more frames to skip.
947 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -0700948 // Current position down stack trace
949 uint32_t count_;
950 // Array of return PC values
951 IntArray* pc_trace_;
952 // An array of the methods on the stack, the last entry is a reference to the
953 // PC trace
954 ObjectArray<Object>* method_trace_;
955 // Local indirect reference table entry for method trace
956 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700957};
958
Ian Rogersaaa20802011-09-11 21:47:37 -0700959void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700960 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -0700961 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700962 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
963 // CHECK(native_to_managed_record_ != NULL);
964 NativeToManagedRecord* record = native_to_managed_record_;
965
Ian Rogersbdb03912011-09-14 00:55:44 -0700966 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700967 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700968 DCHECK(frame.GetMethod()->IsWithinCode(pc));
969 visitor->VisitFrame(frame, pc);
970 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700971 }
972 if (record == NULL) {
973 break;
974 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700975 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -0700976 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -0700977 pc = record->last_top_of_managed_stack_pc_;
978 record = record->link_;
979 }
980}
981
Ian Rogers67375ac2011-09-14 00:55:44 -0700982void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700983 Frame frame = GetTopOfStack();
984 uintptr_t pc = top_of_managed_stack_pc_;
985
986 if (frame.GetSP() != 0) {
987 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700988 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -0700989 visitor->VisitFrame(frame, pc);
990 pc = frame.GetReturnPC();
991 }
Ian Rogers67375ac2011-09-14 00:55:44 -0700992 if (include_upcall) {
993 visitor->VisitFrame(frame, pc);
994 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700995 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700996}
997
Elliott Hughes01158d72011-09-19 19:47:10 -0700998jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700999 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001000 CountStackDepthVisitor count_visitor;
1001 WalkStack(&count_visitor);
1002 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001003 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001004
Ian Rogersaaa20802011-09-11 21:47:37 -07001005 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001006 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001007
1008 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001009 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001010 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001011
Ian Rogersaaa20802011-09-11 21:47:37 -07001012 return build_trace_visitor.GetInternalStackTrace();
1013}
1014
Elliott Hughes01158d72011-09-19 19:47:10 -07001015jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1016 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001017 // Transition into runnable state to work on Object*/Array*
1018 ScopedJniThreadState ts(env);
1019
1020 // Decode the internal stack trace into the depth, method trace and PC trace
1021 ObjectArray<Object>* method_trace =
1022 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1023 int32_t depth = method_trace->GetLength()-1;
1024 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1025
1026 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1027
Elliott Hughes01158d72011-09-19 19:47:10 -07001028 jobjectArray result;
1029 ObjectArray<StackTraceElement>* java_traces;
1030 if (output_array != NULL) {
1031 // Reuse the array we were given.
1032 result = output_array;
1033 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1034 output_array));
1035 // ...adjusting the number of frames we'll write to not exceed the array length.
1036 depth = std::min(depth, java_traces->GetLength());
1037 } else {
1038 // Create java_trace array and place in local reference table
1039 java_traces = class_linker->AllocStackTraceElementArray(depth);
1040 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1041 }
1042
1043 if (stack_depth != NULL) {
1044 *stack_depth = depth;
1045 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001046
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001047 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001048 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1049 Method* method = down_cast<Method*>(method_trace->Get(i));
1050 uint32_t native_pc = pc_trace->Get(i);
1051 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001052 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001053 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001054
Ian Rogersaaa20802011-09-11 21:47:37 -07001055 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001056 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001057 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001058 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001059 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001060 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001061 method->ToDexPC(native_pc)));
1062#ifdef MOVING_GARBAGE_COLLECTOR
1063 // Re-read after potential GC
1064 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1065 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1066 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1067#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001068 java_traces->Set(i, obj);
1069 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001070 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001071}
1072
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001073void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001074 va_list args;
1075 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001076 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001077 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001078}
1079
1080void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1081 std::string msg;
1082 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001083 ThrowNewException(exception_class_descriptor, msg.c_str());
1084}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001085
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001086void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001087 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001089 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001090 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001091 descriptor.erase(descriptor.length() - 1);
1092
1093 JNIEnv* env = GetJniEnv();
1094 jclass exception_class = env->FindClass(descriptor.c_str());
1095 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001096 int rc = env->ThrowNew(exception_class, msg);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001097 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001098 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001099}
1100
Elliott Hughes79082e32011-08-25 12:07:32 -07001101void Thread::ThrowOutOfMemoryError() {
1102 UNIMPLEMENTED(FATAL);
1103}
1104
Ian Rogersbdb03912011-09-14 00:55:44 -07001105class CatchBlockStackVisitor : public Thread::StackVisitor {
1106 public:
1107 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001108 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1109#ifndef NDEBUG
1110 handler_pc_ = 0xEBADC0DE;
1111 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1112#endif
1113 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001114
Ian Rogersbdb03912011-09-14 00:55:44 -07001115 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1116 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001117 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001118 if (method == NULL) {
1119 // This is the upcall, we remember the frame and last_pc so that we may
1120 // long jump to them
1121 handler_pc_ = pc;
1122 handler_frame_ = fr;
1123 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001124 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001125 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001126 if (method->IsPhony()) {
1127 // ignore callee save method
1128 } else if (method->IsNative()) {
1129 native_method_count_++;
1130 } else {
1131 // Move the PC back 2 bytes as a call will frequently terminate the
1132 // decoding of a particular instruction and we want to make sure we
1133 // get the Dex PC of the instruction with the call and not the
1134 // instruction following.
1135 pc -= 2;
1136 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001137 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001138 if (dex_pc != DexFile::kDexNoIndex) {
1139 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1140 if (found_dex_pc != DexFile::kDexNoIndex) {
1141 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001142 handler_pc_ = method->ToNativePC(found_dex_pc);
1143 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001144 }
1145 }
1146 if (!found_) {
1147 // Caller may be handler, fill in callee saves in context
1148 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001149 }
1150 }
1151 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001152
1153 // Did we find a catch block yet?
1154 bool found_;
1155 // The type of the exception catch block to find
1156 Class* to_find_;
1157 // Frame with found handler or last frame if no handler found
1158 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001159 // PC to branch to for the handler
1160 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001161 // Context that will be the target of the long jump
1162 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001163 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1164 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001165};
1166
Ian Rogersff1ed472011-09-20 13:46:24 -07001167void Thread::DeliverException() {
1168 Throwable *exception = GetException(); // Set exception on thread
1169 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001170
1171 Context* long_jump_context = GetLongJumpContext();
1172 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001173 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001174
Ian Rogers67375ac2011-09-14 00:55:44 -07001175 // Pop any SIRT
1176 if (catch_finder.native_method_count_ == 1) {
1177 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001178 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001179 // We only expect the stack crawl to have passed 1 native method as it's terminated
1180 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001181 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001182 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001183 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1184 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001185 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001186}
1187
Ian Rogersbdb03912011-09-14 00:55:44 -07001188Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001189 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001190 if (result == NULL) {
1191 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001192 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001193 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001194 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001195}
1196
Elliott Hughes5f791332011-09-15 17:45:30 -07001197bool Thread::HoldsLock(Object* object) {
1198 if (object == NULL) {
1199 return false;
1200 }
1201 return object->GetLockOwner() == thin_lock_id_;
1202}
1203
Elliott Hughes038a8062011-09-18 14:12:41 -07001204bool Thread::IsDaemon() {
1205 return gThread_daemon->GetBoolean(peer_);
1206}
1207
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001208// blx is 2-byte in Thumb2. Need to offset PC back to a call site.
1209static const int kThumb2InstSize = 2;
1210
Ian Rogersd6b1f612011-09-27 13:38:14 -07001211class ReferenceMapVisitor : public Thread::StackVisitor {
1212 public:
1213 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1214 context_(context), root_visitor_(root_visitor), arg_(arg) {
1215 }
1216
1217 void VisitFrame(const Frame& frame, uintptr_t pc) {
1218 Method* m = frame.GetMethod();
Ian Rogersd6b1f612011-09-27 13:38:14 -07001219
1220 // Process register map (which native and callee save methods don't have)
1221 if (!m->IsNative() && !m->IsPhony()) {
1222 UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
1223
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001224 const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(
1225 map.get(),
1226 m->ToDexPC(pc -kThumb2InstSize));
1227
1228 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
1229 << "@ PC: " << m->ToDexPC(pc - kThumb2InstSize);
1230
Ian Rogersd6b1f612011-09-27 13:38:14 -07001231 CHECK(reg_bitmap != NULL);
1232 ShortArray* vmap = m->GetVMapTable();
1233 // For all dex registers
1234 for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1235 // Does this register hold a reference?
1236 if (TestBitmap(reg, reg_bitmap)) {
1237 // Is the reference in the context or on the stack?
1238 bool in_context = false;
1239 int vmap_offset = -1;
1240 // TODO: take advantage of the registers being ordered
1241 for (int i = 0; i < vmap->GetLength(); i++) {
1242 if (vmap->Get(i) == reg) {
1243 in_context = true;
1244 vmap_offset = i;
1245 break;
1246 }
1247 }
1248 Object* ref;
1249 if (in_context) {
1250 // Compute the register we need to load from the context
1251 uint32_t spill_mask = m->GetCoreSpillMask();
1252 uint32_t reg = 0;
1253 for (int i = 0; i < vmap_offset; i++) {
1254 while ((spill_mask & 1) == 0) {
1255 CHECK_NE(spill_mask, 0u);
1256 spill_mask >>= 1;
1257 reg++;
1258 }
1259 }
1260 ref = reinterpret_cast<Object*>(context_->GetGPR(reg));
1261 } else {
1262 ref = reinterpret_cast<Object*>(frame.GetVReg(m ,reg));
1263 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001264 if (ref != NULL) {
1265 root_visitor_(ref, arg_);
1266 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001267 }
1268 }
1269 }
1270 context_->FillCalleeSaves(frame);
1271 }
1272
1273 private:
1274 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1275 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1276 }
1277
1278 // Context used to build up picture of callee saves
1279 Context* context_;
1280 // Call-back when we visit a root
1281 Heap::RootVisitor* root_visitor_;
1282 // Argument to call-back
1283 void* arg_;
1284};
1285
1286void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001287 if (exception_ != NULL) {
1288 visitor(exception_, arg);
1289 }
1290 if (peer_ != NULL) {
1291 visitor(peer_, arg);
1292 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001293 jni_env_->locals.VisitRoots(visitor, arg);
1294 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001295
1296 SirtVisitRoots(visitor, arg);
1297
Ian Rogersd6b1f612011-09-27 13:38:14 -07001298 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1299 // delivery.
1300 Context* context = GetLongJumpContext();
1301 // Visit roots on this thread's stack
1302 ReferenceMapVisitor mapper(context, visitor, arg);
1303 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001304}
1305
Ian Rogersb033c752011-07-20 12:22:35 -07001306static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001307 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001308 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001309 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001310 "Blocked",
1311 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001312 "Initializing",
1313 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001314 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001315 "VmWait",
1316 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001317};
1318std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001319 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001320 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1321 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001322 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001323 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001324 }
1325 return os;
1326}
1327
Elliott Hughes330304d2011-08-12 14:28:05 -07001328std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1329 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001330 << ",pthread_t=" << thread.GetImpl()
1331 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001332 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001333 << ",state=" << thread.GetState()
1334 << ",peer=" << thread.GetPeer()
1335 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001336 return os;
1337}
1338
Elliott Hughes8daa0922011-09-11 13:46:25 -07001339} // namespace art