blob: 6eac92bbffa244cfceca3026e09a93b793eacc2f [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 Rogers408f79a2011-08-23 18:22:33 -070031#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070032#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070033#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070035#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070036#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070037#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070038#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070039
40namespace art {
41
42pthread_key_t Thread::pthread_key_self_;
43
Elliott Hughes29f27422011-09-18 16:02:18 -070044static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070045static Field* gThread_daemon = NULL;
46static Field* gThread_group = NULL;
47static Field* gThread_lock = NULL;
48static Field* gThread_name = NULL;
49static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070050static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070051static Field* gThread_vmData = NULL;
52static Field* gThreadGroup_name = NULL;
53static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070054static Method* gThreadGroup_removeThread = NULL;
55static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070056
buzbee4a3164f2011-09-03 11:25:10 -070057// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070058void DebugMe(Method* method, uint32_t info) {
buzbee4a3164f2011-09-03 11:25:10 -070059 LOG(INFO) << "DebugMe";
60 if (method != NULL)
61 LOG(INFO) << PrettyMethod(method);
62 LOG(INFO) << "Info: " << info;
63}
64
Ian Rogersbdb03912011-09-14 00:55:44 -070065} // namespace art
66
67// Called by generated call to throw an exception
Ian Rogers67375ac2011-09-14 00:55:44 -070068extern "C" void artDeliverExceptionHelper(art::Throwable* exception,
69 art::Thread* thread,
70 art::Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070071 /*
72 * exception may be NULL, in which case this routine should
73 * throw NPE. NOTE: this is a convenience for generated code,
74 * which previously did the null check inline and constructed
75 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070076 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070077 */
Ian Rogers67375ac2011-09-14 00:55:44 -070078 // Place a special frame at the TOS that will save all callee saves
Ian Rogersbdb03912011-09-14 00:55:44 -070079 *sp = thread->CalleeSaveMethod();
80 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070081 if (exception == NULL) {
82 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
83 exception = thread->GetException();
84 }
Ian Rogersbdb03912011-09-14 00:55:44 -070085 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070086}
87
Ian Rogers9651f422011-09-19 20:26:07 -070088// Called by generated call to throw a NPE exception
89extern "C" void artThrowNullPointerExceptionFromCodeHelper(art::Thread* thread,
90 art::Method** sp) {
91 // Place a special frame at the TOS that will save all callee saves
92 *sp = thread->CalleeSaveMethod();
93 thread->SetTopOfStack(sp, 0);
94 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
95 art::Throwable* exception = thread->GetException();
96 thread->DeliverException(exception);
97}
98
99// Called by generated call to throw an arithmetic divide by zero exception
100extern "C" void artThrowDivZeroFromCodeHelper(art::Thread* thread,
101 art::Method** sp) {
102 // Place a special frame at the TOS that will save all callee saves
103 *sp = thread->CalleeSaveMethod();
104 thread->SetTopOfStack(sp, 0);
105 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
106 art::Throwable* exception = thread->GetException();
107 thread->DeliverException(exception);
108}
109
110// Called by generated call to throw an arithmetic divide by zero exception
111extern "C" void artThrowArrayBoundsFromCodeHelper(int index, int limit,
112 art::Thread* thread,
113 art::Method** sp) {
114 // Place a special frame at the TOS that will save all callee saves
115 *sp = thread->CalleeSaveMethod();
116 thread->SetTopOfStack(sp, 0);
117 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
118 "length=%d; index=%d", limit, index);
119 art::Throwable* exception = thread->GetException();
120 thread->DeliverException(exception);
121}
122
Ian Rogersbdb03912011-09-14 00:55:44 -0700123namespace art {
124
buzbee1b4c8592011-08-31 10:43:51 -0700125// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700126Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700127 /*
128 * Should initialize & fix up method->dex_cache_resolved_types_[].
129 * Returns initialized type. Does not return normally if an exception
130 * is thrown, but instead initiates the catch. Should be similar to
131 * ClassLinker::InitializeStaticStorageFromCode.
132 */
133 UNIMPLEMENTED(FATAL);
134 return NULL;
135}
136
buzbee561227c2011-09-02 15:28:19 -0700137// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700138void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700139 /*
140 * Slow-path handler on invoke virtual method path in which
141 * base method is unresolved at compile-time. Doesn't need to
142 * return anything - just either ensure that
143 * method->dex_cache_resolved_methods_(method_idx) != NULL or
144 * throw and unwind. The caller will restart call sequence
145 * from the beginning.
146 */
147}
148
buzbee1da522d2011-09-04 11:22:20 -0700149// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700150Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700151 /*
152 * Just a wrapper around Array::AllocFromCode() that additionally
153 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
154 */
155 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
156 return Array::AllocFromCode(type_index, method, component_count);
157}
158
buzbee2a475e72011-09-07 17:19:17 -0700159// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700160void CheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700161 DCHECK(a->IsClass());
162 DCHECK(b->IsClass());
163 if (b->IsAssignableFrom(a)) {
164 return;
165 }
166 UNIMPLEMENTED(FATAL);
buzbee2a475e72011-09-07 17:19:17 -0700167}
168
Elliott Hughesd369bb72011-09-12 14:41:14 -0700169void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700170 // TODO: throw and unwind if lock not held
171 // TODO: throw and unwind on NPE
172 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700173}
174
Elliott Hughesd369bb72011-09-12 14:41:14 -0700175void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700176 obj->MonitorEnter(thread);
177 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700178}
179
Elliott Hughesd369bb72011-09-12 14:41:14 -0700180void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700181 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700182}
183
buzbeecefd1872011-09-09 09:59:52 -0700184// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700185void StackOverflowFromCode(Method* method) {
Brian Carlstromfa3baf72011-09-18 15:44:15 -0700186 Thread::Current()->SetTopOfStackPC(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
Brian Carlstrom16192862011-09-12 17:50:06 -0700187 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700188 //NOTE: to save code space, this handler needs to look up its own Thread*
189 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700190}
191
buzbee5ade1d22011-09-09 14:44:52 -0700192// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700193void ThrowNullPointerFromCode() {
Brian Carlstromfa3baf72011-09-18 15:44:15 -0700194 Thread::Current()->SetTopOfStackPC(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700195 Thread::Current()->Dump(std::cerr);
196 //NOTE: to save code space, this handler must look up caller's Method*
197 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700198}
199
200// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700201void ThrowDivZeroFromCode() {
202 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700203}
204
205// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700206void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
207 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700208}
209
210// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700211void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700212 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
213 " ref: " << ref;
214}
215
216// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700217void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700218 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
219}
220
221// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700222void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700223 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
224}
225
226// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700227void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700228 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
229}
230
231// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700232void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700233 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
234}
235
Ian Rogersbdb03912011-09-14 00:55:44 -0700236void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
237 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
238 "abstract method \"%s\"",
239 PrettyMethod(method).c_str());
240 thread->DeliverException(thread->GetException());
241}
242
243
buzbee5ade1d22011-09-09 14:44:52 -0700244/*
245 * Temporary placeholder. Should include run-time checks for size
246 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
247 * As with other new "FromCode" routines, this should return to the caller
248 * only if no exception has been thrown.
249 *
250 * NOTE: When dealing with a raw dex file, the data to be copied uses
251 * little-endian ordering. Require that oat2dex do any required swapping
252 * so this routine can get by with a memcpy().
253 *
254 * Format of the data:
255 * ushort ident = 0x0300 magic value
256 * ushort width width of each element in the table
257 * uint size number of elements in the table
258 * ubyte data[size*width] table of data values (may contain a single-byte
259 * padding at the end)
260 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700261void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700262 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
263 uint32_t size_in_bytes = size * table[1];
264 if (static_cast<int32_t>(size) > array->GetLength()) {
265 ThrowArrayBoundsFromCode(array->GetLength(), size);
266 }
267 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
268 (char*)&table[4], size_in_bytes);
269}
270
Brian Carlstrom16192862011-09-12 17:50:06 -0700271/*
272 * TODO: placeholder for a method that can be called by the
273 * invoke-interface trampoline to unwind and handle exception. The
274 * trampoline will arrange it so that the caller appears to be the
275 * callsite of the failed invoke-interface. See comments in
276 * runtime_support.S
277 */
278extern "C" void artFailedInvokeInterface() {
279 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
280}
281
282// See comments in runtime_support.S
283extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
284 Object* this_object , Method* caller_method)
285{
286 if (this_object == NULL) {
287 ThrowNullPointerFromCode();
288 }
289 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
290 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
291 if (interface_method == NULL) {
292 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
293 }
294 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
295 const void* code = method->GetCode();
296
297 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
298 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
299 uint64_t result = ((code_uint << 32) | method_uint);
300 return result;
301}
302
buzbee5ade1d22011-09-09 14:44:52 -0700303// TODO: move to more appropriate location
304/*
305 * Float/double conversion requires clamping to min and max of integer form. If
306 * target doesn't support this normally, use these.
307 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700308int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700309 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
310 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
311 if (d >= kMaxLong)
312 return (int64_t)0x7fffffffffffffffULL;
313 else if (d <= kMinLong)
314 return (int64_t)0x8000000000000000ULL;
315 else if (d != d) // NaN case
316 return 0;
317 else
318 return (int64_t)d;
319}
320
Elliott Hughesd369bb72011-09-12 14:41:14 -0700321int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700322 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
323 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
324 if (f >= kMaxLong)
325 return (int64_t)0x7fffffffffffffffULL;
326 else if (f <= kMinLong)
327 return (int64_t)0x8000000000000000ULL;
328 else if (f != f) // NaN case
329 return 0;
330 else
331 return (int64_t)f;
332}
333
Brian Carlstrom16192862011-09-12 17:50:06 -0700334// Return value helper for jobject return types
335static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
336 return thread->DecodeJObject(obj);
337}
338
buzbee3ea4ec52011-08-22 17:37:19 -0700339void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700340#if defined(__arm__)
341 pShlLong = art_shl_long;
342 pShrLong = art_shr_long;
343 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700344 pIdiv = __aeabi_idiv;
345 pIdivmod = __aeabi_idivmod;
346 pI2f = __aeabi_i2f;
347 pF2iz = __aeabi_f2iz;
348 pD2f = __aeabi_d2f;
349 pF2d = __aeabi_f2d;
350 pD2iz = __aeabi_d2iz;
351 pL2f = __aeabi_l2f;
352 pL2d = __aeabi_l2d;
353 pFadd = __aeabi_fadd;
354 pFsub = __aeabi_fsub;
355 pFdiv = __aeabi_fdiv;
356 pFmul = __aeabi_fmul;
357 pFmodf = fmodf;
358 pDadd = __aeabi_dadd;
359 pDsub = __aeabi_dsub;
360 pDdiv = __aeabi_ddiv;
361 pDmul = __aeabi_dmul;
362 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700363 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700364 pLmul = __aeabi_lmul;
Ian Rogers9651f422011-09-19 20:26:07 -0700365 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
366 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
367 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700368 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700369#endif
Ian Rogers67375ac2011-09-14 00:55:44 -0700370 pDeliverException = art_deliver_exception;
buzbeec396efc2011-09-11 09:36:41 -0700371 pF2l = F2L;
372 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700373 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700374 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700375 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700376 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700377 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700378 pGet32Static = Field::Get32StaticFromCode;
379 pSet32Static = Field::Set32StaticFromCode;
380 pGet64Static = Field::Get64StaticFromCode;
381 pSet64Static = Field::Set64StaticFromCode;
382 pGetObjStatic = Field::GetObjStaticFromCode;
383 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700384 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700385 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700386 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700387 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700388 pInstanceofNonTrivialFromCode = Object::InstanceOf;
389 pCheckCastFromCode = CheckCastFromCode;
390 pLockObjectFromCode = LockObjectFromCode;
391 pUnlockObjectFromCode = UnlockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700392 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700393 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700394 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700395 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
396 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
397 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
398 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
399 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700400 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700401 pFindNativeMethod = FindNativeMethod;
402 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700403 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700404}
405
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700406void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700407 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
408 DCHECK_NE(frame_size, 0u);
409 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700410 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700411 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700413 DCHECK(*sp_ == NULL ||
414 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700415}
416
Ian Rogers90865722011-09-19 11:11:44 -0700417bool Frame::HasMethod() const {
418 return GetMethod() != NULL && (!GetMethod()->IsPhony());
419}
420
Ian Rogersbdb03912011-09-14 00:55:44 -0700421uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700422 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700423 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700424 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700425}
426
Ian Rogersbdb03912011-09-14 00:55:44 -0700427uintptr_t Frame::LoadCalleeSave(int num) const {
428 // Callee saves are held at the top of the frame
429 Method* method = GetMethod();
430 DCHECK(method != NULL);
431 size_t frame_size = method->GetFrameSizeInBytes();
432 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
433 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700434#if defined(__i386__)
435 save_addr -= kPointerSize; // account for return address
436#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700437 return *reinterpret_cast<uintptr_t*>(save_addr);
438}
439
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700441 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700442 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700444}
445
Brian Carlstrom78128a62011-09-15 17:21:19 -0700446void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700447 Thread* self = reinterpret_cast<Thread*>(arg);
448 Runtime* runtime = Runtime::Current();
449
450 self->Attach(runtime);
451
Elliott Hughes038a8062011-09-18 14:12:41 -0700452 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700453 if (thread_name != NULL) {
454 SetThreadName(thread_name->ToModifiedUtf8().c_str());
455 }
456
457 // Wait until it's safe to start running code. (There may have been a suspend-all
458 // in progress while we were starting up.)
459 runtime->GetThreadList()->WaitForGo();
460
461 // TODO: say "hi" to the debugger.
462 //if (gDvm.debuggerConnected) {
463 // dvmDbgPostThreadStart(self);
464 //}
465
466 // Invoke the 'run' method of our java.lang.Thread.
467 CHECK(self->peer_ != NULL);
468 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700469 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700470 m->Invoke(self, receiver, NULL, NULL);
471
472 // Detach.
473 runtime->GetThreadList()->Unregister();
474
Carl Shapirob5573532011-07-12 18:22:59 -0700475 return NULL;
476}
477
Elliott Hughes93e74e82011-09-13 11:07:03 -0700478void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700479 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700480}
481
Elliott Hughesd369bb72011-09-12 14:41:14 -0700482void Thread::Create(Object* peer, size_t stack_size) {
483 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700484
Elliott Hughesd369bb72011-09-12 14:41:14 -0700485 if (stack_size == 0) {
486 stack_size = Runtime::Current()->GetDefaultStackSize();
487 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700488
Elliott Hughes93e74e82011-09-13 11:07:03 -0700489 Thread* native_thread = new Thread;
490 native_thread->peer_ = peer;
491
492 // Thread.start is synchronized, so we know that vmData is 0,
493 // and know that we're not racing to assign it.
494 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700495
496 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700497 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
498 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
499 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
500 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
501 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700502
503 // Let the child know when it's safe to start running.
504 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700505}
506
Elliott Hughes93e74e82011-09-13 11:07:03 -0700507void Thread::Attach(const Runtime* runtime) {
508 InitCpu();
509 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700510
Elliott Hughes93e74e82011-09-13 11:07:03 -0700511 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700512
Elliott Hughes93e74e82011-09-13 11:07:03 -0700513 tid_ = ::art::GetTid();
514 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700515
Elliott Hughes93e74e82011-09-13 11:07:03 -0700516 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700517
Elliott Hughes8d768a92011-09-14 16:35:25 -0700518 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700519
Elliott Hughes93e74e82011-09-13 11:07:03 -0700520 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700521
Elliott Hughes93e74e82011-09-13 11:07:03 -0700522 runtime->GetThreadList()->Register(this);
523}
524
525Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
526 Thread* self = new Thread;
527 self->Attach(runtime);
528
529 self->SetState(Thread::kRunnable);
530
531 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700532
533 // If we're the main thread, ClassLinker won't be created until after we're attached,
534 // so that thread needs a two-stage attach. Regular threads don't need this hack.
535 if (self->thin_lock_id_ != ThreadList::kMainId) {
536 self->CreatePeer(name, as_daemon);
537 }
538
539 return self;
540}
541
Elliott Hughesd369bb72011-09-12 14:41:14 -0700542jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
543 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
544 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
545 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
546 // This will be null in the compiler (and tests), but never in a running system.
547 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
548 return thread_group;
549}
550
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700551void Thread::CreatePeer(const char* name, bool as_daemon) {
552 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
553
554 JNIEnv* env = jni_env_;
555
Elliott Hughesd369bb72011-09-12 14:41:14 -0700556 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
557 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700558 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700559 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700560 jboolean thread_is_daemon = as_daemon;
561
562 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700563 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700564
Elliott Hughes8daa0922011-09-11 13:46:25 -0700565 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700566
567 // Because we mostly run without code available (in the compiler, in tests), we
568 // manually assign the fields the constructor should have set.
569 // TODO: lose this.
570 jfieldID fid;
571 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
572 env->SetObjectField(peer, fid, thread_group);
573 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
574 env->SetObjectField(peer, fid, thread_name);
575 fid = env->GetFieldID(c, "priority", "I");
576 env->SetIntField(peer, fid, thread_priority);
577 fid = env->GetFieldID(c, "daemon", "Z");
578 env->SetBooleanField(peer, fid, thread_is_daemon);
579
580 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700581}
582
Elliott Hughesbe759c62011-09-08 19:38:21 -0700583void Thread::InitStackHwm() {
584 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700585 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700586
Elliott Hughesbe759c62011-09-08 19:38:21 -0700587 void* stack_base;
588 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700589 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700590
Elliott Hughesbe759c62011-09-08 19:38:21 -0700591 if (stack_size <= kStackOverflowReservedBytes) {
592 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
593 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700594
595 // stack_base is the "lowest addressable byte" of the stack.
596 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
597 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700598 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700599
600 // Sanity check.
601 int stack_variable;
602 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700603
Elliott Hughes8d768a92011-09-14 16:35:25 -0700604 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700605}
606
Elliott Hughesa0957642011-09-02 14:27:33 -0700607void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700608 DumpState(os);
609 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700610}
611
Elliott Hughesd92bec42011-09-02 17:04:36 -0700612std::string GetSchedulerGroup(pid_t tid) {
613 // /proc/<pid>/group looks like this:
614 // 2:devices:/
615 // 1:cpuacct,cpu:/
616 // We want the third field from the line whose second field contains the "cpu" token.
617 std::string cgroup_file;
618 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
619 return "";
620 }
621 std::vector<std::string> cgroup_lines;
622 Split(cgroup_file, '\n', cgroup_lines);
623 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
624 std::vector<std::string> cgroup_fields;
625 Split(cgroup_lines[i], ':', cgroup_fields);
626 std::vector<std::string> cgroups;
627 Split(cgroup_fields[1], ',', cgroups);
628 for (size_t i = 0; i < cgroups.size(); ++i) {
629 if (cgroups[i] == "cpu") {
630 return cgroup_fields[2].substr(1); // Skip the leading slash.
631 }
632 }
633 }
634 return "";
635}
636
637void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700638 std::string thread_name("<native thread without managed peer>");
639 std::string group_name;
640 int priority;
641 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700642
Elliott Hughesd369bb72011-09-12 14:41:14 -0700643 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700644 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700645 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700646 priority = gThread_priority->GetInt(peer_);
647 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700648
Elliott Hughes038a8062011-09-18 14:12:41 -0700649 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700650 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700651 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700652 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
653 }
654 } else {
655 // 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 -0700656 std::string stats;
657 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
658 size_t start = stats.find('(') + 1;
659 size_t end = stats.find(')') - start;
660 thread_name = stats.substr(start, end);
661 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700662 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700663 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700664
665 int policy;
666 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700667 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700668
669 std::string scheduler_group(GetSchedulerGroup(GetTid()));
670 if (scheduler_group.empty()) {
671 scheduler_group = "default";
672 }
673
Elliott Hughesd92bec42011-09-02 17:04:36 -0700674 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700675 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700676 os << " daemon";
677 }
678 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700679 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700680 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700681
Elliott Hughesd92bec42011-09-02 17:04:36 -0700682 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700683 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700684 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700685 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700686 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700687 << " self=" << reinterpret_cast<const void*>(this) << "\n";
688 os << " | sysTid=" << GetTid()
689 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
690 << " sched=" << policy << "/" << sp.sched_priority
691 << " cgrp=" << scheduler_group
692 << " handle=" << GetImpl() << "\n";
693
694 // Grab the scheduler stats for this thread.
695 std::string scheduler_stats;
696 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
697 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
698 } else {
699 scheduler_stats = "0 0 0";
700 }
701
702 int utime = 0;
703 int stime = 0;
704 int task_cpu = 0;
705 std::string stats;
706 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
707 // Skip the command, which may contain spaces.
708 stats = stats.substr(stats.find(')') + 2);
709 // Extract the three fields we care about.
710 std::vector<std::string> fields;
711 Split(stats, ' ', fields);
712 utime = strtoull(fields[11].c_str(), NULL, 10);
713 stime = strtoull(fields[12].c_str(), NULL, 10);
714 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
715 }
716
717 os << " | schedstat=( " << scheduler_stats << " )"
718 << " utm=" << utime
719 << " stm=" << stime
720 << " core=" << task_cpu
721 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
722}
723
Elliott Hughesd369bb72011-09-12 14:41:14 -0700724struct StackDumpVisitor : public Thread::StackVisitor {
725 StackDumpVisitor(std::ostream& os) : os(os) {
726 }
727
Ian Rogersbdb03912011-09-14 00:55:44 -0700728 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700729 }
730
Ian Rogersbdb03912011-09-14 00:55:44 -0700731 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700732 if (!frame.HasMethod()) {
733 return;
734 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700735 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
736
737 Method* m = frame.GetMethod();
738 Class* c = m->GetDeclaringClass();
739 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
740
741 os << " at " << PrettyMethod(m, false);
742 if (m->IsNative()) {
743 os << "(Native method)";
744 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700745 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700746 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
747 }
748 os << "\n";
749 }
750
751 std::ostream& os;
752};
753
Elliott Hughesd92bec42011-09-02 17:04:36 -0700754void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700755 StackDumpVisitor dumper(os);
756 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700757}
758
Elliott Hughes8d768a92011-09-14 16:35:25 -0700759Thread::State Thread::SetState(Thread::State new_state) {
760 Thread::State old_state = state_;
761 if (old_state == new_state) {
762 return old_state;
763 }
764
765 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
766 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
767
768 if (new_state == Thread::kRunnable) {
769 /*
770 * Change our status to Thread::kRunnable. The transition requires
771 * that we check for pending suspension, because the VM considers
772 * us to be "asleep" in all other states, and another thread could
773 * be performing a GC now.
774 *
775 * The order of operations is very significant here. One way to
776 * do this wrong is:
777 *
778 * GCing thread Our thread (in kNative)
779 * ------------ ----------------------
780 * check suspend count (== 0)
781 * SuspendAllThreads()
782 * grab suspend-count lock
783 * increment all suspend counts
784 * release suspend-count lock
785 * check thread state (== kNative)
786 * all are suspended, begin GC
787 * set state to kRunnable
788 * (continue executing)
789 *
790 * We can correct this by grabbing the suspend-count lock and
791 * performing both of our operations (check suspend count, set
792 * state) while holding it, now we need to grab a mutex on every
793 * transition to kRunnable.
794 *
795 * What we do instead is change the order of operations so that
796 * the transition to kRunnable happens first. If we then detect
797 * that the suspend count is nonzero, we switch to kSuspended.
798 *
799 * Appropriate compiler and memory barriers are required to ensure
800 * that the operations are observed in the expected order.
801 *
802 * This does create a small window of opportunity where a GC in
803 * progress could observe what appears to be a running thread (if
804 * it happens to look between when we set to kRunnable and when we
805 * switch to kSuspended). At worst this only affects assertions
806 * and thread logging. (We could work around it with some sort
807 * of intermediate "pre-running" state that is generally treated
808 * as equivalent to running, but that doesn't seem worthwhile.)
809 *
810 * We can also solve this by combining the "status" and "suspend
811 * count" fields into a single 32-bit value. This trades the
812 * store/load barrier on transition to kRunnable for an atomic RMW
813 * op on all transitions and all suspend count updates (also, all
814 * accesses to status or the thread count require bit-fiddling).
815 * It also eliminates the brief transition through kRunnable when
816 * the thread is supposed to be suspended. This is possibly faster
817 * on SMP and slightly more correct, but less convenient.
818 */
819 android_atomic_acquire_store(new_state, addr);
820 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
821 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
822 }
823 } else {
824 /*
825 * Not changing to Thread::kRunnable. No additional work required.
826 *
827 * We use a releasing store to ensure that, if we were runnable,
828 * any updates we previously made to objects on the managed heap
829 * will be observed before the state change.
830 */
831 android_atomic_release_store(new_state, addr);
832 }
833
834 return old_state;
835}
836
837void Thread::WaitUntilSuspended() {
838 // TODO: dalvik dropped the waiting thread's priority after a while.
839 // TODO: dalvik timed out and aborted.
840 useconds_t delay = 0;
841 while (GetState() == Thread::kRunnable) {
842 useconds_t new_delay = delay * 2;
843 CHECK_GE(new_delay, delay);
844 delay = new_delay;
845 if (delay == 0) {
846 sched_yield();
847 delay = 10000;
848 } else {
849 usleep(delay);
850 }
851 }
852}
853
Elliott Hughesbe759c62011-09-08 19:38:21 -0700854void Thread::ThreadExitCallback(void* arg) {
855 Thread* self = reinterpret_cast<Thread*>(arg);
856 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700857}
858
Elliott Hughesbe759c62011-09-08 19:38:21 -0700859void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700860 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700861 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700862
863 // Double-check the TLS slot allocation.
864 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700865 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700866 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700867}
Carl Shapirob5573532011-07-12 18:22:59 -0700868
Elliott Hughes038a8062011-09-18 14:12:41 -0700869void Thread::FinishStartup() {
870 // Finish attaching the main thread.
871 Thread::Current()->CreatePeer("main", false);
872
873 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
874 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
875 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
876 Class* int_class = class_linker->FindPrimitiveClass('I');
877 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
878 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
879 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
880 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
Elliott Hughes29f27422011-09-18 16:02:18 -0700881 Class* UncaughtExceptionHandler_class = class_linker->FindSystemClass("Ljava/lang/Thread$UncaughtExceptionHandler;");
882 gThrowable = class_linker->FindSystemClass("Ljava/lang/Throwable;");
Elliott Hughes038a8062011-09-18 14:12:41 -0700883 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
884 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
885 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
886 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
887 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
888 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
Elliott Hughes29f27422011-09-18 16:02:18 -0700889 gThread_uncaughtHandler = Thread_class->FindDeclaredInstanceField("uncaughtHandler", UncaughtExceptionHandler_class);
Elliott Hughes038a8062011-09-18 14:12:41 -0700890 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
891 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Elliott Hughes29f27422011-09-18 16:02:18 -0700892 gThreadGroup_removeThread = ThreadGroup_class->FindVirtualMethod("removeThread", "(Ljava/lang/Thread;)V");
893 gUncaughtExceptionHandler_uncaughtException =
894 UncaughtExceptionHandler_class->FindVirtualMethod("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Carl Shapirob5573532011-07-12 18:22:59 -0700895}
896
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700897void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700898 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700899}
900
Elliott Hughesdcc24742011-09-07 14:02:44 -0700901Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700902 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700903 wait_mutex_(new Mutex("Thread wait mutex")),
904 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700905 wait_monitor_(NULL),
906 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700907 wait_next_(NULL),
908 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700909 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700910 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700911 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700912 native_to_managed_record_(NULL),
913 top_sirt_(NULL),
914 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700915 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700916 self_(NULL),
917 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700918 exception_(NULL),
919 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700920 class_loader_override_(NULL),
921 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700922}
923
Elliott Hughes02b48d12011-09-07 17:15:51 -0700924void MonitorExitVisitor(const Object* object, void*) {
925 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700926 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700927}
928
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700929Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700930 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700931 if (jni_env_ != NULL) {
932 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
933 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700934
Elliott Hughes93e74e82011-09-13 11:07:03 -0700935 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700936 Object* group = gThread_group->GetObject(peer_);
937
938 // Handle any pending exception.
939 if (IsExceptionPending()) {
940 // Get and clear the exception.
941 Object* exception = GetException();
942 ClearException();
943
944 // If the thread has its own handler, use that.
945 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
946 if (handler == NULL) {
947 // Otherwise use the thread group's default handler.
948 handler = group;
949 }
950
951 // Call the handler.
952 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
953 Object* args[2];
954 args[0] = peer_;
955 args[1] = exception;
956 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
957
958 // If the handler threw, clear that exception too.
959 ClearException();
960 }
961
962 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700963 // group can be null if we're in the compiler or a test.
964 if (group != NULL) {
965 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
966 Object* args = peer_;
967 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
968 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700969
970 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700971 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700972
Elliott Hughes29f27422011-09-18 16:02:18 -0700973 // TODO: say "bye" to the debugger.
974 //if (gDvm.debuggerConnected) {
975 // dvmDbgPostThreadDeath(self);
976 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700977
Elliott Hughes29f27422011-09-18 16:02:18 -0700978 // Thread.join() is implemented as an Object.wait() on the Thread.lock
979 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700980 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700981 Object* lock = gThread_lock->GetObject(peer_);
982 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700983 if (lock != NULL) {
984 lock->MonitorEnter(self);
985 lock->NotifyAll();
986 lock->MonitorExit(self);
987 }
988 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700989
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700990 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700991 jni_env_ = NULL;
992
993 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700994
995 delete wait_cond_;
996 delete wait_mutex_;
997
998 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700999}
1000
Ian Rogers408f79a2011-08-23 18:22:33 -07001001size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001002 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001003 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001004 count += cur->NumberOfReferences();
1005 }
1006 return count;
1007}
1008
Ian Rogers408f79a2011-08-23 18:22:33 -07001009bool Thread::SirtContains(jobject obj) {
1010 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1011 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001012 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001013 // A SIRT should always have a jobject/jclass as a native method is passed
1014 // in a this pointer or a class
1015 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001016 if ((&cur->References()[0] <= sirt_entry) &&
1017 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001018 return true;
1019 }
1020 }
1021 return false;
1022}
1023
Ian Rogers67375ac2011-09-14 00:55:44 -07001024void Thread::PopSirt() {
1025 CHECK(top_sirt_ != NULL);
1026 top_sirt_ = top_sirt_->Link();
1027}
1028
Ian Rogers408f79a2011-08-23 18:22:33 -07001029Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001030 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001031 if (obj == NULL) {
1032 return NULL;
1033 }
1034 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1035 IndirectRefKind kind = GetIndirectRefKind(ref);
1036 Object* result;
1037 switch (kind) {
1038 case kLocal:
1039 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001040 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001041 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001042 break;
1043 }
1044 case kGlobal:
1045 {
1046 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1047 IndirectReferenceTable& globals = vm->globals;
1048 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001049 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001050 break;
1051 }
1052 case kWeakGlobal:
1053 {
1054 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1055 IndirectReferenceTable& weak_globals = vm->weak_globals;
1056 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001057 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001058 if (result == kClearedJniWeakGlobal) {
1059 // This is a special case where it's okay to return NULL.
1060 return NULL;
1061 }
1062 break;
1063 }
1064 case kSirtOrInvalid:
1065 default:
1066 // TODO: make stack indirect reference table lookup more efficient
1067 // Check if this is a local reference in the SIRT
1068 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001069 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001070 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001071 // Assume an invalid local reference is actually a direct pointer.
1072 result = reinterpret_cast<Object*>(obj);
1073 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001074 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001075 }
1076 }
1077
1078 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001079 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1080 JniAbort(NULL);
1081 } else {
1082 if (result != kInvalidIndirectRefObject) {
1083 Heap::VerifyObject(result);
1084 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001085 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001086 return result;
1087}
1088
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001089class CountStackDepthVisitor : public Thread::StackVisitor {
1090 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001091 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001092
Elliott Hughes29f27422011-09-18 16:02:18 -07001093 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1094 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001095 // Note we also skip the frame if it doesn't have a method (namely the callee
1096 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001097 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001098 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001099 skipping_ = false;
1100 }
1101 if (!skipping_) {
1102 ++depth_;
1103 } else {
1104 ++skip_depth_;
1105 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001106 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001107
1108 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001109 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001110 }
1111
Elliott Hughes29f27422011-09-18 16:02:18 -07001112 int GetSkipDepth() const {
1113 return skip_depth_;
1114 }
1115
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001116 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001117 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001118 uint32_t skip_depth_;
1119 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001120};
1121
Ian Rogersaaa20802011-09-11 21:47:37 -07001122class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001123 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001124 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1125 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001126 // Allocate method trace with an extra slot that will hold the PC trace
1127 method_trace_ = Runtime::Current()->GetClassLinker()->
1128 AllocObjectArray<Object>(depth + 1);
1129 // Register a local reference as IntArray::Alloc may trigger GC
1130 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1131 pc_trace_ = IntArray::Alloc(depth);
1132#ifdef MOVING_GARBAGE_COLLECTOR
1133 // Re-read after potential GC
1134 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1135#endif
1136 // Save PC trace in last element of method trace, also places it into the
1137 // object graph.
1138 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001139 }
1140
Ian Rogersaaa20802011-09-11 21:47:37 -07001141 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001142
Ian Rogersbdb03912011-09-14 00:55:44 -07001143 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001144 if (skip_depth_ > 0) {
1145 skip_depth_--;
1146 return;
1147 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001148 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001149 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001150 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001151 }
1152
Ian Rogersaaa20802011-09-11 21:47:37 -07001153 jobject GetInternalStackTrace() const {
1154 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001155 }
1156
1157 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001158 // How many more frames to skip.
1159 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001160 // Current position down stack trace
1161 uint32_t count_;
1162 // Array of return PC values
1163 IntArray* pc_trace_;
1164 // An array of the methods on the stack, the last entry is a reference to the
1165 // PC trace
1166 ObjectArray<Object>* method_trace_;
1167 // Local indirect reference table entry for method trace
1168 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001169};
1170
Ian Rogersaaa20802011-09-11 21:47:37 -07001171void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001172 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001173 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001174 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1175 // CHECK(native_to_managed_record_ != NULL);
1176 NativeToManagedRecord* record = native_to_managed_record_;
1177
Ian Rogersbdb03912011-09-14 00:55:44 -07001178 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001179 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001180 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1181 visitor->VisitFrame(frame, pc);
1182 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001183 }
1184 if (record == NULL) {
1185 break;
1186 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001187 // last_tos should return Frame instead of sp?
1188 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1189 pc = record->last_top_of_managed_stack_pc_;
1190 record = record->link_;
1191 }
1192}
1193
Ian Rogers67375ac2011-09-14 00:55:44 -07001194void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001195 Frame frame = GetTopOfStack();
1196 uintptr_t pc = top_of_managed_stack_pc_;
1197
1198 if (frame.GetSP() != 0) {
1199 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001200 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001201 visitor->VisitFrame(frame, pc);
1202 pc = frame.GetReturnPC();
1203 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001204 if (include_upcall) {
1205 visitor->VisitFrame(frame, pc);
1206 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001207 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001208}
1209
Ian Rogersaaa20802011-09-11 21:47:37 -07001210jobject Thread::CreateInternalStackTrace() const {
1211 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001212 CountStackDepthVisitor count_visitor;
1213 WalkStack(&count_visitor);
1214 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001215 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001216
Ian Rogersaaa20802011-09-11 21:47:37 -07001217 // Transition into runnable state to work on Object*/Array*
1218 ScopedJniThreadState ts(jni_env_);
1219
1220 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001221 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001222 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001223
Ian Rogersaaa20802011-09-11 21:47:37 -07001224 return build_trace_visitor.GetInternalStackTrace();
1225}
1226
1227jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1228 JNIEnv* env) {
1229 // Transition into runnable state to work on Object*/Array*
1230 ScopedJniThreadState ts(env);
1231
1232 // Decode the internal stack trace into the depth, method trace and PC trace
1233 ObjectArray<Object>* method_trace =
1234 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1235 int32_t depth = method_trace->GetLength()-1;
1236 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1237
1238 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1239
1240 // Create java_trace array and place in local reference table
1241 ObjectArray<StackTraceElement>* java_traces =
1242 class_linker->AllocStackTraceElementArray(depth);
1243 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001244
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001245 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001246 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1247 Method* method = down_cast<Method*>(method_trace->Get(i));
1248 uint32_t native_pc = pc_trace->Get(i);
1249 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001250 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001251 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001252
Ian Rogersaaa20802011-09-11 21:47:37 -07001253 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001254 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001255 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001256 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001257 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001258 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001259 method->ToDexPC(native_pc)));
1260#ifdef MOVING_GARBAGE_COLLECTOR
1261 // Re-read after potential GC
1262 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1263 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1264 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1265#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001266 java_traces->Set(i, obj);
1267 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001268 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001269}
1270
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001271void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001272 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001273 va_list args;
1274 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001275 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001276 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001277
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001278 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001279 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001280 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001281 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001282 descriptor.erase(descriptor.length() - 1);
1283
1284 JNIEnv* env = GetJniEnv();
1285 jclass exception_class = env->FindClass(descriptor.c_str());
1286 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1287 int rc = env->ThrowNew(exception_class, msg.c_str());
1288 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001289}
1290
Elliott Hughes79082e32011-08-25 12:07:32 -07001291void Thread::ThrowOutOfMemoryError() {
1292 UNIMPLEMENTED(FATAL);
1293}
1294
Ian Rogersbdb03912011-09-14 00:55:44 -07001295Method* Thread::CalleeSaveMethod() const {
1296 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001297 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001298#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001299 method->SetCode(NULL, art::kThumb2, NULL);
1300 method->SetFrameSizeInBytes(64);
1301 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001302 method->SetCoreSpillMask((1 << art::arm::R1) |
1303 (1 << art::arm::R2) |
1304 (1 << art::arm::R3) |
1305 (1 << art::arm::R4) |
1306 (1 << art::arm::R5) |
1307 (1 << art::arm::R6) |
1308 (1 << art::arm::R7) |
1309 (1 << art::arm::R8) |
1310 (1 << art::arm::R9) |
1311 (1 << art::arm::R10) |
1312 (1 << art::arm::R11) |
1313 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001314 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001315#elif defined(__i386__)
1316 method->SetCode(NULL, art::kX86, NULL);
1317 method->SetFrameSizeInBytes(32);
1318 method->SetReturnPcOffsetInBytes(28);
1319 method->SetCoreSpillMask((1 << art::x86::EBX) |
1320 (1 << art::x86::EBP) |
1321 (1 << art::x86::ESI) |
1322 (1 << art::x86::EDI));
1323 method->SetFpSpillMask(0);
1324#else
1325 UNIMPLEMENTED(FATAL);
1326#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001327 return method;
1328}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001329
Ian Rogersbdb03912011-09-14 00:55:44 -07001330class CatchBlockStackVisitor : public Thread::StackVisitor {
1331 public:
1332 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001333 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1334#ifndef NDEBUG
1335 handler_pc_ = 0xEBADC0DE;
1336 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1337#endif
1338 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001339
Ian Rogersbdb03912011-09-14 00:55:44 -07001340 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1341 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001342 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001343 if (method == NULL) {
1344 // This is the upcall, we remember the frame and last_pc so that we may
1345 // long jump to them
1346 handler_pc_ = pc;
1347 handler_frame_ = fr;
1348 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001349 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001350 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001351 if (method->IsPhony()) {
1352 // ignore callee save method
1353 } else if (method->IsNative()) {
1354 native_method_count_++;
1355 } else {
1356 // Move the PC back 2 bytes as a call will frequently terminate the
1357 // decoding of a particular instruction and we want to make sure we
1358 // get the Dex PC of the instruction with the call and not the
1359 // instruction following.
1360 pc -= 2;
1361 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001362 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001363 if (dex_pc != DexFile::kDexNoIndex) {
1364 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1365 if (found_dex_pc != DexFile::kDexNoIndex) {
1366 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001367 handler_pc_ = method->ToNativePC(found_dex_pc);
1368 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001369 }
1370 }
1371 if (!found_) {
1372 // Caller may be handler, fill in callee saves in context
1373 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001374 }
1375 }
1376 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001377
1378 // Did we find a catch block yet?
1379 bool found_;
1380 // The type of the exception catch block to find
1381 Class* to_find_;
1382 // Frame with found handler or last frame if no handler found
1383 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001384 // PC to branch to for the handler
1385 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001386 // Context that will be the target of the long jump
1387 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001388 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1389 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001390};
1391
1392void Thread::DeliverException(Throwable* exception) {
1393 SetException(exception); // Set exception on thread
1394
1395 Context* long_jump_context = GetLongJumpContext();
1396 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001397 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001398
Ian Rogers67375ac2011-09-14 00:55:44 -07001399 // Pop any SIRT
1400 if (catch_finder.native_method_count_ == 1) {
1401 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001402 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001403 // We only expect the stack crawl to have passed 1 native method as it's terminated
1404 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001405 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001406 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001407 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1408 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001409 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001410}
1411
Ian Rogersbdb03912011-09-14 00:55:44 -07001412Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001413 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001414 if (result == NULL) {
1415 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001416 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001417 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001418 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001419}
1420
Elliott Hughes5f791332011-09-15 17:45:30 -07001421bool Thread::HoldsLock(Object* object) {
1422 if (object == NULL) {
1423 return false;
1424 }
1425 return object->GetLockOwner() == thin_lock_id_;
1426}
1427
Elliott Hughes038a8062011-09-18 14:12:41 -07001428bool Thread::IsDaemon() {
1429 return gThread_daemon->GetBoolean(peer_);
1430}
1431
Elliott Hughes410c0c82011-09-01 17:58:25 -07001432void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001433 if (exception_ != NULL) {
1434 visitor(exception_, arg);
1435 }
1436 if (peer_ != NULL) {
1437 visitor(peer_, arg);
1438 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001439 jni_env_->locals.VisitRoots(visitor, arg);
1440 jni_env_->monitors.VisitRoots(visitor, arg);
1441 // visitThreadStack(visitor, thread, arg);
1442 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1443}
1444
Ian Rogersb033c752011-07-20 12:22:35 -07001445static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001446 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001447 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001448 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001449 "Blocked",
1450 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001451 "Initializing",
1452 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001453 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001454 "VmWait",
1455 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001456};
1457std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001458 int int_state = static_cast<int>(state);
1459 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1460 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001461 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001462 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001463 }
1464 return os;
1465}
1466
Elliott Hughes330304d2011-08-12 14:28:05 -07001467std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1468 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001469 << ",pthread_t=" << thread.GetImpl()
1470 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001471 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001472 << ",state=" << thread.GetState()
1473 << ",peer=" << thread.GetPeer()
1474 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001475 return os;
1476}
1477
Elliott Hughes8daa0922011-09-11 13:46:25 -07001478} // namespace art