blob: 737faff5b5111a1507ca01a5ee2903493b40a95d [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#if defined(__i386__)
79 thread = art::Thread::Current(); // TODO: fix passing this in as an argument
80#endif
81 // Place a special frame at the TOS that will save all callee saves
Ian Rogersbdb03912011-09-14 00:55:44 -070082 *sp = thread->CalleeSaveMethod();
83 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070084 if (exception == NULL) {
85 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
86 exception = thread->GetException();
87 }
Ian Rogersbdb03912011-09-14 00:55:44 -070088 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070089}
90
Ian Rogersbdb03912011-09-14 00:55:44 -070091namespace art {
92
buzbee1b4c8592011-08-31 10:43:51 -070093// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070094Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070095 /*
96 * Should initialize & fix up method->dex_cache_resolved_types_[].
97 * Returns initialized type. Does not return normally if an exception
98 * is thrown, but instead initiates the catch. Should be similar to
99 * ClassLinker::InitializeStaticStorageFromCode.
100 */
101 UNIMPLEMENTED(FATAL);
102 return NULL;
103}
104
buzbee561227c2011-09-02 15:28:19 -0700105// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700106void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700107 /*
108 * Slow-path handler on invoke virtual method path in which
109 * base method is unresolved at compile-time. Doesn't need to
110 * return anything - just either ensure that
111 * method->dex_cache_resolved_methods_(method_idx) != NULL or
112 * throw and unwind. The caller will restart call sequence
113 * from the beginning.
114 */
115}
116
buzbee1da522d2011-09-04 11:22:20 -0700117// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700118Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700119 /*
120 * Just a wrapper around Array::AllocFromCode() that additionally
121 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
122 */
123 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
124 return Array::AllocFromCode(type_index, method, component_count);
125}
126
buzbee2a475e72011-09-07 17:19:17 -0700127// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700128void CheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700129 DCHECK(a->IsClass());
130 DCHECK(b->IsClass());
131 if (b->IsAssignableFrom(a)) {
132 return;
133 }
134 UNIMPLEMENTED(FATAL);
buzbee2a475e72011-09-07 17:19:17 -0700135}
136
Elliott Hughesd369bb72011-09-12 14:41:14 -0700137void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700138 // TODO: throw and unwind if lock not held
139 // TODO: throw and unwind on NPE
140 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700141}
142
Elliott Hughesd369bb72011-09-12 14:41:14 -0700143void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700144 obj->MonitorEnter(thread);
145 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700146}
147
Elliott Hughesd369bb72011-09-12 14:41:14 -0700148void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700149 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700150}
151
buzbeecefd1872011-09-09 09:59:52 -0700152// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700153void StackOverflowFromCode(Method* method) {
Brian Carlstromfa3baf72011-09-18 15:44:15 -0700154 Thread::Current()->SetTopOfStackPC(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
Brian Carlstrom16192862011-09-12 17:50:06 -0700155 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700156 //NOTE: to save code space, this handler needs to look up its own Thread*
157 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700158}
159
buzbee5ade1d22011-09-09 14:44:52 -0700160// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700161void ThrowNullPointerFromCode() {
Brian Carlstromfa3baf72011-09-18 15:44:15 -0700162 Thread::Current()->SetTopOfStackPC(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700163 Thread::Current()->Dump(std::cerr);
164 //NOTE: to save code space, this handler must look up caller's Method*
165 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700166}
167
168// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700169void ThrowDivZeroFromCode() {
170 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700171}
172
173// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700174void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
175 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700176}
177
178// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700179void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700180 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
181 " ref: " << ref;
182}
183
184// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700185void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700186 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
187}
188
189// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700190void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700191 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
192}
193
194// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700195void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700196 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
197}
198
199// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700200void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700201 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
202}
203
Ian Rogersbdb03912011-09-14 00:55:44 -0700204void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
205 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
206 "abstract method \"%s\"",
207 PrettyMethod(method).c_str());
208 thread->DeliverException(thread->GetException());
209}
210
211
buzbee5ade1d22011-09-09 14:44:52 -0700212/*
213 * Temporary placeholder. Should include run-time checks for size
214 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
215 * As with other new "FromCode" routines, this should return to the caller
216 * only if no exception has been thrown.
217 *
218 * NOTE: When dealing with a raw dex file, the data to be copied uses
219 * little-endian ordering. Require that oat2dex do any required swapping
220 * so this routine can get by with a memcpy().
221 *
222 * Format of the data:
223 * ushort ident = 0x0300 magic value
224 * ushort width width of each element in the table
225 * uint size number of elements in the table
226 * ubyte data[size*width] table of data values (may contain a single-byte
227 * padding at the end)
228 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700229void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700230 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
231 uint32_t size_in_bytes = size * table[1];
232 if (static_cast<int32_t>(size) > array->GetLength()) {
233 ThrowArrayBoundsFromCode(array->GetLength(), size);
234 }
235 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
236 (char*)&table[4], size_in_bytes);
237}
238
Brian Carlstrom16192862011-09-12 17:50:06 -0700239/*
240 * TODO: placeholder for a method that can be called by the
241 * invoke-interface trampoline to unwind and handle exception. The
242 * trampoline will arrange it so that the caller appears to be the
243 * callsite of the failed invoke-interface. See comments in
244 * runtime_support.S
245 */
246extern "C" void artFailedInvokeInterface() {
247 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
248}
249
250// See comments in runtime_support.S
251extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
252 Object* this_object , Method* caller_method)
253{
254 if (this_object == NULL) {
255 ThrowNullPointerFromCode();
256 }
257 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
258 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
259 if (interface_method == NULL) {
260 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
261 }
262 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
263 const void* code = method->GetCode();
264
265 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
266 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
267 uint64_t result = ((code_uint << 32) | method_uint);
268 return result;
269}
270
buzbee5ade1d22011-09-09 14:44:52 -0700271// TODO: move to more appropriate location
272/*
273 * Float/double conversion requires clamping to min and max of integer form. If
274 * target doesn't support this normally, use these.
275 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700276int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700277 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
278 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
279 if (d >= kMaxLong)
280 return (int64_t)0x7fffffffffffffffULL;
281 else if (d <= kMinLong)
282 return (int64_t)0x8000000000000000ULL;
283 else if (d != d) // NaN case
284 return 0;
285 else
286 return (int64_t)d;
287}
288
Elliott Hughesd369bb72011-09-12 14:41:14 -0700289int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700290 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
291 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
292 if (f >= kMaxLong)
293 return (int64_t)0x7fffffffffffffffULL;
294 else if (f <= kMinLong)
295 return (int64_t)0x8000000000000000ULL;
296 else if (f != f) // NaN case
297 return 0;
298 else
299 return (int64_t)f;
300}
301
Brian Carlstrom16192862011-09-12 17:50:06 -0700302// Return value helper for jobject return types
303static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
304 return thread->DecodeJObject(obj);
305}
306
buzbee3ea4ec52011-08-22 17:37:19 -0700307void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700308#if defined(__arm__)
309 pShlLong = art_shl_long;
310 pShrLong = art_shr_long;
311 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700312 pIdiv = __aeabi_idiv;
313 pIdivmod = __aeabi_idivmod;
314 pI2f = __aeabi_i2f;
315 pF2iz = __aeabi_f2iz;
316 pD2f = __aeabi_d2f;
317 pF2d = __aeabi_f2d;
318 pD2iz = __aeabi_d2iz;
319 pL2f = __aeabi_l2f;
320 pL2d = __aeabi_l2d;
321 pFadd = __aeabi_fadd;
322 pFsub = __aeabi_fsub;
323 pFdiv = __aeabi_fdiv;
324 pFmul = __aeabi_fmul;
325 pFmodf = fmodf;
326 pDadd = __aeabi_dadd;
327 pDsub = __aeabi_dsub;
328 pDdiv = __aeabi_ddiv;
329 pDmul = __aeabi_dmul;
330 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700331 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700332 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700333 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700334#endif
Ian Rogers67375ac2011-09-14 00:55:44 -0700335 pDeliverException = art_deliver_exception;
buzbeec396efc2011-09-11 09:36:41 -0700336 pF2l = F2L;
337 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700338 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700339 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700340 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700341 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700342 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700343 pGet32Static = Field::Get32StaticFromCode;
344 pSet32Static = Field::Set32StaticFromCode;
345 pGet64Static = Field::Get64StaticFromCode;
346 pSet64Static = Field::Set64StaticFromCode;
347 pGetObjStatic = Field::GetObjStaticFromCode;
348 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700349 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700350 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700351 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700352 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700353 pInstanceofNonTrivialFromCode = Object::InstanceOf;
354 pCheckCastFromCode = CheckCastFromCode;
355 pLockObjectFromCode = LockObjectFromCode;
356 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700357 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700358 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700359 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700360 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
361 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
362 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
363 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
364 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
365 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
366 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
367 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700368 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700369 pFindNativeMethod = FindNativeMethod;
370 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700371 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700372}
373
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700374void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700375 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
376 DCHECK_NE(frame_size, 0u);
377 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700378 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700379 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700380 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700381 DCHECK(*sp_ == NULL ||
382 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700383}
384
Ian Rogers90865722011-09-19 11:11:44 -0700385bool Frame::HasMethod() const {
386 return GetMethod() != NULL && (!GetMethod()->IsPhony());
387}
388
Ian Rogersbdb03912011-09-14 00:55:44 -0700389uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700390 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700391 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700392 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700393}
394
Ian Rogersbdb03912011-09-14 00:55:44 -0700395uintptr_t Frame::LoadCalleeSave(int num) const {
396 // Callee saves are held at the top of the frame
397 Method* method = GetMethod();
398 DCHECK(method != NULL);
399 size_t frame_size = method->GetFrameSizeInBytes();
400 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
401 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700402#if defined(__i386__)
403 save_addr -= kPointerSize; // account for return address
404#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700405 return *reinterpret_cast<uintptr_t*>(save_addr);
406}
407
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700409 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700410 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700412}
413
Brian Carlstrom78128a62011-09-15 17:21:19 -0700414void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700415 Thread* self = reinterpret_cast<Thread*>(arg);
416 Runtime* runtime = Runtime::Current();
417
418 self->Attach(runtime);
419
Elliott Hughes038a8062011-09-18 14:12:41 -0700420 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700421 if (thread_name != NULL) {
422 SetThreadName(thread_name->ToModifiedUtf8().c_str());
423 }
424
425 // Wait until it's safe to start running code. (There may have been a suspend-all
426 // in progress while we were starting up.)
427 runtime->GetThreadList()->WaitForGo();
428
429 // TODO: say "hi" to the debugger.
430 //if (gDvm.debuggerConnected) {
431 // dvmDbgPostThreadStart(self);
432 //}
433
434 // Invoke the 'run' method of our java.lang.Thread.
435 CHECK(self->peer_ != NULL);
436 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700437 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700438 m->Invoke(self, receiver, NULL, NULL);
439
440 // Detach.
441 runtime->GetThreadList()->Unregister();
442
Carl Shapirob5573532011-07-12 18:22:59 -0700443 return NULL;
444}
445
Elliott Hughes93e74e82011-09-13 11:07:03 -0700446void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700447 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700448}
449
Elliott Hughesd369bb72011-09-12 14:41:14 -0700450void Thread::Create(Object* peer, size_t stack_size) {
451 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700452
Elliott Hughesd369bb72011-09-12 14:41:14 -0700453 if (stack_size == 0) {
454 stack_size = Runtime::Current()->GetDefaultStackSize();
455 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700456
Elliott Hughes93e74e82011-09-13 11:07:03 -0700457 Thread* native_thread = new Thread;
458 native_thread->peer_ = peer;
459
460 // Thread.start is synchronized, so we know that vmData is 0,
461 // and know that we're not racing to assign it.
462 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700463
464 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700465 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
466 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
467 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
468 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
469 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700470
471 // Let the child know when it's safe to start running.
472 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700473}
474
Elliott Hughes93e74e82011-09-13 11:07:03 -0700475void Thread::Attach(const Runtime* runtime) {
476 InitCpu();
477 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700478
Elliott Hughes93e74e82011-09-13 11:07:03 -0700479 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700480
Elliott Hughes93e74e82011-09-13 11:07:03 -0700481 tid_ = ::art::GetTid();
482 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700483
Elliott Hughes93e74e82011-09-13 11:07:03 -0700484 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700485
Elliott Hughes8d768a92011-09-14 16:35:25 -0700486 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700487
Elliott Hughes93e74e82011-09-13 11:07:03 -0700488 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700489
Elliott Hughes93e74e82011-09-13 11:07:03 -0700490 runtime->GetThreadList()->Register(this);
491}
492
493Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
494 Thread* self = new Thread;
495 self->Attach(runtime);
496
497 self->SetState(Thread::kRunnable);
498
499 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700500
501 // If we're the main thread, ClassLinker won't be created until after we're attached,
502 // so that thread needs a two-stage attach. Regular threads don't need this hack.
503 if (self->thin_lock_id_ != ThreadList::kMainId) {
504 self->CreatePeer(name, as_daemon);
505 }
506
507 return self;
508}
509
Elliott Hughesd369bb72011-09-12 14:41:14 -0700510jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
511 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
512 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
513 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
514 // This will be null in the compiler (and tests), but never in a running system.
515 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
516 return thread_group;
517}
518
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700519void Thread::CreatePeer(const char* name, bool as_daemon) {
520 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
521
522 JNIEnv* env = jni_env_;
523
Elliott Hughesd369bb72011-09-12 14:41:14 -0700524 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
525 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700526 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700527 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700528 jboolean thread_is_daemon = as_daemon;
529
530 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700531 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700532
Elliott Hughes8daa0922011-09-11 13:46:25 -0700533 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700534
535 // Because we mostly run without code available (in the compiler, in tests), we
536 // manually assign the fields the constructor should have set.
537 // TODO: lose this.
538 jfieldID fid;
539 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
540 env->SetObjectField(peer, fid, thread_group);
541 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
542 env->SetObjectField(peer, fid, thread_name);
543 fid = env->GetFieldID(c, "priority", "I");
544 env->SetIntField(peer, fid, thread_priority);
545 fid = env->GetFieldID(c, "daemon", "Z");
546 env->SetBooleanField(peer, fid, thread_is_daemon);
547
548 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700549}
550
Elliott Hughesbe759c62011-09-08 19:38:21 -0700551void Thread::InitStackHwm() {
552 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700553 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700554
Elliott Hughesbe759c62011-09-08 19:38:21 -0700555 void* stack_base;
556 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700557 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700558
Elliott Hughesbe759c62011-09-08 19:38:21 -0700559 if (stack_size <= kStackOverflowReservedBytes) {
560 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
561 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700562
563 // stack_base is the "lowest addressable byte" of the stack.
564 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
565 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700566 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700567
568 // Sanity check.
569 int stack_variable;
570 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700571
Elliott Hughes8d768a92011-09-14 16:35:25 -0700572 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700573}
574
Elliott Hughesa0957642011-09-02 14:27:33 -0700575void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700576 DumpState(os);
577 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700578}
579
Elliott Hughesd92bec42011-09-02 17:04:36 -0700580std::string GetSchedulerGroup(pid_t tid) {
581 // /proc/<pid>/group looks like this:
582 // 2:devices:/
583 // 1:cpuacct,cpu:/
584 // We want the third field from the line whose second field contains the "cpu" token.
585 std::string cgroup_file;
586 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
587 return "";
588 }
589 std::vector<std::string> cgroup_lines;
590 Split(cgroup_file, '\n', cgroup_lines);
591 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
592 std::vector<std::string> cgroup_fields;
593 Split(cgroup_lines[i], ':', cgroup_fields);
594 std::vector<std::string> cgroups;
595 Split(cgroup_fields[1], ',', cgroups);
596 for (size_t i = 0; i < cgroups.size(); ++i) {
597 if (cgroups[i] == "cpu") {
598 return cgroup_fields[2].substr(1); // Skip the leading slash.
599 }
600 }
601 }
602 return "";
603}
604
605void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700606 std::string thread_name("<native thread without managed peer>");
607 std::string group_name;
608 int priority;
609 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700610
Elliott Hughesd369bb72011-09-12 14:41:14 -0700611 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700612 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700613 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700614 priority = gThread_priority->GetInt(peer_);
615 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700616
Elliott Hughes038a8062011-09-18 14:12:41 -0700617 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700618 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700619 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700620 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
621 }
622 } else {
623 // 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 -0700624 std::string stats;
625 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
626 size_t start = stats.find('(') + 1;
627 size_t end = stats.find(')') - start;
628 thread_name = stats.substr(start, end);
629 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700630 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700631 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700632
633 int policy;
634 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700635 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700636
637 std::string scheduler_group(GetSchedulerGroup(GetTid()));
638 if (scheduler_group.empty()) {
639 scheduler_group = "default";
640 }
641
Elliott Hughesd92bec42011-09-02 17:04:36 -0700642 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700643 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700644 os << " daemon";
645 }
646 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700647 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700648 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700649
Elliott Hughesd92bec42011-09-02 17:04:36 -0700650 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700651 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700652 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700653 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700654 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700655 << " self=" << reinterpret_cast<const void*>(this) << "\n";
656 os << " | sysTid=" << GetTid()
657 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
658 << " sched=" << policy << "/" << sp.sched_priority
659 << " cgrp=" << scheduler_group
660 << " handle=" << GetImpl() << "\n";
661
662 // Grab the scheduler stats for this thread.
663 std::string scheduler_stats;
664 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
665 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
666 } else {
667 scheduler_stats = "0 0 0";
668 }
669
670 int utime = 0;
671 int stime = 0;
672 int task_cpu = 0;
673 std::string stats;
674 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
675 // Skip the command, which may contain spaces.
676 stats = stats.substr(stats.find(')') + 2);
677 // Extract the three fields we care about.
678 std::vector<std::string> fields;
679 Split(stats, ' ', fields);
680 utime = strtoull(fields[11].c_str(), NULL, 10);
681 stime = strtoull(fields[12].c_str(), NULL, 10);
682 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
683 }
684
685 os << " | schedstat=( " << scheduler_stats << " )"
686 << " utm=" << utime
687 << " stm=" << stime
688 << " core=" << task_cpu
689 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
690}
691
Elliott Hughesd369bb72011-09-12 14:41:14 -0700692struct StackDumpVisitor : public Thread::StackVisitor {
693 StackDumpVisitor(std::ostream& os) : os(os) {
694 }
695
Ian Rogersbdb03912011-09-14 00:55:44 -0700696 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700697 }
698
Ian Rogersbdb03912011-09-14 00:55:44 -0700699 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700700 if (!frame.HasMethod()) {
701 return;
702 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700703 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
704
705 Method* m = frame.GetMethod();
706 Class* c = m->GetDeclaringClass();
707 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
708
709 os << " at " << PrettyMethod(m, false);
710 if (m->IsNative()) {
711 os << "(Native method)";
712 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700713 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700714 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
715 }
716 os << "\n";
717 }
718
719 std::ostream& os;
720};
721
Elliott Hughesd92bec42011-09-02 17:04:36 -0700722void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700723 StackDumpVisitor dumper(os);
724 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700725}
726
Elliott Hughes8d768a92011-09-14 16:35:25 -0700727Thread::State Thread::SetState(Thread::State new_state) {
728 Thread::State old_state = state_;
729 if (old_state == new_state) {
730 return old_state;
731 }
732
733 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
734 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
735
736 if (new_state == Thread::kRunnable) {
737 /*
738 * Change our status to Thread::kRunnable. The transition requires
739 * that we check for pending suspension, because the VM considers
740 * us to be "asleep" in all other states, and another thread could
741 * be performing a GC now.
742 *
743 * The order of operations is very significant here. One way to
744 * do this wrong is:
745 *
746 * GCing thread Our thread (in kNative)
747 * ------------ ----------------------
748 * check suspend count (== 0)
749 * SuspendAllThreads()
750 * grab suspend-count lock
751 * increment all suspend counts
752 * release suspend-count lock
753 * check thread state (== kNative)
754 * all are suspended, begin GC
755 * set state to kRunnable
756 * (continue executing)
757 *
758 * We can correct this by grabbing the suspend-count lock and
759 * performing both of our operations (check suspend count, set
760 * state) while holding it, now we need to grab a mutex on every
761 * transition to kRunnable.
762 *
763 * What we do instead is change the order of operations so that
764 * the transition to kRunnable happens first. If we then detect
765 * that the suspend count is nonzero, we switch to kSuspended.
766 *
767 * Appropriate compiler and memory barriers are required to ensure
768 * that the operations are observed in the expected order.
769 *
770 * This does create a small window of opportunity where a GC in
771 * progress could observe what appears to be a running thread (if
772 * it happens to look between when we set to kRunnable and when we
773 * switch to kSuspended). At worst this only affects assertions
774 * and thread logging. (We could work around it with some sort
775 * of intermediate "pre-running" state that is generally treated
776 * as equivalent to running, but that doesn't seem worthwhile.)
777 *
778 * We can also solve this by combining the "status" and "suspend
779 * count" fields into a single 32-bit value. This trades the
780 * store/load barrier on transition to kRunnable for an atomic RMW
781 * op on all transitions and all suspend count updates (also, all
782 * accesses to status or the thread count require bit-fiddling).
783 * It also eliminates the brief transition through kRunnable when
784 * the thread is supposed to be suspended. This is possibly faster
785 * on SMP and slightly more correct, but less convenient.
786 */
787 android_atomic_acquire_store(new_state, addr);
788 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
789 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
790 }
791 } else {
792 /*
793 * Not changing to Thread::kRunnable. No additional work required.
794 *
795 * We use a releasing store to ensure that, if we were runnable,
796 * any updates we previously made to objects on the managed heap
797 * will be observed before the state change.
798 */
799 android_atomic_release_store(new_state, addr);
800 }
801
802 return old_state;
803}
804
805void Thread::WaitUntilSuspended() {
806 // TODO: dalvik dropped the waiting thread's priority after a while.
807 // TODO: dalvik timed out and aborted.
808 useconds_t delay = 0;
809 while (GetState() == Thread::kRunnable) {
810 useconds_t new_delay = delay * 2;
811 CHECK_GE(new_delay, delay);
812 delay = new_delay;
813 if (delay == 0) {
814 sched_yield();
815 delay = 10000;
816 } else {
817 usleep(delay);
818 }
819 }
820}
821
Elliott Hughesbe759c62011-09-08 19:38:21 -0700822void Thread::ThreadExitCallback(void* arg) {
823 Thread* self = reinterpret_cast<Thread*>(arg);
824 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700825}
826
Elliott Hughesbe759c62011-09-08 19:38:21 -0700827void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700828 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700829 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700830
831 // Double-check the TLS slot allocation.
832 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700833 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700834 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700835}
Carl Shapirob5573532011-07-12 18:22:59 -0700836
Elliott Hughes038a8062011-09-18 14:12:41 -0700837void Thread::FinishStartup() {
838 // Finish attaching the main thread.
839 Thread::Current()->CreatePeer("main", false);
840
841 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
842 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
843 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
844 Class* int_class = class_linker->FindPrimitiveClass('I');
845 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
846 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
847 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
848 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
Elliott Hughes29f27422011-09-18 16:02:18 -0700849 Class* UncaughtExceptionHandler_class = class_linker->FindSystemClass("Ljava/lang/Thread$UncaughtExceptionHandler;");
850 gThrowable = class_linker->FindSystemClass("Ljava/lang/Throwable;");
Elliott Hughes038a8062011-09-18 14:12:41 -0700851 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
852 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
853 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
854 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
855 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
856 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
Elliott Hughes29f27422011-09-18 16:02:18 -0700857 gThread_uncaughtHandler = Thread_class->FindDeclaredInstanceField("uncaughtHandler", UncaughtExceptionHandler_class);
Elliott Hughes038a8062011-09-18 14:12:41 -0700858 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
859 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Elliott Hughes29f27422011-09-18 16:02:18 -0700860 gThreadGroup_removeThread = ThreadGroup_class->FindVirtualMethod("removeThread", "(Ljava/lang/Thread;)V");
861 gUncaughtExceptionHandler_uncaughtException =
862 UncaughtExceptionHandler_class->FindVirtualMethod("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Carl Shapirob5573532011-07-12 18:22:59 -0700863}
864
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700865void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700866 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700867}
868
Elliott Hughesdcc24742011-09-07 14:02:44 -0700869Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700870 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700871 wait_mutex_(new Mutex("Thread wait mutex")),
872 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700873 wait_monitor_(NULL),
874 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700875 wait_next_(NULL),
876 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700877 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700878 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700879 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700880 native_to_managed_record_(NULL),
881 top_sirt_(NULL),
882 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700883 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700884 self_(NULL),
885 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700886 exception_(NULL),
887 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700888 class_loader_override_(NULL),
889 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700890}
891
Elliott Hughes02b48d12011-09-07 17:15:51 -0700892void MonitorExitVisitor(const Object* object, void*) {
893 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700894 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700895}
896
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700897Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700898 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700899 if (jni_env_ != NULL) {
900 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
901 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700902
Elliott Hughes93e74e82011-09-13 11:07:03 -0700903 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700904 Object* group = gThread_group->GetObject(peer_);
905
906 // Handle any pending exception.
907 if (IsExceptionPending()) {
908 // Get and clear the exception.
909 Object* exception = GetException();
910 ClearException();
911
912 // If the thread has its own handler, use that.
913 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
914 if (handler == NULL) {
915 // Otherwise use the thread group's default handler.
916 handler = group;
917 }
918
919 // Call the handler.
920 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
921 Object* args[2];
922 args[0] = peer_;
923 args[1] = exception;
924 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
925
926 // If the handler threw, clear that exception too.
927 ClearException();
928 }
929
930 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700931 // group can be null if we're in the compiler or a test.
932 if (group != NULL) {
933 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
934 Object* args = peer_;
935 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
936 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700937
938 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700939 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700940
Elliott Hughes29f27422011-09-18 16:02:18 -0700941 // TODO: say "bye" to the debugger.
942 //if (gDvm.debuggerConnected) {
943 // dvmDbgPostThreadDeath(self);
944 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700945
Elliott Hughes29f27422011-09-18 16:02:18 -0700946 // Thread.join() is implemented as an Object.wait() on the Thread.lock
947 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700948 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700949 Object* lock = gThread_lock->GetObject(peer_);
950 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700951 if (lock != NULL) {
952 lock->MonitorEnter(self);
953 lock->NotifyAll();
954 lock->MonitorExit(self);
955 }
956 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700957
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700958 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700959 jni_env_ = NULL;
960
961 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700962
963 delete wait_cond_;
964 delete wait_mutex_;
965
966 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700967}
968
Ian Rogers408f79a2011-08-23 18:22:33 -0700969size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700970 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700971 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700972 count += cur->NumberOfReferences();
973 }
974 return count;
975}
976
Ian Rogers408f79a2011-08-23 18:22:33 -0700977bool Thread::SirtContains(jobject obj) {
978 Object** sirt_entry = reinterpret_cast<Object**>(obj);
979 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700980 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700981 // A SIRT should always have a jobject/jclass as a native method is passed
982 // in a this pointer or a class
983 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700984 if ((&cur->References()[0] <= sirt_entry) &&
985 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700986 return true;
987 }
988 }
989 return false;
990}
991
Ian Rogers67375ac2011-09-14 00:55:44 -0700992void Thread::PopSirt() {
993 CHECK(top_sirt_ != NULL);
994 top_sirt_ = top_sirt_->Link();
995}
996
Ian Rogers408f79a2011-08-23 18:22:33 -0700997Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700998 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700999 if (obj == NULL) {
1000 return NULL;
1001 }
1002 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1003 IndirectRefKind kind = GetIndirectRefKind(ref);
1004 Object* result;
1005 switch (kind) {
1006 case kLocal:
1007 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001008 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001009 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001010 break;
1011 }
1012 case kGlobal:
1013 {
1014 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1015 IndirectReferenceTable& globals = vm->globals;
1016 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001017 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001018 break;
1019 }
1020 case kWeakGlobal:
1021 {
1022 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1023 IndirectReferenceTable& weak_globals = vm->weak_globals;
1024 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001025 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001026 if (result == kClearedJniWeakGlobal) {
1027 // This is a special case where it's okay to return NULL.
1028 return NULL;
1029 }
1030 break;
1031 }
1032 case kSirtOrInvalid:
1033 default:
1034 // TODO: make stack indirect reference table lookup more efficient
1035 // Check if this is a local reference in the SIRT
1036 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001037 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001038 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001039 // Assume an invalid local reference is actually a direct pointer.
1040 result = reinterpret_cast<Object*>(obj);
1041 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001042 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001043 }
1044 }
1045
1046 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001047 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1048 JniAbort(NULL);
1049 } else {
1050 if (result != kInvalidIndirectRefObject) {
1051 Heap::VerifyObject(result);
1052 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001053 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001054 return result;
1055}
1056
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001057class CountStackDepthVisitor : public Thread::StackVisitor {
1058 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001059 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001060
Elliott Hughes29f27422011-09-18 16:02:18 -07001061 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1062 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001063 // Note we also skip the frame if it doesn't have a method (namely the callee
1064 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001065 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001066 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001067 skipping_ = false;
1068 }
1069 if (!skipping_) {
1070 ++depth_;
1071 } else {
1072 ++skip_depth_;
1073 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001074 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001075
1076 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001077 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001078 }
1079
Elliott Hughes29f27422011-09-18 16:02:18 -07001080 int GetSkipDepth() const {
1081 return skip_depth_;
1082 }
1083
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001084 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001085 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001086 uint32_t skip_depth_;
1087 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001088};
1089
Ian Rogersaaa20802011-09-11 21:47:37 -07001090class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001091 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001092 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1093 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001094 // Allocate method trace with an extra slot that will hold the PC trace
1095 method_trace_ = Runtime::Current()->GetClassLinker()->
1096 AllocObjectArray<Object>(depth + 1);
1097 // Register a local reference as IntArray::Alloc may trigger GC
1098 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1099 pc_trace_ = IntArray::Alloc(depth);
1100#ifdef MOVING_GARBAGE_COLLECTOR
1101 // Re-read after potential GC
1102 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1103#endif
1104 // Save PC trace in last element of method trace, also places it into the
1105 // object graph.
1106 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001107 }
1108
Ian Rogersaaa20802011-09-11 21:47:37 -07001109 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001110
Ian Rogersbdb03912011-09-14 00:55:44 -07001111 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001112 if (skip_depth_ > 0) {
1113 skip_depth_--;
1114 return;
1115 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001116 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001117 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001118 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001119 }
1120
Ian Rogersaaa20802011-09-11 21:47:37 -07001121 jobject GetInternalStackTrace() const {
1122 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001123 }
1124
1125 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001126 // How many more frames to skip.
1127 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001128 // Current position down stack trace
1129 uint32_t count_;
1130 // Array of return PC values
1131 IntArray* pc_trace_;
1132 // An array of the methods on the stack, the last entry is a reference to the
1133 // PC trace
1134 ObjectArray<Object>* method_trace_;
1135 // Local indirect reference table entry for method trace
1136 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001137};
1138
Ian Rogersaaa20802011-09-11 21:47:37 -07001139void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001140 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001141 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001142 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1143 // CHECK(native_to_managed_record_ != NULL);
1144 NativeToManagedRecord* record = native_to_managed_record_;
1145
Ian Rogersbdb03912011-09-14 00:55:44 -07001146 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001147 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001148 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1149 visitor->VisitFrame(frame, pc);
1150 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001151 }
1152 if (record == NULL) {
1153 break;
1154 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001155 // last_tos should return Frame instead of sp?
1156 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1157 pc = record->last_top_of_managed_stack_pc_;
1158 record = record->link_;
1159 }
1160}
1161
Ian Rogers67375ac2011-09-14 00:55:44 -07001162void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001163 Frame frame = GetTopOfStack();
1164 uintptr_t pc = top_of_managed_stack_pc_;
1165
1166 if (frame.GetSP() != 0) {
1167 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001168 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001169 visitor->VisitFrame(frame, pc);
1170 pc = frame.GetReturnPC();
1171 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001172 if (include_upcall) {
1173 visitor->VisitFrame(frame, pc);
1174 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001175 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001176}
1177
Ian Rogersaaa20802011-09-11 21:47:37 -07001178jobject Thread::CreateInternalStackTrace() const {
1179 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001180 CountStackDepthVisitor count_visitor;
1181 WalkStack(&count_visitor);
1182 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001183 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001184
Ian Rogersaaa20802011-09-11 21:47:37 -07001185 // Transition into runnable state to work on Object*/Array*
1186 ScopedJniThreadState ts(jni_env_);
1187
1188 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001189 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001190 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001191
Ian Rogersaaa20802011-09-11 21:47:37 -07001192 return build_trace_visitor.GetInternalStackTrace();
1193}
1194
1195jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1196 JNIEnv* env) {
1197 // Transition into runnable state to work on Object*/Array*
1198 ScopedJniThreadState ts(env);
1199
1200 // Decode the internal stack trace into the depth, method trace and PC trace
1201 ObjectArray<Object>* method_trace =
1202 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1203 int32_t depth = method_trace->GetLength()-1;
1204 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1205
1206 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1207
1208 // Create java_trace array and place in local reference table
1209 ObjectArray<StackTraceElement>* java_traces =
1210 class_linker->AllocStackTraceElementArray(depth);
1211 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001212
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001213 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001214 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1215 Method* method = down_cast<Method*>(method_trace->Get(i));
1216 uint32_t native_pc = pc_trace->Get(i);
1217 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001218 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001219 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001220
Ian Rogersaaa20802011-09-11 21:47:37 -07001221 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001222 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001223 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001224 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001225 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001226 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001227 method->ToDexPC(native_pc)));
1228#ifdef MOVING_GARBAGE_COLLECTOR
1229 // Re-read after potential GC
1230 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1231 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1232 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1233#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001234 java_traces->Set(i, obj);
1235 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001236 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001237}
1238
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001239void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001240 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001241 va_list args;
1242 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001243 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001244 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001245
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001246 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001247 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001248 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001249 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001250 descriptor.erase(descriptor.length() - 1);
1251
1252 JNIEnv* env = GetJniEnv();
1253 jclass exception_class = env->FindClass(descriptor.c_str());
1254 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1255 int rc = env->ThrowNew(exception_class, msg.c_str());
1256 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001257}
1258
Elliott Hughes79082e32011-08-25 12:07:32 -07001259void Thread::ThrowOutOfMemoryError() {
1260 UNIMPLEMENTED(FATAL);
1261}
1262
Ian Rogersbdb03912011-09-14 00:55:44 -07001263Method* Thread::CalleeSaveMethod() const {
1264 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001265 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001266#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001267 method->SetCode(NULL, art::kThumb2, NULL);
1268 method->SetFrameSizeInBytes(64);
1269 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001270 method->SetCoreSpillMask((1 << art::arm::R1) |
1271 (1 << art::arm::R2) |
1272 (1 << art::arm::R3) |
1273 (1 << art::arm::R4) |
1274 (1 << art::arm::R5) |
1275 (1 << art::arm::R6) |
1276 (1 << art::arm::R7) |
1277 (1 << art::arm::R8) |
1278 (1 << art::arm::R9) |
1279 (1 << art::arm::R10) |
1280 (1 << art::arm::R11) |
1281 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001282 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001283#elif defined(__i386__)
1284 method->SetCode(NULL, art::kX86, NULL);
1285 method->SetFrameSizeInBytes(32);
1286 method->SetReturnPcOffsetInBytes(28);
1287 method->SetCoreSpillMask((1 << art::x86::EBX) |
1288 (1 << art::x86::EBP) |
1289 (1 << art::x86::ESI) |
1290 (1 << art::x86::EDI));
1291 method->SetFpSpillMask(0);
1292#else
1293 UNIMPLEMENTED(FATAL);
1294#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001295 return method;
1296}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001297
Ian Rogersbdb03912011-09-14 00:55:44 -07001298class CatchBlockStackVisitor : public Thread::StackVisitor {
1299 public:
1300 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001301 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1302#ifndef NDEBUG
1303 handler_pc_ = 0xEBADC0DE;
1304 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1305#endif
1306 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001307
Ian Rogersbdb03912011-09-14 00:55:44 -07001308 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1309 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001310 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001311 if (method == NULL) {
1312 // This is the upcall, we remember the frame and last_pc so that we may
1313 // long jump to them
1314 handler_pc_ = pc;
1315 handler_frame_ = fr;
1316 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001317 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001318 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001319 if (method->IsPhony()) {
1320 // ignore callee save method
1321 } else if (method->IsNative()) {
1322 native_method_count_++;
1323 } else {
1324 // Move the PC back 2 bytes as a call will frequently terminate the
1325 // decoding of a particular instruction and we want to make sure we
1326 // get the Dex PC of the instruction with the call and not the
1327 // instruction following.
1328 pc -= 2;
1329 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001330 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001331 if (dex_pc != DexFile::kDexNoIndex) {
1332 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1333 if (found_dex_pc != DexFile::kDexNoIndex) {
1334 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001335 handler_pc_ = method->ToNativePC(found_dex_pc);
1336 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001337 }
1338 }
1339 if (!found_) {
1340 // Caller may be handler, fill in callee saves in context
1341 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001342 }
1343 }
1344 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001345
1346 // Did we find a catch block yet?
1347 bool found_;
1348 // The type of the exception catch block to find
1349 Class* to_find_;
1350 // Frame with found handler or last frame if no handler found
1351 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001352 // PC to branch to for the handler
1353 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001354 // Context that will be the target of the long jump
1355 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001356 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1357 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001358};
1359
1360void Thread::DeliverException(Throwable* exception) {
1361 SetException(exception); // Set exception on thread
1362
1363 Context* long_jump_context = GetLongJumpContext();
1364 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001365 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001366
Ian Rogers67375ac2011-09-14 00:55:44 -07001367 // Pop any SIRT
1368 if (catch_finder.native_method_count_ == 1) {
1369 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001370 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001371 // We only expect the stack crawl to have passed 1 native method as it's terminated
1372 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001373 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001374 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001375 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1376 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001377 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001378}
1379
Ian Rogersbdb03912011-09-14 00:55:44 -07001380Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001381 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001382 if (result == NULL) {
1383 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001384 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001385 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001386 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001387}
1388
Elliott Hughes5f791332011-09-15 17:45:30 -07001389bool Thread::HoldsLock(Object* object) {
1390 if (object == NULL) {
1391 return false;
1392 }
1393 return object->GetLockOwner() == thin_lock_id_;
1394}
1395
Elliott Hughes038a8062011-09-18 14:12:41 -07001396bool Thread::IsDaemon() {
1397 return gThread_daemon->GetBoolean(peer_);
1398}
1399
Elliott Hughes410c0c82011-09-01 17:58:25 -07001400void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001401 if (exception_ != NULL) {
1402 visitor(exception_, arg);
1403 }
1404 if (peer_ != NULL) {
1405 visitor(peer_, arg);
1406 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001407 jni_env_->locals.VisitRoots(visitor, arg);
1408 jni_env_->monitors.VisitRoots(visitor, arg);
1409 // visitThreadStack(visitor, thread, arg);
1410 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1411}
1412
Ian Rogersb033c752011-07-20 12:22:35 -07001413static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001414 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001415 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001416 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001417 "Blocked",
1418 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001419 "Initializing",
1420 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001421 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001422 "VmWait",
1423 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001424};
1425std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001426 int int_state = static_cast<int>(state);
1427 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1428 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001429 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001430 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001431 }
1432 return os;
1433}
1434
Elliott Hughes330304d2011-08-12 14:28:05 -07001435std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1436 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001437 << ",pthread_t=" << thread.GetImpl()
1438 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001439 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001440 << ",state=" << thread.GetState()
1441 << ",peer=" << thread.GetPeer()
1442 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001443 return os;
1444}
1445
Elliott Hughes8daa0922011-09-11 13:46:25 -07001446} // namespace art