blob: d86a0c567483b93aaf5f72f2258dc6dee91715cd [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) {
Elliott Hughes01158d72011-09-19 19:47:10 -070059 LOG(INFO) << "DebugMe";
60 if (method != NULL) {
61 LOG(INFO) << PrettyMethod(method);
62 }
63 LOG(INFO) << "Info: " << info;
buzbee4a3164f2011-09-03 11:25:10 -070064}
65
Ian Rogersbdb03912011-09-14 00:55:44 -070066} // namespace art
67
68// Called by generated call to throw an exception
Ian Rogers67375ac2011-09-14 00:55:44 -070069extern "C" void artDeliverExceptionHelper(art::Throwable* exception,
70 art::Thread* thread,
71 art::Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070072 /*
73 * exception may be NULL, in which case this routine should
74 * throw NPE. NOTE: this is a convenience for generated code,
75 * which previously did the null check inline and constructed
76 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070077 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070078 */
Ian Rogers67375ac2011-09-14 00:55:44 -070079 // Place a special frame at the TOS that will save all callee saves
Ian Rogersbdb03912011-09-14 00:55:44 -070080 *sp = thread->CalleeSaveMethod();
81 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070082 if (exception == NULL) {
83 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
84 exception = thread->GetException();
85 }
Ian Rogersbdb03912011-09-14 00:55:44 -070086 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070087}
88
Ian Rogers9651f422011-09-19 20:26:07 -070089// Called by generated call to throw a NPE exception
90extern "C" void artThrowNullPointerExceptionFromCodeHelper(art::Thread* thread,
91 art::Method** sp) {
92 // Place a special frame at the TOS that will save all callee saves
93 *sp = thread->CalleeSaveMethod();
94 thread->SetTopOfStack(sp, 0);
95 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
96 art::Throwable* exception = thread->GetException();
97 thread->DeliverException(exception);
98}
99
100// Called by generated call to throw an arithmetic divide by zero exception
101extern "C" void artThrowDivZeroFromCodeHelper(art::Thread* thread,
102 art::Method** sp) {
103 // Place a special frame at the TOS that will save all callee saves
104 *sp = thread->CalleeSaveMethod();
105 thread->SetTopOfStack(sp, 0);
106 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
107 art::Throwable* exception = thread->GetException();
108 thread->DeliverException(exception);
109}
110
111// Called by generated call to throw an arithmetic divide by zero exception
112extern "C" void artThrowArrayBoundsFromCodeHelper(int index, int limit,
113 art::Thread* thread,
114 art::Method** sp) {
115 // Place a special frame at the TOS that will save all callee saves
116 *sp = thread->CalleeSaveMethod();
117 thread->SetTopOfStack(sp, 0);
118 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
119 "length=%d; index=%d", limit, index);
120 art::Throwable* exception = thread->GetException();
121 thread->DeliverException(exception);
122}
123
Ian Rogersbdb03912011-09-14 00:55:44 -0700124namespace art {
125
buzbee1b4c8592011-08-31 10:43:51 -0700126// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700127Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700128 /*
129 * Should initialize & fix up method->dex_cache_resolved_types_[].
130 * Returns initialized type. Does not return normally if an exception
131 * is thrown, but instead initiates the catch. Should be similar to
132 * ClassLinker::InitializeStaticStorageFromCode.
133 */
134 UNIMPLEMENTED(FATAL);
135 return NULL;
136}
137
buzbee561227c2011-09-02 15:28:19 -0700138// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700139void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700140 /*
141 * Slow-path handler on invoke virtual method path in which
142 * base method is unresolved at compile-time. Doesn't need to
143 * return anything - just either ensure that
144 * method->dex_cache_resolved_methods_(method_idx) != NULL or
145 * throw and unwind. The caller will restart call sequence
146 * from the beginning.
147 */
148}
149
buzbee1da522d2011-09-04 11:22:20 -0700150// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700151Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700152 /*
153 * Just a wrapper around Array::AllocFromCode() that additionally
154 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
155 */
156 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
157 return Array::AllocFromCode(type_index, method, component_count);
158}
159
buzbee2a475e72011-09-07 17:19:17 -0700160// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700161void CheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700162 DCHECK(a->IsClass());
163 DCHECK(b->IsClass());
164 if (b->IsAssignableFrom(a)) {
165 return;
166 }
167 UNIMPLEMENTED(FATAL);
buzbee2a475e72011-09-07 17:19:17 -0700168}
169
Elliott Hughesd369bb72011-09-12 14:41:14 -0700170void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700171 // TODO: throw and unwind if lock not held
172 // TODO: throw and unwind on NPE
173 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700174}
175
Elliott Hughesd369bb72011-09-12 14:41:14 -0700176void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700177 obj->MonitorEnter(thread);
178 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700179}
180
Elliott Hughesd369bb72011-09-12 14:41:14 -0700181void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700182 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700183}
184
buzbeecefd1872011-09-09 09:59:52 -0700185// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700186void StackOverflowFromCode(Method* method) {
Brian Carlstromfa3baf72011-09-18 15:44:15 -0700187 Thread::Current()->SetTopOfStackPC(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
Brian Carlstrom16192862011-09-12 17:50:06 -0700188 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700189 //NOTE: to save code space, this handler needs to look up its own Thread*
190 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700191}
192
buzbee5ade1d22011-09-09 14:44:52 -0700193// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700194void ThrowNullPointerFromCode() {
Brian Carlstromfa3baf72011-09-18 15:44:15 -0700195 Thread::Current()->SetTopOfStackPC(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700196 Thread::Current()->Dump(std::cerr);
197 //NOTE: to save code space, this handler must look up caller's Method*
198 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700199}
200
201// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700202void ThrowDivZeroFromCode() {
203 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700204}
205
206// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700207void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
208 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700209}
210
211// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700212void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700213 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
214 " ref: " << ref;
215}
216
217// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700218void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700219 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
220}
221
222// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700223void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700224 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
225}
226
227// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700228void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700229 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
230}
231
232// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700233void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700234 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
235}
236
Ian Rogersbdb03912011-09-14 00:55:44 -0700237void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
238 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
239 "abstract method \"%s\"",
240 PrettyMethod(method).c_str());
241 thread->DeliverException(thread->GetException());
242}
243
244
buzbee5ade1d22011-09-09 14:44:52 -0700245/*
246 * Temporary placeholder. Should include run-time checks for size
247 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
248 * As with other new "FromCode" routines, this should return to the caller
249 * only if no exception has been thrown.
250 *
251 * NOTE: When dealing with a raw dex file, the data to be copied uses
252 * little-endian ordering. Require that oat2dex do any required swapping
253 * so this routine can get by with a memcpy().
254 *
255 * Format of the data:
256 * ushort ident = 0x0300 magic value
257 * ushort width width of each element in the table
258 * uint size number of elements in the table
259 * ubyte data[size*width] table of data values (may contain a single-byte
260 * padding at the end)
261 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700262void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700263 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
264 uint32_t size_in_bytes = size * table[1];
265 if (static_cast<int32_t>(size) > array->GetLength()) {
266 ThrowArrayBoundsFromCode(array->GetLength(), size);
267 }
268 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
269 (char*)&table[4], size_in_bytes);
270}
271
Brian Carlstrom16192862011-09-12 17:50:06 -0700272/*
273 * TODO: placeholder for a method that can be called by the
274 * invoke-interface trampoline to unwind and handle exception. The
275 * trampoline will arrange it so that the caller appears to be the
276 * callsite of the failed invoke-interface. See comments in
277 * runtime_support.S
278 */
279extern "C" void artFailedInvokeInterface() {
280 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
281}
282
283// See comments in runtime_support.S
284extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
285 Object* this_object , Method* caller_method)
286{
287 if (this_object == NULL) {
288 ThrowNullPointerFromCode();
289 }
290 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
291 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
292 if (interface_method == NULL) {
293 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
294 }
295 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
296 const void* code = method->GetCode();
297
298 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
299 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
300 uint64_t result = ((code_uint << 32) | method_uint);
301 return result;
302}
303
buzbee5ade1d22011-09-09 14:44:52 -0700304// TODO: move to more appropriate location
305/*
306 * Float/double conversion requires clamping to min and max of integer form. If
307 * target doesn't support this normally, use these.
308 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700309int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700310 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
311 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
312 if (d >= kMaxLong)
313 return (int64_t)0x7fffffffffffffffULL;
314 else if (d <= kMinLong)
315 return (int64_t)0x8000000000000000ULL;
316 else if (d != d) // NaN case
317 return 0;
318 else
319 return (int64_t)d;
320}
321
Elliott Hughesd369bb72011-09-12 14:41:14 -0700322int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700323 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
324 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
325 if (f >= kMaxLong)
326 return (int64_t)0x7fffffffffffffffULL;
327 else if (f <= kMinLong)
328 return (int64_t)0x8000000000000000ULL;
329 else if (f != f) // NaN case
330 return 0;
331 else
332 return (int64_t)f;
333}
334
Brian Carlstrom16192862011-09-12 17:50:06 -0700335// Return value helper for jobject return types
336static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
337 return thread->DecodeJObject(obj);
338}
339
buzbee3ea4ec52011-08-22 17:37:19 -0700340void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700341#if defined(__arm__)
342 pShlLong = art_shl_long;
343 pShrLong = art_shr_long;
344 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700345 pIdiv = __aeabi_idiv;
346 pIdivmod = __aeabi_idivmod;
347 pI2f = __aeabi_i2f;
348 pF2iz = __aeabi_f2iz;
349 pD2f = __aeabi_d2f;
350 pF2d = __aeabi_f2d;
351 pD2iz = __aeabi_d2iz;
352 pL2f = __aeabi_l2f;
353 pL2d = __aeabi_l2d;
354 pFadd = __aeabi_fadd;
355 pFsub = __aeabi_fsub;
356 pFdiv = __aeabi_fdiv;
357 pFmul = __aeabi_fmul;
358 pFmodf = fmodf;
359 pDadd = __aeabi_dadd;
360 pDsub = __aeabi_dsub;
361 pDdiv = __aeabi_ddiv;
362 pDmul = __aeabi_dmul;
363 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700364 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700365 pLmul = __aeabi_lmul;
Ian Rogers9651f422011-09-19 20:26:07 -0700366 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
367 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
368 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700369 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700370#endif
Ian Rogers67375ac2011-09-14 00:55:44 -0700371 pDeliverException = art_deliver_exception;
buzbeec396efc2011-09-11 09:36:41 -0700372 pF2l = F2L;
373 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700374 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700375 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700376 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700377 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700378 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700379 pGet32Static = Field::Get32StaticFromCode;
380 pSet32Static = Field::Set32StaticFromCode;
381 pGet64Static = Field::Get64StaticFromCode;
382 pSet64Static = Field::Set64StaticFromCode;
383 pGetObjStatic = Field::GetObjStaticFromCode;
384 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700385 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700386 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700387 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700388 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700389 pInstanceofNonTrivialFromCode = Object::InstanceOf;
390 pCheckCastFromCode = CheckCastFromCode;
391 pLockObjectFromCode = LockObjectFromCode;
392 pUnlockObjectFromCode = UnlockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700393 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700394 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700395 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700396 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
397 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
398 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
399 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
400 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700401 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700402 pFindNativeMethod = FindNativeMethod;
403 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700404 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700405}
406
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700407void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700408 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
409 DCHECK_NE(frame_size, 0u);
410 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700411 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700412 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700414 DCHECK(*sp_ == NULL ||
415 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700416}
417
Ian Rogers90865722011-09-19 11:11:44 -0700418bool Frame::HasMethod() const {
419 return GetMethod() != NULL && (!GetMethod()->IsPhony());
420}
421
Ian Rogersbdb03912011-09-14 00:55:44 -0700422uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700423 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700424 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700425 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700426}
427
Ian Rogersbdb03912011-09-14 00:55:44 -0700428uintptr_t Frame::LoadCalleeSave(int num) const {
429 // Callee saves are held at the top of the frame
430 Method* method = GetMethod();
431 DCHECK(method != NULL);
432 size_t frame_size = method->GetFrameSizeInBytes();
433 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
434 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700435#if defined(__i386__)
436 save_addr -= kPointerSize; // account for return address
437#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700438 return *reinterpret_cast<uintptr_t*>(save_addr);
439}
440
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700442 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700443 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700445}
446
Brian Carlstrom78128a62011-09-15 17:21:19 -0700447void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700448 Thread* self = reinterpret_cast<Thread*>(arg);
449 Runtime* runtime = Runtime::Current();
450
451 self->Attach(runtime);
452
Elliott Hughes038a8062011-09-18 14:12:41 -0700453 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700454 if (thread_name != NULL) {
455 SetThreadName(thread_name->ToModifiedUtf8().c_str());
456 }
457
458 // Wait until it's safe to start running code. (There may have been a suspend-all
459 // in progress while we were starting up.)
460 runtime->GetThreadList()->WaitForGo();
461
462 // TODO: say "hi" to the debugger.
463 //if (gDvm.debuggerConnected) {
464 // dvmDbgPostThreadStart(self);
465 //}
466
467 // Invoke the 'run' method of our java.lang.Thread.
468 CHECK(self->peer_ != NULL);
469 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700470 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700471 m->Invoke(self, receiver, NULL, NULL);
472
473 // Detach.
474 runtime->GetThreadList()->Unregister();
475
Carl Shapirob5573532011-07-12 18:22:59 -0700476 return NULL;
477}
478
Elliott Hughes93e74e82011-09-13 11:07:03 -0700479void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700480 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700481}
482
Elliott Hughes01158d72011-09-19 19:47:10 -0700483Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
484 Object* thread = Decode<Object*>(env, java_thread);
485 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
486}
487
Elliott Hughesd369bb72011-09-12 14:41:14 -0700488void Thread::Create(Object* peer, size_t stack_size) {
489 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700490
Elliott Hughesd369bb72011-09-12 14:41:14 -0700491 if (stack_size == 0) {
492 stack_size = Runtime::Current()->GetDefaultStackSize();
493 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700494
Elliott Hughes93e74e82011-09-13 11:07:03 -0700495 Thread* native_thread = new Thread;
496 native_thread->peer_ = peer;
497
498 // Thread.start is synchronized, so we know that vmData is 0,
499 // and know that we're not racing to assign it.
500 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700501
502 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700503 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
504 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
505 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
506 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
507 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700508
509 // Let the child know when it's safe to start running.
510 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700511}
512
Elliott Hughes93e74e82011-09-13 11:07:03 -0700513void Thread::Attach(const Runtime* runtime) {
514 InitCpu();
515 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700516
Elliott Hughes93e74e82011-09-13 11:07:03 -0700517 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700518
Elliott Hughes93e74e82011-09-13 11:07:03 -0700519 tid_ = ::art::GetTid();
520 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700521
Elliott Hughes93e74e82011-09-13 11:07:03 -0700522 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700523
Elliott Hughes8d768a92011-09-14 16:35:25 -0700524 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700525
Elliott Hughes93e74e82011-09-13 11:07:03 -0700526 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700527
Elliott Hughes93e74e82011-09-13 11:07:03 -0700528 runtime->GetThreadList()->Register(this);
529}
530
531Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
532 Thread* self = new Thread;
533 self->Attach(runtime);
534
535 self->SetState(Thread::kRunnable);
536
537 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700538
539 // If we're the main thread, ClassLinker won't be created until after we're attached,
540 // so that thread needs a two-stage attach. Regular threads don't need this hack.
541 if (self->thin_lock_id_ != ThreadList::kMainId) {
542 self->CreatePeer(name, as_daemon);
543 }
544
545 return self;
546}
547
Elliott Hughesd369bb72011-09-12 14:41:14 -0700548jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
549 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
550 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
551 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
552 // This will be null in the compiler (and tests), but never in a running system.
553 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
554 return thread_group;
555}
556
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700557void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes01158d72011-09-19 19:47:10 -0700558 Thread* self = Thread::Current();
559 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700560
561 JNIEnv* env = jni_env_;
562
Elliott Hughesd369bb72011-09-12 14:41:14 -0700563 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
564 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700565 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700566 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700567 jboolean thread_is_daemon = as_daemon;
568
569 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700570 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700571
Elliott Hughes8daa0922011-09-11 13:46:25 -0700572 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700573 peer_ = DecodeJObject(peer);
574 SetVmData(peer_, self);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700575
576 // Because we mostly run without code available (in the compiler, in tests), we
577 // manually assign the fields the constructor should have set.
578 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700579 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
580 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
581 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
582 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700583}
584
Elliott Hughesbe759c62011-09-08 19:38:21 -0700585void Thread::InitStackHwm() {
586 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700587 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700588
Elliott Hughesbe759c62011-09-08 19:38:21 -0700589 void* stack_base;
590 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700591 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700592
Elliott Hughesbe759c62011-09-08 19:38:21 -0700593 if (stack_size <= kStackOverflowReservedBytes) {
594 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
595 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700596
597 // stack_base is the "lowest addressable byte" of the stack.
598 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
599 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700600 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700601
602 // Sanity check.
603 int stack_variable;
604 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700605
Elliott Hughes8d768a92011-09-14 16:35:25 -0700606 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700607}
608
Elliott Hughesa0957642011-09-02 14:27:33 -0700609void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700610 DumpState(os);
611 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700612}
613
Elliott Hughesd92bec42011-09-02 17:04:36 -0700614std::string GetSchedulerGroup(pid_t tid) {
615 // /proc/<pid>/group looks like this:
616 // 2:devices:/
617 // 1:cpuacct,cpu:/
618 // We want the third field from the line whose second field contains the "cpu" token.
619 std::string cgroup_file;
620 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
621 return "";
622 }
623 std::vector<std::string> cgroup_lines;
624 Split(cgroup_file, '\n', cgroup_lines);
625 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
626 std::vector<std::string> cgroup_fields;
627 Split(cgroup_lines[i], ':', cgroup_fields);
628 std::vector<std::string> cgroups;
629 Split(cgroup_fields[1], ',', cgroups);
630 for (size_t i = 0; i < cgroups.size(); ++i) {
631 if (cgroups[i] == "cpu") {
632 return cgroup_fields[2].substr(1); // Skip the leading slash.
633 }
634 }
635 }
636 return "";
637}
638
639void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700640 std::string thread_name("<native thread without managed peer>");
641 std::string group_name;
642 int priority;
643 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700644
Elliott Hughesd369bb72011-09-12 14:41:14 -0700645 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700646 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700647 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700648 priority = gThread_priority->GetInt(peer_);
649 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700650
Elliott Hughes038a8062011-09-18 14:12:41 -0700651 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700652 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700653 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700654 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
655 }
656 } else {
657 // 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 -0700658 std::string stats;
659 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
660 size_t start = stats.find('(') + 1;
661 size_t end = stats.find(')') - start;
662 thread_name = stats.substr(start, end);
663 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700664 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700665 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700666
667 int policy;
668 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700669 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700670
671 std::string scheduler_group(GetSchedulerGroup(GetTid()));
672 if (scheduler_group.empty()) {
673 scheduler_group = "default";
674 }
675
Elliott Hughesd92bec42011-09-02 17:04:36 -0700676 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700677 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700678 os << " daemon";
679 }
680 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700681 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700682 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700683
Elliott Hughesd92bec42011-09-02 17:04:36 -0700684 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700685 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700686 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700687 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700688 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700689 << " self=" << reinterpret_cast<const void*>(this) << "\n";
690 os << " | sysTid=" << GetTid()
691 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
692 << " sched=" << policy << "/" << sp.sched_priority
693 << " cgrp=" << scheduler_group
694 << " handle=" << GetImpl() << "\n";
695
696 // Grab the scheduler stats for this thread.
697 std::string scheduler_stats;
698 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
699 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
700 } else {
701 scheduler_stats = "0 0 0";
702 }
703
704 int utime = 0;
705 int stime = 0;
706 int task_cpu = 0;
707 std::string stats;
708 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
709 // Skip the command, which may contain spaces.
710 stats = stats.substr(stats.find(')') + 2);
711 // Extract the three fields we care about.
712 std::vector<std::string> fields;
713 Split(stats, ' ', fields);
714 utime = strtoull(fields[11].c_str(), NULL, 10);
715 stime = strtoull(fields[12].c_str(), NULL, 10);
716 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
717 }
718
719 os << " | schedstat=( " << scheduler_stats << " )"
720 << " utm=" << utime
721 << " stm=" << stime
722 << " core=" << task_cpu
723 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
724}
725
Elliott Hughesd369bb72011-09-12 14:41:14 -0700726struct StackDumpVisitor : public Thread::StackVisitor {
727 StackDumpVisitor(std::ostream& os) : os(os) {
728 }
729
Ian Rogersbdb03912011-09-14 00:55:44 -0700730 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700731 }
732
Ian Rogersbdb03912011-09-14 00:55:44 -0700733 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700734 if (!frame.HasMethod()) {
735 return;
736 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700737 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
738
739 Method* m = frame.GetMethod();
740 Class* c = m->GetDeclaringClass();
741 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
742
743 os << " at " << PrettyMethod(m, false);
744 if (m->IsNative()) {
745 os << "(Native method)";
746 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700747 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700748 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
749 }
750 os << "\n";
751 }
752
753 std::ostream& os;
754};
755
Elliott Hughesd92bec42011-09-02 17:04:36 -0700756void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700757 StackDumpVisitor dumper(os);
758 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700759}
760
Elliott Hughes8d768a92011-09-14 16:35:25 -0700761Thread::State Thread::SetState(Thread::State new_state) {
762 Thread::State old_state = state_;
763 if (old_state == new_state) {
764 return old_state;
765 }
766
767 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
768 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
769
770 if (new_state == Thread::kRunnable) {
771 /*
772 * Change our status to Thread::kRunnable. The transition requires
773 * that we check for pending suspension, because the VM considers
774 * us to be "asleep" in all other states, and another thread could
775 * be performing a GC now.
776 *
777 * The order of operations is very significant here. One way to
778 * do this wrong is:
779 *
780 * GCing thread Our thread (in kNative)
781 * ------------ ----------------------
782 * check suspend count (== 0)
783 * SuspendAllThreads()
784 * grab suspend-count lock
785 * increment all suspend counts
786 * release suspend-count lock
787 * check thread state (== kNative)
788 * all are suspended, begin GC
789 * set state to kRunnable
790 * (continue executing)
791 *
792 * We can correct this by grabbing the suspend-count lock and
793 * performing both of our operations (check suspend count, set
794 * state) while holding it, now we need to grab a mutex on every
795 * transition to kRunnable.
796 *
797 * What we do instead is change the order of operations so that
798 * the transition to kRunnable happens first. If we then detect
799 * that the suspend count is nonzero, we switch to kSuspended.
800 *
801 * Appropriate compiler and memory barriers are required to ensure
802 * that the operations are observed in the expected order.
803 *
804 * This does create a small window of opportunity where a GC in
805 * progress could observe what appears to be a running thread (if
806 * it happens to look between when we set to kRunnable and when we
807 * switch to kSuspended). At worst this only affects assertions
808 * and thread logging. (We could work around it with some sort
809 * of intermediate "pre-running" state that is generally treated
810 * as equivalent to running, but that doesn't seem worthwhile.)
811 *
812 * We can also solve this by combining the "status" and "suspend
813 * count" fields into a single 32-bit value. This trades the
814 * store/load barrier on transition to kRunnable for an atomic RMW
815 * op on all transitions and all suspend count updates (also, all
816 * accesses to status or the thread count require bit-fiddling).
817 * It also eliminates the brief transition through kRunnable when
818 * the thread is supposed to be suspended. This is possibly faster
819 * on SMP and slightly more correct, but less convenient.
820 */
821 android_atomic_acquire_store(new_state, addr);
822 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
823 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
824 }
825 } else {
826 /*
827 * Not changing to Thread::kRunnable. No additional work required.
828 *
829 * We use a releasing store to ensure that, if we were runnable,
830 * any updates we previously made to objects on the managed heap
831 * will be observed before the state change.
832 */
833 android_atomic_release_store(new_state, addr);
834 }
835
836 return old_state;
837}
838
839void Thread::WaitUntilSuspended() {
840 // TODO: dalvik dropped the waiting thread's priority after a while.
841 // TODO: dalvik timed out and aborted.
842 useconds_t delay = 0;
843 while (GetState() == Thread::kRunnable) {
844 useconds_t new_delay = delay * 2;
845 CHECK_GE(new_delay, delay);
846 delay = new_delay;
847 if (delay == 0) {
848 sched_yield();
849 delay = 10000;
850 } else {
851 usleep(delay);
852 }
853 }
854}
855
Elliott Hughesbe759c62011-09-08 19:38:21 -0700856void Thread::ThreadExitCallback(void* arg) {
857 Thread* self = reinterpret_cast<Thread*>(arg);
858 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700859}
860
Elliott Hughesbe759c62011-09-08 19:38:21 -0700861void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700862 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700863 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700864
865 // Double-check the TLS slot allocation.
866 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700867 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700868 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700869}
Carl Shapirob5573532011-07-12 18:22:59 -0700870
Elliott Hughes038a8062011-09-18 14:12:41 -0700871void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700872 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
873 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
874 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
875 Class* int_class = class_linker->FindPrimitiveClass('I');
876 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
877 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
878 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
879 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
Elliott Hughes29f27422011-09-18 16:02:18 -0700880 Class* UncaughtExceptionHandler_class = class_linker->FindSystemClass("Ljava/lang/Thread$UncaughtExceptionHandler;");
881 gThrowable = class_linker->FindSystemClass("Ljava/lang/Throwable;");
Elliott Hughes038a8062011-09-18 14:12:41 -0700882 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
883 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
884 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
885 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
886 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
887 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
Elliott Hughes29f27422011-09-18 16:02:18 -0700888 gThread_uncaughtHandler = Thread_class->FindDeclaredInstanceField("uncaughtHandler", UncaughtExceptionHandler_class);
Elliott Hughes038a8062011-09-18 14:12:41 -0700889 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
890 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Elliott Hughes29f27422011-09-18 16:02:18 -0700891 gThreadGroup_removeThread = ThreadGroup_class->FindVirtualMethod("removeThread", "(Ljava/lang/Thread;)V");
892 gUncaughtExceptionHandler_uncaughtException =
893 UncaughtExceptionHandler_class->FindVirtualMethod("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700894
895 // Finish attaching the main thread.
896 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700897}
898
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700899void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700900 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700901}
902
Elliott Hughesdcc24742011-09-07 14:02:44 -0700903Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700904 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700905 wait_mutex_(new Mutex("Thread wait mutex")),
906 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700907 wait_monitor_(NULL),
908 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700909 wait_next_(NULL),
910 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700911 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700912 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700913 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700914 native_to_managed_record_(NULL),
915 top_sirt_(NULL),
916 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700917 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700918 self_(NULL),
919 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700920 exception_(NULL),
921 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700922 class_loader_override_(NULL),
923 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700924}
925
Elliott Hughes02b48d12011-09-07 17:15:51 -0700926void MonitorExitVisitor(const Object* object, void*) {
927 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700928 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700929}
930
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700931Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700932 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700933 if (jni_env_ != NULL) {
934 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
935 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700936
Elliott Hughes93e74e82011-09-13 11:07:03 -0700937 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700938 Object* group = gThread_group->GetObject(peer_);
939
940 // Handle any pending exception.
941 if (IsExceptionPending()) {
942 // Get and clear the exception.
943 Object* exception = GetException();
944 ClearException();
945
946 // If the thread has its own handler, use that.
947 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
948 if (handler == NULL) {
949 // Otherwise use the thread group's default handler.
950 handler = group;
951 }
952
953 // Call the handler.
954 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
955 Object* args[2];
956 args[0] = peer_;
957 args[1] = exception;
958 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
959
960 // If the handler threw, clear that exception too.
961 ClearException();
962 }
963
964 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700965 // group can be null if we're in the compiler or a test.
966 if (group != NULL) {
967 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
968 Object* args = peer_;
969 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
970 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700971
972 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700973 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700974
Elliott Hughes29f27422011-09-18 16:02:18 -0700975 // TODO: say "bye" to the debugger.
976 //if (gDvm.debuggerConnected) {
977 // dvmDbgPostThreadDeath(self);
978 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700979
Elliott Hughes29f27422011-09-18 16:02:18 -0700980 // Thread.join() is implemented as an Object.wait() on the Thread.lock
981 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700982 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700983 Object* lock = gThread_lock->GetObject(peer_);
984 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700985 if (lock != NULL) {
986 lock->MonitorEnter(self);
987 lock->NotifyAll();
988 lock->MonitorExit(self);
989 }
990 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700991
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700992 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700993 jni_env_ = NULL;
994
995 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700996
997 delete wait_cond_;
998 delete wait_mutex_;
999
1000 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001001}
1002
Ian Rogers408f79a2011-08-23 18:22:33 -07001003size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001004 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001005 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001006 count += cur->NumberOfReferences();
1007 }
1008 return count;
1009}
1010
Ian Rogers408f79a2011-08-23 18:22:33 -07001011bool Thread::SirtContains(jobject obj) {
1012 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1013 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001014 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001015 // A SIRT should always have a jobject/jclass as a native method is passed
1016 // in a this pointer or a class
1017 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001018 if ((&cur->References()[0] <= sirt_entry) &&
1019 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001020 return true;
1021 }
1022 }
1023 return false;
1024}
1025
Ian Rogers67375ac2011-09-14 00:55:44 -07001026void Thread::PopSirt() {
1027 CHECK(top_sirt_ != NULL);
1028 top_sirt_ = top_sirt_->Link();
1029}
1030
Ian Rogers408f79a2011-08-23 18:22:33 -07001031Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001032 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001033 if (obj == NULL) {
1034 return NULL;
1035 }
1036 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1037 IndirectRefKind kind = GetIndirectRefKind(ref);
1038 Object* result;
1039 switch (kind) {
1040 case kLocal:
1041 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001042 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001043 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001044 break;
1045 }
1046 case kGlobal:
1047 {
1048 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1049 IndirectReferenceTable& globals = vm->globals;
1050 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001051 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001052 break;
1053 }
1054 case kWeakGlobal:
1055 {
1056 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1057 IndirectReferenceTable& weak_globals = vm->weak_globals;
1058 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001059 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001060 if (result == kClearedJniWeakGlobal) {
1061 // This is a special case where it's okay to return NULL.
1062 return NULL;
1063 }
1064 break;
1065 }
1066 case kSirtOrInvalid:
1067 default:
1068 // TODO: make stack indirect reference table lookup more efficient
1069 // Check if this is a local reference in the SIRT
1070 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001071 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001072 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001073 // Assume an invalid local reference is actually a direct pointer.
1074 result = reinterpret_cast<Object*>(obj);
1075 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001076 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001077 }
1078 }
1079
1080 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001081 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1082 JniAbort(NULL);
1083 } else {
1084 if (result != kInvalidIndirectRefObject) {
1085 Heap::VerifyObject(result);
1086 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001087 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001088 return result;
1089}
1090
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001091class CountStackDepthVisitor : public Thread::StackVisitor {
1092 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001093 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001094
Elliott Hughes29f27422011-09-18 16:02:18 -07001095 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1096 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001097 // Note we also skip the frame if it doesn't have a method (namely the callee
1098 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001099 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001100 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001101 skipping_ = false;
1102 }
1103 if (!skipping_) {
1104 ++depth_;
1105 } else {
1106 ++skip_depth_;
1107 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001108 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001109
1110 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001111 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001112 }
1113
Elliott Hughes29f27422011-09-18 16:02:18 -07001114 int GetSkipDepth() const {
1115 return skip_depth_;
1116 }
1117
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001118 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001119 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001120 uint32_t skip_depth_;
1121 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001122};
1123
Ian Rogersaaa20802011-09-11 21:47:37 -07001124class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001125 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001126 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1127 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001128 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001129 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001130 // Register a local reference as IntArray::Alloc may trigger GC
1131 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1132 pc_trace_ = IntArray::Alloc(depth);
1133#ifdef MOVING_GARBAGE_COLLECTOR
1134 // Re-read after potential GC
1135 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1136#endif
1137 // Save PC trace in last element of method trace, also places it into the
1138 // object graph.
1139 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001140 }
1141
Ian Rogersaaa20802011-09-11 21:47:37 -07001142 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001143
Ian Rogersbdb03912011-09-14 00:55:44 -07001144 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001145 if (skip_depth_ > 0) {
1146 skip_depth_--;
1147 return;
1148 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001149 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001150 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001151 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001152 }
1153
Ian Rogersaaa20802011-09-11 21:47:37 -07001154 jobject GetInternalStackTrace() const {
1155 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001156 }
1157
1158 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001159 // How many more frames to skip.
1160 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001161 // Current position down stack trace
1162 uint32_t count_;
1163 // Array of return PC values
1164 IntArray* pc_trace_;
1165 // An array of the methods on the stack, the last entry is a reference to the
1166 // PC trace
1167 ObjectArray<Object>* method_trace_;
1168 // Local indirect reference table entry for method trace
1169 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001170};
1171
Ian Rogersaaa20802011-09-11 21:47:37 -07001172void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001173 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001174 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001175 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1176 // CHECK(native_to_managed_record_ != NULL);
1177 NativeToManagedRecord* record = native_to_managed_record_;
1178
Ian Rogersbdb03912011-09-14 00:55:44 -07001179 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001180 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001181 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1182 visitor->VisitFrame(frame, pc);
1183 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001184 }
1185 if (record == NULL) {
1186 break;
1187 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001188 // last_tos should return Frame instead of sp?
1189 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1190 pc = record->last_top_of_managed_stack_pc_;
1191 record = record->link_;
1192 }
1193}
1194
Ian Rogers67375ac2011-09-14 00:55:44 -07001195void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001196 Frame frame = GetTopOfStack();
1197 uintptr_t pc = top_of_managed_stack_pc_;
1198
1199 if (frame.GetSP() != 0) {
1200 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001201 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001202 visitor->VisitFrame(frame, pc);
1203 pc = frame.GetReturnPC();
1204 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001205 if (include_upcall) {
1206 visitor->VisitFrame(frame, pc);
1207 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001208 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001209}
1210
Elliott Hughes01158d72011-09-19 19:47:10 -07001211jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001212 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001213 CountStackDepthVisitor count_visitor;
1214 WalkStack(&count_visitor);
1215 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001216 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001217
Ian Rogersaaa20802011-09-11 21:47:37 -07001218 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001219 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001220
1221 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001222 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001223 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001224
Ian Rogersaaa20802011-09-11 21:47:37 -07001225 return build_trace_visitor.GetInternalStackTrace();
1226}
1227
Elliott Hughes01158d72011-09-19 19:47:10 -07001228jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1229 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001230 // Transition into runnable state to work on Object*/Array*
1231 ScopedJniThreadState ts(env);
1232
1233 // Decode the internal stack trace into the depth, method trace and PC trace
1234 ObjectArray<Object>* method_trace =
1235 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1236 int32_t depth = method_trace->GetLength()-1;
1237 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1238
1239 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1240
Elliott Hughes01158d72011-09-19 19:47:10 -07001241 jobjectArray result;
1242 ObjectArray<StackTraceElement>* java_traces;
1243 if (output_array != NULL) {
1244 // Reuse the array we were given.
1245 result = output_array;
1246 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1247 output_array));
1248 // ...adjusting the number of frames we'll write to not exceed the array length.
1249 depth = std::min(depth, java_traces->GetLength());
1250 } else {
1251 // Create java_trace array and place in local reference table
1252 java_traces = class_linker->AllocStackTraceElementArray(depth);
1253 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1254 }
1255
1256 if (stack_depth != NULL) {
1257 *stack_depth = depth;
1258 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001259
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001260 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001261 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1262 Method* method = down_cast<Method*>(method_trace->Get(i));
1263 uint32_t native_pc = pc_trace->Get(i);
1264 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001265 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001266 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001267
Ian Rogersaaa20802011-09-11 21:47:37 -07001268 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001269 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001270 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001271 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001272 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001273 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001274 method->ToDexPC(native_pc)));
1275#ifdef MOVING_GARBAGE_COLLECTOR
1276 // Re-read after potential GC
1277 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1278 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1279 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1280#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001281 java_traces->Set(i, obj);
1282 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001283 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001284}
1285
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001286void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001287 va_list args;
1288 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001289 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001290 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001291}
1292
1293void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1294 std::string msg;
1295 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001296
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001297 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001298 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001299 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001300 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001301 descriptor.erase(descriptor.length() - 1);
1302
1303 JNIEnv* env = GetJniEnv();
1304 jclass exception_class = env->FindClass(descriptor.c_str());
1305 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1306 int rc = env->ThrowNew(exception_class, msg.c_str());
1307 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001308}
1309
Elliott Hughes79082e32011-08-25 12:07:32 -07001310void Thread::ThrowOutOfMemoryError() {
1311 UNIMPLEMENTED(FATAL);
1312}
1313
Ian Rogersbdb03912011-09-14 00:55:44 -07001314Method* Thread::CalleeSaveMethod() const {
1315 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001316 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001317#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001318 method->SetCode(NULL, art::kThumb2, NULL);
1319 method->SetFrameSizeInBytes(64);
1320 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001321 method->SetCoreSpillMask((1 << art::arm::R1) |
1322 (1 << art::arm::R2) |
1323 (1 << art::arm::R3) |
1324 (1 << art::arm::R4) |
1325 (1 << art::arm::R5) |
1326 (1 << art::arm::R6) |
1327 (1 << art::arm::R7) |
1328 (1 << art::arm::R8) |
1329 (1 << art::arm::R9) |
1330 (1 << art::arm::R10) |
1331 (1 << art::arm::R11) |
1332 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001333 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001334#elif defined(__i386__)
1335 method->SetCode(NULL, art::kX86, NULL);
1336 method->SetFrameSizeInBytes(32);
1337 method->SetReturnPcOffsetInBytes(28);
1338 method->SetCoreSpillMask((1 << art::x86::EBX) |
1339 (1 << art::x86::EBP) |
1340 (1 << art::x86::ESI) |
1341 (1 << art::x86::EDI));
1342 method->SetFpSpillMask(0);
1343#else
1344 UNIMPLEMENTED(FATAL);
1345#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001346 return method;
1347}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001348
Ian Rogersbdb03912011-09-14 00:55:44 -07001349class CatchBlockStackVisitor : public Thread::StackVisitor {
1350 public:
1351 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001352 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1353#ifndef NDEBUG
1354 handler_pc_ = 0xEBADC0DE;
1355 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1356#endif
1357 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001358
Ian Rogersbdb03912011-09-14 00:55:44 -07001359 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1360 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001361 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001362 if (method == NULL) {
1363 // This is the upcall, we remember the frame and last_pc so that we may
1364 // long jump to them
1365 handler_pc_ = pc;
1366 handler_frame_ = fr;
1367 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001368 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001369 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001370 if (method->IsPhony()) {
1371 // ignore callee save method
1372 } else if (method->IsNative()) {
1373 native_method_count_++;
1374 } else {
1375 // Move the PC back 2 bytes as a call will frequently terminate the
1376 // decoding of a particular instruction and we want to make sure we
1377 // get the Dex PC of the instruction with the call and not the
1378 // instruction following.
1379 pc -= 2;
1380 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001381 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001382 if (dex_pc != DexFile::kDexNoIndex) {
1383 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1384 if (found_dex_pc != DexFile::kDexNoIndex) {
1385 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001386 handler_pc_ = method->ToNativePC(found_dex_pc);
1387 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001388 }
1389 }
1390 if (!found_) {
1391 // Caller may be handler, fill in callee saves in context
1392 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001393 }
1394 }
1395 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001396
1397 // Did we find a catch block yet?
1398 bool found_;
1399 // The type of the exception catch block to find
1400 Class* to_find_;
1401 // Frame with found handler or last frame if no handler found
1402 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001403 // PC to branch to for the handler
1404 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001405 // Context that will be the target of the long jump
1406 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001407 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1408 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001409};
1410
1411void Thread::DeliverException(Throwable* exception) {
1412 SetException(exception); // Set exception on thread
1413
1414 Context* long_jump_context = GetLongJumpContext();
1415 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001416 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001417
Ian Rogers67375ac2011-09-14 00:55:44 -07001418 // Pop any SIRT
1419 if (catch_finder.native_method_count_ == 1) {
1420 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001421 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001422 // We only expect the stack crawl to have passed 1 native method as it's terminated
1423 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001424 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001425 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001426 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1427 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001428 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001429}
1430
Ian Rogersbdb03912011-09-14 00:55:44 -07001431Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001432 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001433 if (result == NULL) {
1434 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001435 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001436 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001437 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001438}
1439
Elliott Hughes5f791332011-09-15 17:45:30 -07001440bool Thread::HoldsLock(Object* object) {
1441 if (object == NULL) {
1442 return false;
1443 }
1444 return object->GetLockOwner() == thin_lock_id_;
1445}
1446
Elliott Hughes038a8062011-09-18 14:12:41 -07001447bool Thread::IsDaemon() {
1448 return gThread_daemon->GetBoolean(peer_);
1449}
1450
Elliott Hughes410c0c82011-09-01 17:58:25 -07001451void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001452 if (exception_ != NULL) {
1453 visitor(exception_, arg);
1454 }
1455 if (peer_ != NULL) {
1456 visitor(peer_, arg);
1457 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001458 jni_env_->locals.VisitRoots(visitor, arg);
1459 jni_env_->monitors.VisitRoots(visitor, arg);
1460 // visitThreadStack(visitor, thread, arg);
1461 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1462}
1463
Ian Rogersb033c752011-07-20 12:22:35 -07001464static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001465 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001466 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001467 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001468 "Blocked",
1469 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001470 "Initializing",
1471 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001472 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001473 "VmWait",
1474 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001475};
1476std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001477 int int_state = static_cast<int>(state);
1478 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1479 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001480 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001481 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001482 }
1483 return os;
1484}
1485
Elliott Hughes330304d2011-08-12 14:28:05 -07001486std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1487 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001488 << ",pthread_t=" << thread.GetImpl()
1489 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001490 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001491 << ",state=" << thread.GetState()
1492 << ",peer=" << thread.GetPeer()
1493 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001494 return os;
1495}
1496
Elliott Hughes8daa0922011-09-11 13:46:25 -07001497} // namespace art