blob: 69fb3ba1c113a3d77d30bd59ea0961c85a175663 [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
buzbee4a3164f2011-09-03 11:25:10 -070044// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070045void DebugMe(Method* method, uint32_t info) {
buzbee4a3164f2011-09-03 11:25:10 -070046 LOG(INFO) << "DebugMe";
47 if (method != NULL)
48 LOG(INFO) << PrettyMethod(method);
49 LOG(INFO) << "Info: " << info;
50}
51
Ian Rogersbdb03912011-09-14 00:55:44 -070052} // namespace art
53
54// Called by generated call to throw an exception
Ian Rogers67375ac2011-09-14 00:55:44 -070055extern "C" void artDeliverExceptionHelper(art::Throwable* exception,
56 art::Thread* thread,
57 art::Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070058 /*
59 * exception may be NULL, in which case this routine should
60 * throw NPE. NOTE: this is a convenience for generated code,
61 * which previously did the null check inline and constructed
62 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070063 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070064 */
Ian Rogers67375ac2011-09-14 00:55:44 -070065#if defined(__i386__)
66 thread = art::Thread::Current(); // TODO: fix passing this in as an argument
67#endif
68 // Place a special frame at the TOS that will save all callee saves
Ian Rogersbdb03912011-09-14 00:55:44 -070069 *sp = thread->CalleeSaveMethod();
70 thread->SetTopOfStack(sp, 0);
71 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070072}
73
Ian Rogersbdb03912011-09-14 00:55:44 -070074namespace art {
75
buzbee1b4c8592011-08-31 10:43:51 -070076// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070077Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070078 /*
79 * Should initialize & fix up method->dex_cache_resolved_types_[].
80 * Returns initialized type. Does not return normally if an exception
81 * is thrown, but instead initiates the catch. Should be similar to
82 * ClassLinker::InitializeStaticStorageFromCode.
83 */
84 UNIMPLEMENTED(FATAL);
85 return NULL;
86}
87
buzbee561227c2011-09-02 15:28:19 -070088// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -070089void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -070090 /*
91 * Slow-path handler on invoke virtual method path in which
92 * base method is unresolved at compile-time. Doesn't need to
93 * return anything - just either ensure that
94 * method->dex_cache_resolved_methods_(method_idx) != NULL or
95 * throw and unwind. The caller will restart call sequence
96 * from the beginning.
97 */
98}
99
buzbee1da522d2011-09-04 11:22:20 -0700100// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700101Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700102 /*
103 * Just a wrapper around Array::AllocFromCode() that additionally
104 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
105 */
106 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
107 return Array::AllocFromCode(type_index, method, component_count);
108}
109
buzbee2a475e72011-09-07 17:19:17 -0700110// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700111void CheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700112 DCHECK(a->IsClass());
113 DCHECK(b->IsClass());
114 if (b->IsAssignableFrom(a)) {
115 return;
116 }
117 UNIMPLEMENTED(FATAL);
buzbee2a475e72011-09-07 17:19:17 -0700118}
119
Elliott Hughesd369bb72011-09-12 14:41:14 -0700120void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700121 // TODO: throw and unwind if lock not held
122 // TODO: throw and unwind on NPE
123 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700124}
125
Elliott Hughesd369bb72011-09-12 14:41:14 -0700126void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700127 obj->MonitorEnter(thread);
128 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700129}
130
Elliott Hughesd369bb72011-09-12 14:41:14 -0700131void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700132 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700133}
134
buzbeecefd1872011-09-09 09:59:52 -0700135// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700136void StackOverflowFromCode(Method* method) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700137 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700138 //NOTE: to save code space, this handler needs to look up its own Thread*
139 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700140}
141
buzbee5ade1d22011-09-09 14:44:52 -0700142// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700143void ThrowNullPointerFromCode() {
144 Thread::Current()->Dump(std::cerr);
145 //NOTE: to save code space, this handler must look up caller's Method*
146 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700147}
148
149// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700150void ThrowDivZeroFromCode() {
151 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700152}
153
154// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700155void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
156 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700157}
158
159// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700160void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700161 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
162 " ref: " << ref;
163}
164
165// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700166void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700167 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
168}
169
170// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700171void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700172 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
173}
174
175// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700176void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700177 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
178}
179
180// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700181void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700182 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
183}
184
Ian Rogersbdb03912011-09-14 00:55:44 -0700185void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
186 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
187 "abstract method \"%s\"",
188 PrettyMethod(method).c_str());
189 thread->DeliverException(thread->GetException());
190}
191
192
buzbee5ade1d22011-09-09 14:44:52 -0700193/*
194 * Temporary placeholder. Should include run-time checks for size
195 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
196 * As with other new "FromCode" routines, this should return to the caller
197 * only if no exception has been thrown.
198 *
199 * NOTE: When dealing with a raw dex file, the data to be copied uses
200 * little-endian ordering. Require that oat2dex do any required swapping
201 * so this routine can get by with a memcpy().
202 *
203 * Format of the data:
204 * ushort ident = 0x0300 magic value
205 * ushort width width of each element in the table
206 * uint size number of elements in the table
207 * ubyte data[size*width] table of data values (may contain a single-byte
208 * padding at the end)
209 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700210void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700211 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
212 uint32_t size_in_bytes = size * table[1];
213 if (static_cast<int32_t>(size) > array->GetLength()) {
214 ThrowArrayBoundsFromCode(array->GetLength(), size);
215 }
216 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
217 (char*)&table[4], size_in_bytes);
218}
219
Brian Carlstrom16192862011-09-12 17:50:06 -0700220/*
221 * TODO: placeholder for a method that can be called by the
222 * invoke-interface trampoline to unwind and handle exception. The
223 * trampoline will arrange it so that the caller appears to be the
224 * callsite of the failed invoke-interface. See comments in
225 * runtime_support.S
226 */
227extern "C" void artFailedInvokeInterface() {
228 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
229}
230
231// See comments in runtime_support.S
232extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
233 Object* this_object , Method* caller_method)
234{
235 if (this_object == NULL) {
236 ThrowNullPointerFromCode();
237 }
238 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
239 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
240 if (interface_method == NULL) {
241 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
242 }
243 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
244 const void* code = method->GetCode();
245
246 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
247 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
248 uint64_t result = ((code_uint << 32) | method_uint);
249 return result;
250}
251
buzbee5ade1d22011-09-09 14:44:52 -0700252// TODO: move to more appropriate location
253/*
254 * Float/double conversion requires clamping to min and max of integer form. If
255 * target doesn't support this normally, use these.
256 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700257int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700258 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
259 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
260 if (d >= kMaxLong)
261 return (int64_t)0x7fffffffffffffffULL;
262 else if (d <= kMinLong)
263 return (int64_t)0x8000000000000000ULL;
264 else if (d != d) // NaN case
265 return 0;
266 else
267 return (int64_t)d;
268}
269
Elliott Hughesd369bb72011-09-12 14:41:14 -0700270int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700271 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
272 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
273 if (f >= kMaxLong)
274 return (int64_t)0x7fffffffffffffffULL;
275 else if (f <= kMinLong)
276 return (int64_t)0x8000000000000000ULL;
277 else if (f != f) // NaN case
278 return 0;
279 else
280 return (int64_t)f;
281}
282
Brian Carlstrom16192862011-09-12 17:50:06 -0700283// Return value helper for jobject return types
284static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
285 return thread->DecodeJObject(obj);
286}
287
buzbee3ea4ec52011-08-22 17:37:19 -0700288void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700289#if defined(__arm__)
290 pShlLong = art_shl_long;
291 pShrLong = art_shr_long;
292 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700293 pIdiv = __aeabi_idiv;
294 pIdivmod = __aeabi_idivmod;
295 pI2f = __aeabi_i2f;
296 pF2iz = __aeabi_f2iz;
297 pD2f = __aeabi_d2f;
298 pF2d = __aeabi_f2d;
299 pD2iz = __aeabi_d2iz;
300 pL2f = __aeabi_l2f;
301 pL2d = __aeabi_l2d;
302 pFadd = __aeabi_fadd;
303 pFsub = __aeabi_fsub;
304 pFdiv = __aeabi_fdiv;
305 pFmul = __aeabi_fmul;
306 pFmodf = fmodf;
307 pDadd = __aeabi_dadd;
308 pDsub = __aeabi_dsub;
309 pDdiv = __aeabi_ddiv;
310 pDmul = __aeabi_dmul;
311 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700312 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700313 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700314 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700315#endif
Ian Rogers67375ac2011-09-14 00:55:44 -0700316 pDeliverException = art_deliver_exception;
buzbeec396efc2011-09-11 09:36:41 -0700317 pF2l = F2L;
318 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700319 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700320 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700321 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700322 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700323 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700324 pGet32Static = Field::Get32StaticFromCode;
325 pSet32Static = Field::Set32StaticFromCode;
326 pGet64Static = Field::Get64StaticFromCode;
327 pSet64Static = Field::Set64StaticFromCode;
328 pGetObjStatic = Field::GetObjStaticFromCode;
329 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700330 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700331 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700332 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700333 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700334 pInstanceofNonTrivialFromCode = Object::InstanceOf;
335 pCheckCastFromCode = CheckCastFromCode;
336 pLockObjectFromCode = LockObjectFromCode;
337 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700338 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700339 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700340 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700341 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
342 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
343 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
344 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
345 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
346 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
347 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
348 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700349 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700350 pFindNativeMethod = FindNativeMethod;
351 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700352 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700353}
354
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700355void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700356 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
357 DCHECK_NE(frame_size, 0u);
358 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700359 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700360 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700362 DCHECK(*sp_ == NULL ||
363 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700364}
365
Ian Rogersbdb03912011-09-14 00:55:44 -0700366uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700367 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700368 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700369 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700370}
371
Ian Rogersbdb03912011-09-14 00:55:44 -0700372uintptr_t Frame::LoadCalleeSave(int num) const {
373 // Callee saves are held at the top of the frame
374 Method* method = GetMethod();
375 DCHECK(method != NULL);
376 size_t frame_size = method->GetFrameSizeInBytes();
377 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
378 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700379#if defined(__i386__)
380 save_addr -= kPointerSize; // account for return address
381#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700382 return *reinterpret_cast<uintptr_t*>(save_addr);
383}
384
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700386 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700387 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700389}
390
Brian Carlstrom78128a62011-09-15 17:21:19 -0700391void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700392 Thread* self = reinterpret_cast<Thread*>(arg);
393 Runtime* runtime = Runtime::Current();
394
395 self->Attach(runtime);
396
397 ClassLinker* class_linker = runtime->GetClassLinker();
398
399 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
400 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
401
402 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
403 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
404 if (thread_name != NULL) {
405 SetThreadName(thread_name->ToModifiedUtf8().c_str());
406 }
407
408 // Wait until it's safe to start running code. (There may have been a suspend-all
409 // in progress while we were starting up.)
410 runtime->GetThreadList()->WaitForGo();
411
412 // TODO: say "hi" to the debugger.
413 //if (gDvm.debuggerConnected) {
414 // dvmDbgPostThreadStart(self);
415 //}
416
417 // Invoke the 'run' method of our java.lang.Thread.
418 CHECK(self->peer_ != NULL);
419 Object* receiver = self->peer_;
420 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
421 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
422 m->Invoke(self, receiver, NULL, NULL);
423
424 // Detach.
425 runtime->GetThreadList()->Unregister();
426
Carl Shapirob5573532011-07-12 18:22:59 -0700427 return NULL;
428}
429
Elliott Hughes93e74e82011-09-13 11:07:03 -0700430void SetVmData(Object* managed_thread, Thread* native_thread) {
431 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
432
433 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
434 Class* int_class = class_linker->FindPrimitiveClass('I');
435
436 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
437
438 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
439}
440
Elliott Hughesd369bb72011-09-12 14:41:14 -0700441void Thread::Create(Object* peer, size_t stack_size) {
442 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700443
Elliott Hughesd369bb72011-09-12 14:41:14 -0700444 if (stack_size == 0) {
445 stack_size = Runtime::Current()->GetDefaultStackSize();
446 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700447
Elliott Hughes93e74e82011-09-13 11:07:03 -0700448 Thread* native_thread = new Thread;
449 native_thread->peer_ = peer;
450
451 // Thread.start is synchronized, so we know that vmData is 0,
452 // and know that we're not racing to assign it.
453 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700454
455 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700456 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
457 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
458 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
459 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
460 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700461
462 // Let the child know when it's safe to start running.
463 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700464}
465
Elliott Hughes93e74e82011-09-13 11:07:03 -0700466void Thread::Attach(const Runtime* runtime) {
467 InitCpu();
468 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700469
Elliott Hughes93e74e82011-09-13 11:07:03 -0700470 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700471
Elliott Hughes93e74e82011-09-13 11:07:03 -0700472 tid_ = ::art::GetTid();
473 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700474
Elliott Hughes93e74e82011-09-13 11:07:03 -0700475 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700476
Elliott Hughes8d768a92011-09-14 16:35:25 -0700477 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700478
Elliott Hughes93e74e82011-09-13 11:07:03 -0700479 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700480
Elliott Hughes93e74e82011-09-13 11:07:03 -0700481 runtime->GetThreadList()->Register(this);
482}
483
484Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
485 Thread* self = new Thread;
486 self->Attach(runtime);
487
488 self->SetState(Thread::kRunnable);
489
490 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700491
492 // If we're the main thread, ClassLinker won't be created until after we're attached,
493 // so that thread needs a two-stage attach. Regular threads don't need this hack.
494 if (self->thin_lock_id_ != ThreadList::kMainId) {
495 self->CreatePeer(name, as_daemon);
496 }
497
498 return self;
499}
500
Elliott Hughesd369bb72011-09-12 14:41:14 -0700501jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
502 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
503 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
504 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
505 // This will be null in the compiler (and tests), but never in a running system.
506 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
507 return thread_group;
508}
509
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700510void Thread::CreatePeer(const char* name, bool as_daemon) {
511 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
512
513 JNIEnv* env = jni_env_;
514
Elliott Hughesd369bb72011-09-12 14:41:14 -0700515 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
516 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700517 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700518 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700519 jboolean thread_is_daemon = as_daemon;
520
521 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700522 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700523
Elliott Hughes8daa0922011-09-11 13:46:25 -0700524 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700525
526 // Because we mostly run without code available (in the compiler, in tests), we
527 // manually assign the fields the constructor should have set.
528 // TODO: lose this.
529 jfieldID fid;
530 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
531 env->SetObjectField(peer, fid, thread_group);
532 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
533 env->SetObjectField(peer, fid, thread_name);
534 fid = env->GetFieldID(c, "priority", "I");
535 env->SetIntField(peer, fid, thread_priority);
536 fid = env->GetFieldID(c, "daemon", "Z");
537 env->SetBooleanField(peer, fid, thread_is_daemon);
538
539 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700540}
541
Elliott Hughesbe759c62011-09-08 19:38:21 -0700542void Thread::InitStackHwm() {
543 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700544 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700545
Elliott Hughesbe759c62011-09-08 19:38:21 -0700546 void* stack_base;
547 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700548 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700549
Elliott Hughesbe759c62011-09-08 19:38:21 -0700550 if (stack_size <= kStackOverflowReservedBytes) {
551 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
552 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700553
554 // stack_base is the "lowest addressable byte" of the stack.
555 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
556 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700557 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700558
559 // Sanity check.
560 int stack_variable;
561 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700562
Elliott Hughes8d768a92011-09-14 16:35:25 -0700563 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700564}
565
Elliott Hughesa0957642011-09-02 14:27:33 -0700566void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700567 DumpState(os);
568 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700569}
570
Elliott Hughesd92bec42011-09-02 17:04:36 -0700571std::string GetSchedulerGroup(pid_t tid) {
572 // /proc/<pid>/group looks like this:
573 // 2:devices:/
574 // 1:cpuacct,cpu:/
575 // We want the third field from the line whose second field contains the "cpu" token.
576 std::string cgroup_file;
577 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
578 return "";
579 }
580 std::vector<std::string> cgroup_lines;
581 Split(cgroup_file, '\n', cgroup_lines);
582 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
583 std::vector<std::string> cgroup_fields;
584 Split(cgroup_lines[i], ':', cgroup_fields);
585 std::vector<std::string> cgroups;
586 Split(cgroup_fields[1], ',', cgroups);
587 for (size_t i = 0; i < cgroups.size(); ++i) {
588 if (cgroups[i] == "cpu") {
589 return cgroup_fields[2].substr(1); // Skip the leading slash.
590 }
591 }
592 }
593 return "";
594}
595
596void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700597 std::string thread_name("<native thread without managed peer>");
598 std::string group_name;
599 int priority;
600 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700601
Elliott Hughesd369bb72011-09-12 14:41:14 -0700602 if (peer_ != NULL) {
603 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
604
605 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
606 Class* int_class = class_linker->FindPrimitiveClass('I');
607 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
608 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
609 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
610
611 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
612 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
613 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
614 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
615
616 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
617 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
618 priority = priority_field->GetInt(peer_);
619 is_daemon = daemon_field->GetBoolean(peer_);
620
621 Object* thread_group = thread_group_field->GetObject(peer_);
622 if (thread_group != NULL) {
623 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
624 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
625 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
626 }
627 } else {
628 // 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 -0700629 std::string stats;
630 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
631 size_t start = stats.find('(') + 1;
632 size_t end = stats.find(')') - start;
633 thread_name = stats.substr(start, end);
634 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700635 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700636 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700637
638 int policy;
639 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700640 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700641
642 std::string scheduler_group(GetSchedulerGroup(GetTid()));
643 if (scheduler_group.empty()) {
644 scheduler_group = "default";
645 }
646
Elliott Hughesd92bec42011-09-02 17:04:36 -0700647 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700648 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700649 os << " daemon";
650 }
651 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700652 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700653 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700654
Elliott Hughesd92bec42011-09-02 17:04:36 -0700655 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700656 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700657 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700658 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700659 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700660 << " self=" << reinterpret_cast<const void*>(this) << "\n";
661 os << " | sysTid=" << GetTid()
662 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
663 << " sched=" << policy << "/" << sp.sched_priority
664 << " cgrp=" << scheduler_group
665 << " handle=" << GetImpl() << "\n";
666
667 // Grab the scheduler stats for this thread.
668 std::string scheduler_stats;
669 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
670 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
671 } else {
672 scheduler_stats = "0 0 0";
673 }
674
675 int utime = 0;
676 int stime = 0;
677 int task_cpu = 0;
678 std::string stats;
679 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
680 // Skip the command, which may contain spaces.
681 stats = stats.substr(stats.find(')') + 2);
682 // Extract the three fields we care about.
683 std::vector<std::string> fields;
684 Split(stats, ' ', fields);
685 utime = strtoull(fields[11].c_str(), NULL, 10);
686 stime = strtoull(fields[12].c_str(), NULL, 10);
687 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
688 }
689
690 os << " | schedstat=( " << scheduler_stats << " )"
691 << " utm=" << utime
692 << " stm=" << stime
693 << " core=" << task_cpu
694 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
695}
696
Elliott Hughesd369bb72011-09-12 14:41:14 -0700697struct StackDumpVisitor : public Thread::StackVisitor {
698 StackDumpVisitor(std::ostream& os) : os(os) {
699 }
700
Ian Rogersbdb03912011-09-14 00:55:44 -0700701 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700702 }
703
Ian Rogersbdb03912011-09-14 00:55:44 -0700704 void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700705 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
706
707 Method* m = frame.GetMethod();
708 Class* c = m->GetDeclaringClass();
709 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
710
711 os << " at " << PrettyMethod(m, false);
712 if (m->IsNative()) {
713 os << "(Native method)";
714 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700715 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700716 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
717 }
718 os << "\n";
719 }
720
721 std::ostream& os;
722};
723
Elliott Hughesd92bec42011-09-02 17:04:36 -0700724void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700725 StackDumpVisitor dumper(os);
726 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700727}
728
Elliott Hughes8d768a92011-09-14 16:35:25 -0700729Thread::State Thread::SetState(Thread::State new_state) {
730 Thread::State old_state = state_;
731 if (old_state == new_state) {
732 return old_state;
733 }
734
735 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
736 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
737
738 if (new_state == Thread::kRunnable) {
739 /*
740 * Change our status to Thread::kRunnable. The transition requires
741 * that we check for pending suspension, because the VM considers
742 * us to be "asleep" in all other states, and another thread could
743 * be performing a GC now.
744 *
745 * The order of operations is very significant here. One way to
746 * do this wrong is:
747 *
748 * GCing thread Our thread (in kNative)
749 * ------------ ----------------------
750 * check suspend count (== 0)
751 * SuspendAllThreads()
752 * grab suspend-count lock
753 * increment all suspend counts
754 * release suspend-count lock
755 * check thread state (== kNative)
756 * all are suspended, begin GC
757 * set state to kRunnable
758 * (continue executing)
759 *
760 * We can correct this by grabbing the suspend-count lock and
761 * performing both of our operations (check suspend count, set
762 * state) while holding it, now we need to grab a mutex on every
763 * transition to kRunnable.
764 *
765 * What we do instead is change the order of operations so that
766 * the transition to kRunnable happens first. If we then detect
767 * that the suspend count is nonzero, we switch to kSuspended.
768 *
769 * Appropriate compiler and memory barriers are required to ensure
770 * that the operations are observed in the expected order.
771 *
772 * This does create a small window of opportunity where a GC in
773 * progress could observe what appears to be a running thread (if
774 * it happens to look between when we set to kRunnable and when we
775 * switch to kSuspended). At worst this only affects assertions
776 * and thread logging. (We could work around it with some sort
777 * of intermediate "pre-running" state that is generally treated
778 * as equivalent to running, but that doesn't seem worthwhile.)
779 *
780 * We can also solve this by combining the "status" and "suspend
781 * count" fields into a single 32-bit value. This trades the
782 * store/load barrier on transition to kRunnable for an atomic RMW
783 * op on all transitions and all suspend count updates (also, all
784 * accesses to status or the thread count require bit-fiddling).
785 * It also eliminates the brief transition through kRunnable when
786 * the thread is supposed to be suspended. This is possibly faster
787 * on SMP and slightly more correct, but less convenient.
788 */
789 android_atomic_acquire_store(new_state, addr);
790 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
791 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
792 }
793 } else {
794 /*
795 * Not changing to Thread::kRunnable. No additional work required.
796 *
797 * We use a releasing store to ensure that, if we were runnable,
798 * any updates we previously made to objects on the managed heap
799 * will be observed before the state change.
800 */
801 android_atomic_release_store(new_state, addr);
802 }
803
804 return old_state;
805}
806
807void Thread::WaitUntilSuspended() {
808 // TODO: dalvik dropped the waiting thread's priority after a while.
809 // TODO: dalvik timed out and aborted.
810 useconds_t delay = 0;
811 while (GetState() == Thread::kRunnable) {
812 useconds_t new_delay = delay * 2;
813 CHECK_GE(new_delay, delay);
814 delay = new_delay;
815 if (delay == 0) {
816 sched_yield();
817 delay = 10000;
818 } else {
819 usleep(delay);
820 }
821 }
822}
823
Elliott Hughesbe759c62011-09-08 19:38:21 -0700824void Thread::ThreadExitCallback(void* arg) {
825 Thread* self = reinterpret_cast<Thread*>(arg);
826 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700827}
828
Elliott Hughesbe759c62011-09-08 19:38:21 -0700829void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700830 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700831 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700832
833 // Double-check the TLS slot allocation.
834 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700835 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700836 }
837
838 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700839}
840
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700841void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700842 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700843}
844
Elliott Hughesdcc24742011-09-07 14:02:44 -0700845Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700846 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700847 wait_mutex_(new Mutex("Thread wait mutex")),
848 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700849 wait_monitor_(NULL),
850 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700851 wait_next_(NULL),
852 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700853 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700854 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700855 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700856 native_to_managed_record_(NULL),
857 top_sirt_(NULL),
858 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700859 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700860 self_(NULL),
861 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700862 exception_(NULL),
863 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700864 class_loader_override_(NULL),
865 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700866}
867
Elliott Hughes02b48d12011-09-07 17:15:51 -0700868void MonitorExitVisitor(const Object* object, void*) {
869 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700870 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700871}
872
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700873Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700874 // TODO: check we're not calling the JNI DetachCurrentThread function from
875 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
876
877 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700878 if (jni_env_ != NULL) {
879 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
880 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700881
882 if (IsExceptionPending()) {
883 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
884 }
885
886 // TODO: ThreadGroup.removeThread(this);
887
Elliott Hughes93e74e82011-09-13 11:07:03 -0700888 if (peer_ != NULL) {
889 SetVmData(peer_, NULL);
890 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700891
892 // TODO: say "bye" to the debugger.
893 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700894 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700895 //}
896
897 // Thread.join() is implemented as an Object.wait() on the Thread.lock
898 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700899 if (peer_ != NULL) {
900 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
901 Class* java_lang_Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
902 Class* java_lang_ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
903 Field* lock_field = java_lang_Thread_class->FindDeclaredInstanceField("lock", java_lang_ThreadLock_class);
904
905 Thread* self = Thread::Current();
906 Object* lock = lock_field->GetObject(peer_);
907 // This conditional is only needed for tests, where Thread.lock won't have been set.
908 if (lock != NULL) {
909 lock->MonitorEnter(self);
910 lock->NotifyAll();
911 lock->MonitorExit(self);
912 }
913 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700914
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700915 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700916 jni_env_ = NULL;
917
918 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700919
920 delete wait_cond_;
921 delete wait_mutex_;
922
923 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700924}
925
Ian Rogers408f79a2011-08-23 18:22:33 -0700926size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700927 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700928 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700929 count += cur->NumberOfReferences();
930 }
931 return count;
932}
933
Ian Rogers408f79a2011-08-23 18:22:33 -0700934bool Thread::SirtContains(jobject obj) {
935 Object** sirt_entry = reinterpret_cast<Object**>(obj);
936 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700937 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700938 // A SIRT should always have a jobject/jclass as a native method is passed
939 // in a this pointer or a class
940 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700941 if ((&cur->References()[0] <= sirt_entry) &&
942 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700943 return true;
944 }
945 }
946 return false;
947}
948
Ian Rogers67375ac2011-09-14 00:55:44 -0700949void Thread::PopSirt() {
950 CHECK(top_sirt_ != NULL);
951 top_sirt_ = top_sirt_->Link();
952}
953
Ian Rogers408f79a2011-08-23 18:22:33 -0700954Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700955 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700956 if (obj == NULL) {
957 return NULL;
958 }
959 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
960 IndirectRefKind kind = GetIndirectRefKind(ref);
961 Object* result;
962 switch (kind) {
963 case kLocal:
964 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700965 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700966 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700967 break;
968 }
969 case kGlobal:
970 {
971 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
972 IndirectReferenceTable& globals = vm->globals;
973 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700974 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700975 break;
976 }
977 case kWeakGlobal:
978 {
979 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
980 IndirectReferenceTable& weak_globals = vm->weak_globals;
981 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700982 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700983 if (result == kClearedJniWeakGlobal) {
984 // This is a special case where it's okay to return NULL.
985 return NULL;
986 }
987 break;
988 }
989 case kSirtOrInvalid:
990 default:
991 // TODO: make stack indirect reference table lookup more efficient
992 // Check if this is a local reference in the SIRT
993 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700994 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700995 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700996 // Assume an invalid local reference is actually a direct pointer.
997 result = reinterpret_cast<Object*>(obj);
998 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700999 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001000 }
1001 }
1002
1003 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001004 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1005 JniAbort(NULL);
1006 } else {
1007 if (result != kInvalidIndirectRefObject) {
1008 Heap::VerifyObject(result);
1009 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001010 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001011 return result;
1012}
1013
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001014class CountStackDepthVisitor : public Thread::StackVisitor {
1015 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001016 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001017
Ian Rogersbdb03912011-09-14 00:55:44 -07001018 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001019 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001020 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001021
1022 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001023 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001024 }
1025
1026 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001027 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001028};
1029
Ian Rogersaaa20802011-09-11 21:47:37 -07001030//
1031class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001032 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001033 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1034 // Allocate method trace with an extra slot that will hold the PC trace
1035 method_trace_ = Runtime::Current()->GetClassLinker()->
1036 AllocObjectArray<Object>(depth + 1);
1037 // Register a local reference as IntArray::Alloc may trigger GC
1038 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1039 pc_trace_ = IntArray::Alloc(depth);
1040#ifdef MOVING_GARBAGE_COLLECTOR
1041 // Re-read after potential GC
1042 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1043#endif
1044 // Save PC trace in last element of method trace, also places it into the
1045 // object graph.
1046 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001047 }
1048
Ian Rogersaaa20802011-09-11 21:47:37 -07001049 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001050
Ian Rogersbdb03912011-09-14 00:55:44 -07001051 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001052 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001053 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001054 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001055 }
1056
Ian Rogersaaa20802011-09-11 21:47:37 -07001057 jobject GetInternalStackTrace() const {
1058 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001059 }
1060
1061 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001062 // Current position down stack trace
1063 uint32_t count_;
1064 // Array of return PC values
1065 IntArray* pc_trace_;
1066 // An array of the methods on the stack, the last entry is a reference to the
1067 // PC trace
1068 ObjectArray<Object>* method_trace_;
1069 // Local indirect reference table entry for method trace
1070 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001071};
1072
Ian Rogersaaa20802011-09-11 21:47:37 -07001073void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001074 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001075 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001076 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1077 // CHECK(native_to_managed_record_ != NULL);
1078 NativeToManagedRecord* record = native_to_managed_record_;
1079
Ian Rogersbdb03912011-09-14 00:55:44 -07001080 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001081 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001082 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1083 visitor->VisitFrame(frame, pc);
1084 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001085 }
1086 if (record == NULL) {
1087 break;
1088 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001089 // last_tos should return Frame instead of sp?
1090 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1091 pc = record->last_top_of_managed_stack_pc_;
1092 record = record->link_;
1093 }
1094}
1095
Ian Rogers67375ac2011-09-14 00:55:44 -07001096void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001097 Frame frame = GetTopOfStack();
1098 uintptr_t pc = top_of_managed_stack_pc_;
1099
1100 if (frame.GetSP() != 0) {
1101 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001102 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001103 visitor->VisitFrame(frame, pc);
1104 pc = frame.GetReturnPC();
1105 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001106 if (include_upcall) {
1107 visitor->VisitFrame(frame, pc);
1108 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001109 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001110}
1111
Ian Rogersaaa20802011-09-11 21:47:37 -07001112jobject Thread::CreateInternalStackTrace() const {
1113 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001114 CountStackDepthVisitor count_visitor;
1115 WalkStack(&count_visitor);
1116 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001117
Ian Rogersaaa20802011-09-11 21:47:37 -07001118 // Transition into runnable state to work on Object*/Array*
1119 ScopedJniThreadState ts(jni_env_);
1120
1121 // Build internal stack trace
1122 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001123 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001124
Ian Rogersaaa20802011-09-11 21:47:37 -07001125 return build_trace_visitor.GetInternalStackTrace();
1126}
1127
1128jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1129 JNIEnv* env) {
1130 // Transition into runnable state to work on Object*/Array*
1131 ScopedJniThreadState ts(env);
1132
1133 // Decode the internal stack trace into the depth, method trace and PC trace
1134 ObjectArray<Object>* method_trace =
1135 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1136 int32_t depth = method_trace->GetLength()-1;
1137 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1138
1139 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1140
1141 // Create java_trace array and place in local reference table
1142 ObjectArray<StackTraceElement>* java_traces =
1143 class_linker->AllocStackTraceElementArray(depth);
1144 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001145
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001146 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001147 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1148 Method* method = down_cast<Method*>(method_trace->Get(i));
1149 uint32_t native_pc = pc_trace->Get(i);
1150 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001151 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001152 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001153
Ian Rogersaaa20802011-09-11 21:47:37 -07001154 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001155 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001156 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001157 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001158 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001159 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001160 method->ToDexPC(native_pc)));
1161#ifdef MOVING_GARBAGE_COLLECTOR
1162 // Re-read after potential GC
1163 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1164 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1165 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1166#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001167 java_traces->Set(i, obj);
1168 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001169 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001170}
1171
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001172void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001173 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001174 va_list args;
1175 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001176 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001177 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001178
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001179 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001180 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001181 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001182 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001183 descriptor.erase(descriptor.length() - 1);
1184
1185 JNIEnv* env = GetJniEnv();
1186 jclass exception_class = env->FindClass(descriptor.c_str());
1187 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1188 int rc = env->ThrowNew(exception_class, msg.c_str());
1189 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001190}
1191
Elliott Hughes79082e32011-08-25 12:07:32 -07001192void Thread::ThrowOutOfMemoryError() {
1193 UNIMPLEMENTED(FATAL);
1194}
1195
Ian Rogersbdb03912011-09-14 00:55:44 -07001196Method* Thread::CalleeSaveMethod() const {
1197 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001198 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001199#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001200 method->SetCode(NULL, art::kThumb2, NULL);
1201 method->SetFrameSizeInBytes(64);
1202 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001203 method->SetCoreSpillMask((1 << art::arm::R1) |
1204 (1 << art::arm::R2) |
1205 (1 << art::arm::R3) |
1206 (1 << art::arm::R4) |
1207 (1 << art::arm::R5) |
1208 (1 << art::arm::R6) |
1209 (1 << art::arm::R7) |
1210 (1 << art::arm::R8) |
1211 (1 << art::arm::R9) |
1212 (1 << art::arm::R10) |
1213 (1 << art::arm::R11) |
1214 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001215 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001216#elif defined(__i386__)
1217 method->SetCode(NULL, art::kX86, NULL);
1218 method->SetFrameSizeInBytes(32);
1219 method->SetReturnPcOffsetInBytes(28);
1220 method->SetCoreSpillMask((1 << art::x86::EBX) |
1221 (1 << art::x86::EBP) |
1222 (1 << art::x86::ESI) |
1223 (1 << art::x86::EDI));
1224 method->SetFpSpillMask(0);
1225#else
1226 UNIMPLEMENTED(FATAL);
1227#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001228 return method;
1229}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001230
Ian Rogersbdb03912011-09-14 00:55:44 -07001231class CatchBlockStackVisitor : public Thread::StackVisitor {
1232 public:
1233 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001234 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1235#ifndef NDEBUG
1236 handler_pc_ = 0xEBADC0DE;
1237 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1238#endif
1239 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001240
Ian Rogersbdb03912011-09-14 00:55:44 -07001241 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1242 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001243 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001244 if (method == NULL) {
1245 // This is the upcall, we remember the frame and last_pc so that we may
1246 // long jump to them
1247 handler_pc_ = pc;
1248 handler_frame_ = fr;
1249 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001250 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001251 uint32_t dex_pc = DexFile::kDexNoIndex;
1252 if (pc > 0) {
1253 if (method->IsNative()) {
1254 native_method_count_++;
1255 } else {
1256 // Move the PC back 2 bytes as a call will frequently terminate the
1257 // decoding of a particular instruction and we want to make sure we
1258 // get the Dex PC of the instruction with the call and not the
1259 // instruction following.
1260 pc -= 2;
1261 dex_pc = method->ToDexPC(pc);
1262 }
1263 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001264 if (dex_pc != DexFile::kDexNoIndex) {
1265 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1266 if (found_dex_pc != DexFile::kDexNoIndex) {
1267 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001268 handler_pc_ = method->ToNativePC(found_dex_pc);
1269 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001270 }
1271 }
1272 if (!found_) {
1273 // Caller may be handler, fill in callee saves in context
1274 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001275 }
1276 }
1277 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001278
1279 // Did we find a catch block yet?
1280 bool found_;
1281 // The type of the exception catch block to find
1282 Class* to_find_;
1283 // Frame with found handler or last frame if no handler found
1284 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001285 // PC to branch to for the handler
1286 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001287 // Context that will be the target of the long jump
1288 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001289 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1290 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001291};
1292
1293void Thread::DeliverException(Throwable* exception) {
1294 SetException(exception); // Set exception on thread
1295
1296 Context* long_jump_context = GetLongJumpContext();
1297 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001298 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001299
Ian Rogers67375ac2011-09-14 00:55:44 -07001300 // Pop any SIRT
1301 if (catch_finder.native_method_count_ == 1) {
1302 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001303 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001304 // We only expect the stack crawl to have passed 1 native method as it's terminated
1305 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001306 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001307 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001308 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1309 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001310 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001311}
1312
Ian Rogersbdb03912011-09-14 00:55:44 -07001313Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001314 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001315 if (result == NULL) {
1316 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001317 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001318 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001319 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001320}
1321
Elliott Hughes5f791332011-09-15 17:45:30 -07001322bool Thread::HoldsLock(Object* object) {
1323 if (object == NULL) {
1324 return false;
1325 }
1326 return object->GetLockOwner() == thin_lock_id_;
1327}
1328
Elliott Hughes410c0c82011-09-01 17:58:25 -07001329void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001330 if (exception_ != NULL) {
1331 visitor(exception_, arg);
1332 }
1333 if (peer_ != NULL) {
1334 visitor(peer_, arg);
1335 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001336 jni_env_->locals.VisitRoots(visitor, arg);
1337 jni_env_->monitors.VisitRoots(visitor, arg);
1338 // visitThreadStack(visitor, thread, arg);
1339 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1340}
1341
Ian Rogersb033c752011-07-20 12:22:35 -07001342static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001343 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001344 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001345 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001346 "Blocked",
1347 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001348 "Initializing",
1349 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001350 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001351 "VmWait",
1352 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001353};
1354std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001355 int int_state = static_cast<int>(state);
1356 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1357 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001358 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001359 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001360 }
1361 return os;
1362}
1363
Elliott Hughes330304d2011-08-12 14:28:05 -07001364std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1365 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001366 << ",pthread_t=" << thread.GetImpl()
1367 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001368 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001369 << ",state=" << thread.GetState()
1370 << ",peer=" << thread.GetPeer()
1371 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001372 return os;
1373}
1374
Elliott Hughes8daa0922011-09-11 13:46:25 -07001375} // namespace art