blob: 92b3d4fd6c3deff4baf59dcb28fa97928aa025f3 [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 pDeliverException = art_deliver_exception;
316#endif
317#if defined(__i386__)
318 pDeliverException = art_deliver_exception;
buzbee54330722011-08-23 16:46:55 -0700319#endif
buzbeec396efc2011-09-11 09:36:41 -0700320 pF2l = F2L;
321 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700322 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700323 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700324 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700325 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700326 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700327 pGet32Static = Field::Get32StaticFromCode;
328 pSet32Static = Field::Set32StaticFromCode;
329 pGet64Static = Field::Get64StaticFromCode;
330 pSet64Static = Field::Set64StaticFromCode;
331 pGetObjStatic = Field::GetObjStaticFromCode;
332 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700333 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700334 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700335 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700336 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700337 pInstanceofNonTrivialFromCode = Object::InstanceOf;
338 pCheckCastFromCode = CheckCastFromCode;
339 pLockObjectFromCode = LockObjectFromCode;
340 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700341 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700342 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700343 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700344 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
345 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
346 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
347 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
348 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
349 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
350 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
351 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700352 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700353 pFindNativeMethod = FindNativeMethod;
354 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700355 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700356}
357
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700358void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700359 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
360 DCHECK_NE(frame_size, 0u);
361 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700362 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700363 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700365 DCHECK(*sp_ == NULL ||
366 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700367}
368
Ian Rogersbdb03912011-09-14 00:55:44 -0700369uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700370 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700371 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700372 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700373}
374
Ian Rogersbdb03912011-09-14 00:55:44 -0700375uintptr_t Frame::LoadCalleeSave(int num) const {
376 // Callee saves are held at the top of the frame
377 Method* method = GetMethod();
378 DCHECK(method != NULL);
379 size_t frame_size = method->GetFrameSizeInBytes();
380 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
381 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700382#if defined(__i386__)
383 save_addr -= kPointerSize; // account for return address
384#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700385 return *reinterpret_cast<uintptr_t*>(save_addr);
386}
387
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700389 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700390 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700392}
393
Brian Carlstrom78128a62011-09-15 17:21:19 -0700394void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700395 Thread* self = reinterpret_cast<Thread*>(arg);
396 Runtime* runtime = Runtime::Current();
397
398 self->Attach(runtime);
399
400 ClassLinker* class_linker = runtime->GetClassLinker();
401
402 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
403 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
404
405 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
406 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
407 if (thread_name != NULL) {
408 SetThreadName(thread_name->ToModifiedUtf8().c_str());
409 }
410
411 // Wait until it's safe to start running code. (There may have been a suspend-all
412 // in progress while we were starting up.)
413 runtime->GetThreadList()->WaitForGo();
414
415 // TODO: say "hi" to the debugger.
416 //if (gDvm.debuggerConnected) {
417 // dvmDbgPostThreadStart(self);
418 //}
419
420 // Invoke the 'run' method of our java.lang.Thread.
421 CHECK(self->peer_ != NULL);
422 Object* receiver = self->peer_;
423 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
424 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
425 m->Invoke(self, receiver, NULL, NULL);
426
427 // Detach.
428 runtime->GetThreadList()->Unregister();
429
Carl Shapirob5573532011-07-12 18:22:59 -0700430 return NULL;
431}
432
Elliott Hughes93e74e82011-09-13 11:07:03 -0700433void SetVmData(Object* managed_thread, Thread* native_thread) {
434 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
435
436 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
437 Class* int_class = class_linker->FindPrimitiveClass('I');
438
439 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
440
441 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
442}
443
Elliott Hughesd369bb72011-09-12 14:41:14 -0700444void Thread::Create(Object* peer, size_t stack_size) {
445 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700446
Elliott Hughesd369bb72011-09-12 14:41:14 -0700447 if (stack_size == 0) {
448 stack_size = Runtime::Current()->GetDefaultStackSize();
449 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700450
Elliott Hughes93e74e82011-09-13 11:07:03 -0700451 Thread* native_thread = new Thread;
452 native_thread->peer_ = peer;
453
454 // Thread.start is synchronized, so we know that vmData is 0,
455 // and know that we're not racing to assign it.
456 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700457
458 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700459 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
460 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
461 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
462 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
463 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700464
465 // Let the child know when it's safe to start running.
466 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700467}
468
Elliott Hughes93e74e82011-09-13 11:07:03 -0700469void Thread::Attach(const Runtime* runtime) {
470 InitCpu();
471 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700472
Elliott Hughes93e74e82011-09-13 11:07:03 -0700473 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700474
Elliott Hughes93e74e82011-09-13 11:07:03 -0700475 tid_ = ::art::GetTid();
476 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700477
Elliott Hughes93e74e82011-09-13 11:07:03 -0700478 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700479
Elliott Hughes8d768a92011-09-14 16:35:25 -0700480 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700481
Elliott Hughes93e74e82011-09-13 11:07:03 -0700482 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700483
Elliott Hughes93e74e82011-09-13 11:07:03 -0700484 runtime->GetThreadList()->Register(this);
485}
486
487Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
488 Thread* self = new Thread;
489 self->Attach(runtime);
490
491 self->SetState(Thread::kRunnable);
492
493 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700494
495 // If we're the main thread, ClassLinker won't be created until after we're attached,
496 // so that thread needs a two-stage attach. Regular threads don't need this hack.
497 if (self->thin_lock_id_ != ThreadList::kMainId) {
498 self->CreatePeer(name, as_daemon);
499 }
500
501 return self;
502}
503
Elliott Hughesd369bb72011-09-12 14:41:14 -0700504jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
505 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
506 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
507 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
508 // This will be null in the compiler (and tests), but never in a running system.
509 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
510 return thread_group;
511}
512
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700513void Thread::CreatePeer(const char* name, bool as_daemon) {
514 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
515
516 JNIEnv* env = jni_env_;
517
Elliott Hughesd369bb72011-09-12 14:41:14 -0700518 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
519 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700520 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700521 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700522 jboolean thread_is_daemon = as_daemon;
523
524 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700525 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700526
Elliott Hughes8daa0922011-09-11 13:46:25 -0700527 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700528
529 // Because we mostly run without code available (in the compiler, in tests), we
530 // manually assign the fields the constructor should have set.
531 // TODO: lose this.
532 jfieldID fid;
533 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
534 env->SetObjectField(peer, fid, thread_group);
535 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
536 env->SetObjectField(peer, fid, thread_name);
537 fid = env->GetFieldID(c, "priority", "I");
538 env->SetIntField(peer, fid, thread_priority);
539 fid = env->GetFieldID(c, "daemon", "Z");
540 env->SetBooleanField(peer, fid, thread_is_daemon);
541
542 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700543}
544
Elliott Hughesbe759c62011-09-08 19:38:21 -0700545void Thread::InitStackHwm() {
546 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700547 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700548
Elliott Hughesbe759c62011-09-08 19:38:21 -0700549 void* stack_base;
550 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700551 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700552
Elliott Hughesbe759c62011-09-08 19:38:21 -0700553 if (stack_size <= kStackOverflowReservedBytes) {
554 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
555 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700556
557 // stack_base is the "lowest addressable byte" of the stack.
558 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
559 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700560 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700561
562 // Sanity check.
563 int stack_variable;
564 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700565
Elliott Hughes8d768a92011-09-14 16:35:25 -0700566 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700567}
568
Elliott Hughesa0957642011-09-02 14:27:33 -0700569void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700570 DumpState(os);
571 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700572}
573
Elliott Hughesd92bec42011-09-02 17:04:36 -0700574std::string GetSchedulerGroup(pid_t tid) {
575 // /proc/<pid>/group looks like this:
576 // 2:devices:/
577 // 1:cpuacct,cpu:/
578 // We want the third field from the line whose second field contains the "cpu" token.
579 std::string cgroup_file;
580 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
581 return "";
582 }
583 std::vector<std::string> cgroup_lines;
584 Split(cgroup_file, '\n', cgroup_lines);
585 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
586 std::vector<std::string> cgroup_fields;
587 Split(cgroup_lines[i], ':', cgroup_fields);
588 std::vector<std::string> cgroups;
589 Split(cgroup_fields[1], ',', cgroups);
590 for (size_t i = 0; i < cgroups.size(); ++i) {
591 if (cgroups[i] == "cpu") {
592 return cgroup_fields[2].substr(1); // Skip the leading slash.
593 }
594 }
595 }
596 return "";
597}
598
599void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700600 std::string thread_name("<native thread without managed peer>");
601 std::string group_name;
602 int priority;
603 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700604
Elliott Hughesd369bb72011-09-12 14:41:14 -0700605 if (peer_ != NULL) {
606 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
607
608 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
609 Class* int_class = class_linker->FindPrimitiveClass('I');
610 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
611 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
612 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
613
614 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
615 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
616 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
617 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
618
619 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
620 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
621 priority = priority_field->GetInt(peer_);
622 is_daemon = daemon_field->GetBoolean(peer_);
623
624 Object* thread_group = thread_group_field->GetObject(peer_);
625 if (thread_group != NULL) {
626 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
627 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
628 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
629 }
630 } else {
631 // 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 -0700632 std::string stats;
633 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
634 size_t start = stats.find('(') + 1;
635 size_t end = stats.find(')') - start;
636 thread_name = stats.substr(start, end);
637 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700638 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700639 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700640
641 int policy;
642 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700643 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700644
645 std::string scheduler_group(GetSchedulerGroup(GetTid()));
646 if (scheduler_group.empty()) {
647 scheduler_group = "default";
648 }
649
Elliott Hughesd92bec42011-09-02 17:04:36 -0700650 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700651 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700652 os << " daemon";
653 }
654 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700655 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700656 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700657
Elliott Hughesd92bec42011-09-02 17:04:36 -0700658 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700659 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700660 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700661 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700662 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700663 << " self=" << reinterpret_cast<const void*>(this) << "\n";
664 os << " | sysTid=" << GetTid()
665 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
666 << " sched=" << policy << "/" << sp.sched_priority
667 << " cgrp=" << scheduler_group
668 << " handle=" << GetImpl() << "\n";
669
670 // Grab the scheduler stats for this thread.
671 std::string scheduler_stats;
672 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
673 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
674 } else {
675 scheduler_stats = "0 0 0";
676 }
677
678 int utime = 0;
679 int stime = 0;
680 int task_cpu = 0;
681 std::string stats;
682 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
683 // Skip the command, which may contain spaces.
684 stats = stats.substr(stats.find(')') + 2);
685 // Extract the three fields we care about.
686 std::vector<std::string> fields;
687 Split(stats, ' ', fields);
688 utime = strtoull(fields[11].c_str(), NULL, 10);
689 stime = strtoull(fields[12].c_str(), NULL, 10);
690 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
691 }
692
693 os << " | schedstat=( " << scheduler_stats << " )"
694 << " utm=" << utime
695 << " stm=" << stime
696 << " core=" << task_cpu
697 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
698}
699
Elliott Hughesd369bb72011-09-12 14:41:14 -0700700struct StackDumpVisitor : public Thread::StackVisitor {
701 StackDumpVisitor(std::ostream& os) : os(os) {
702 }
703
Ian Rogersbdb03912011-09-14 00:55:44 -0700704 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700705 }
706
Ian Rogersbdb03912011-09-14 00:55:44 -0700707 void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700708 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
709
710 Method* m = frame.GetMethod();
711 Class* c = m->GetDeclaringClass();
712 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
713
714 os << " at " << PrettyMethod(m, false);
715 if (m->IsNative()) {
716 os << "(Native method)";
717 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700718 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700719 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
720 }
721 os << "\n";
722 }
723
724 std::ostream& os;
725};
726
Elliott Hughesd92bec42011-09-02 17:04:36 -0700727void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700728 StackDumpVisitor dumper(os);
729 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700730}
731
Elliott Hughes8d768a92011-09-14 16:35:25 -0700732Thread::State Thread::SetState(Thread::State new_state) {
733 Thread::State old_state = state_;
734 if (old_state == new_state) {
735 return old_state;
736 }
737
738 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
739 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
740
741 if (new_state == Thread::kRunnable) {
742 /*
743 * Change our status to Thread::kRunnable. The transition requires
744 * that we check for pending suspension, because the VM considers
745 * us to be "asleep" in all other states, and another thread could
746 * be performing a GC now.
747 *
748 * The order of operations is very significant here. One way to
749 * do this wrong is:
750 *
751 * GCing thread Our thread (in kNative)
752 * ------------ ----------------------
753 * check suspend count (== 0)
754 * SuspendAllThreads()
755 * grab suspend-count lock
756 * increment all suspend counts
757 * release suspend-count lock
758 * check thread state (== kNative)
759 * all are suspended, begin GC
760 * set state to kRunnable
761 * (continue executing)
762 *
763 * We can correct this by grabbing the suspend-count lock and
764 * performing both of our operations (check suspend count, set
765 * state) while holding it, now we need to grab a mutex on every
766 * transition to kRunnable.
767 *
768 * What we do instead is change the order of operations so that
769 * the transition to kRunnable happens first. If we then detect
770 * that the suspend count is nonzero, we switch to kSuspended.
771 *
772 * Appropriate compiler and memory barriers are required to ensure
773 * that the operations are observed in the expected order.
774 *
775 * This does create a small window of opportunity where a GC in
776 * progress could observe what appears to be a running thread (if
777 * it happens to look between when we set to kRunnable and when we
778 * switch to kSuspended). At worst this only affects assertions
779 * and thread logging. (We could work around it with some sort
780 * of intermediate "pre-running" state that is generally treated
781 * as equivalent to running, but that doesn't seem worthwhile.)
782 *
783 * We can also solve this by combining the "status" and "suspend
784 * count" fields into a single 32-bit value. This trades the
785 * store/load barrier on transition to kRunnable for an atomic RMW
786 * op on all transitions and all suspend count updates (also, all
787 * accesses to status or the thread count require bit-fiddling).
788 * It also eliminates the brief transition through kRunnable when
789 * the thread is supposed to be suspended. This is possibly faster
790 * on SMP and slightly more correct, but less convenient.
791 */
792 android_atomic_acquire_store(new_state, addr);
793 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
794 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
795 }
796 } else {
797 /*
798 * Not changing to Thread::kRunnable. No additional work required.
799 *
800 * We use a releasing store to ensure that, if we were runnable,
801 * any updates we previously made to objects on the managed heap
802 * will be observed before the state change.
803 */
804 android_atomic_release_store(new_state, addr);
805 }
806
807 return old_state;
808}
809
810void Thread::WaitUntilSuspended() {
811 // TODO: dalvik dropped the waiting thread's priority after a while.
812 // TODO: dalvik timed out and aborted.
813 useconds_t delay = 0;
814 while (GetState() == Thread::kRunnable) {
815 useconds_t new_delay = delay * 2;
816 CHECK_GE(new_delay, delay);
817 delay = new_delay;
818 if (delay == 0) {
819 sched_yield();
820 delay = 10000;
821 } else {
822 usleep(delay);
823 }
824 }
825}
826
Elliott Hughesbe759c62011-09-08 19:38:21 -0700827void Thread::ThreadExitCallback(void* arg) {
828 Thread* self = reinterpret_cast<Thread*>(arg);
829 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700830}
831
Elliott Hughesbe759c62011-09-08 19:38:21 -0700832void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700833 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700834 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700835
836 // Double-check the TLS slot allocation.
837 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700838 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700839 }
840
841 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700842}
843
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700844void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700845 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700846}
847
Elliott Hughesdcc24742011-09-07 14:02:44 -0700848Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700849 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700850 wait_mutex_(new Mutex("Thread wait mutex")),
851 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700852 wait_monitor_(NULL),
853 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700854 wait_next_(NULL),
855 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700856 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700857 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700858 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700859 native_to_managed_record_(NULL),
860 top_sirt_(NULL),
861 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700862 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700863 self_(NULL),
864 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700865 exception_(NULL),
866 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700867 class_loader_override_(NULL),
868 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700869}
870
Elliott Hughes02b48d12011-09-07 17:15:51 -0700871void MonitorExitVisitor(const Object* object, void*) {
872 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700873 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700874}
875
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700876Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700877 // TODO: check we're not calling the JNI DetachCurrentThread function from
878 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
879
880 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700881 if (jni_env_ != NULL) {
882 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
883 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700884
885 if (IsExceptionPending()) {
886 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
887 }
888
889 // TODO: ThreadGroup.removeThread(this);
890
Elliott Hughes93e74e82011-09-13 11:07:03 -0700891 if (peer_ != NULL) {
892 SetVmData(peer_, NULL);
893 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700894
895 // TODO: say "bye" to the debugger.
896 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700897 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700898 //}
899
900 // Thread.join() is implemented as an Object.wait() on the Thread.lock
901 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700902 if (peer_ != NULL) {
903 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
904 Class* java_lang_Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
905 Class* java_lang_ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
906 Field* lock_field = java_lang_Thread_class->FindDeclaredInstanceField("lock", java_lang_ThreadLock_class);
907
908 Thread* self = Thread::Current();
909 Object* lock = lock_field->GetObject(peer_);
910 // This conditional is only needed for tests, where Thread.lock won't have been set.
911 if (lock != NULL) {
912 lock->MonitorEnter(self);
913 lock->NotifyAll();
914 lock->MonitorExit(self);
915 }
916 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700917
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700918 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700919 jni_env_ = NULL;
920
921 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700922
923 delete wait_cond_;
924 delete wait_mutex_;
925
926 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700927}
928
Ian Rogers408f79a2011-08-23 18:22:33 -0700929size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700930 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700931 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700932 count += cur->NumberOfReferences();
933 }
934 return count;
935}
936
Ian Rogers408f79a2011-08-23 18:22:33 -0700937bool Thread::SirtContains(jobject obj) {
938 Object** sirt_entry = reinterpret_cast<Object**>(obj);
939 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700940 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700941 // A SIRT should always have a jobject/jclass as a native method is passed
942 // in a this pointer or a class
943 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700944 if ((&cur->References()[0] <= sirt_entry) &&
945 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700946 return true;
947 }
948 }
949 return false;
950}
951
Ian Rogers67375ac2011-09-14 00:55:44 -0700952void Thread::PopSirt() {
953 CHECK(top_sirt_ != NULL);
954 top_sirt_ = top_sirt_->Link();
955}
956
Ian Rogers408f79a2011-08-23 18:22:33 -0700957Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700958 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700959 if (obj == NULL) {
960 return NULL;
961 }
962 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
963 IndirectRefKind kind = GetIndirectRefKind(ref);
964 Object* result;
965 switch (kind) {
966 case kLocal:
967 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700968 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700969 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700970 break;
971 }
972 case kGlobal:
973 {
974 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
975 IndirectReferenceTable& globals = vm->globals;
976 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700977 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700978 break;
979 }
980 case kWeakGlobal:
981 {
982 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
983 IndirectReferenceTable& weak_globals = vm->weak_globals;
984 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700985 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700986 if (result == kClearedJniWeakGlobal) {
987 // This is a special case where it's okay to return NULL.
988 return NULL;
989 }
990 break;
991 }
992 case kSirtOrInvalid:
993 default:
994 // TODO: make stack indirect reference table lookup more efficient
995 // Check if this is a local reference in the SIRT
996 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700997 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700998 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700999 // Assume an invalid local reference is actually a direct pointer.
1000 result = reinterpret_cast<Object*>(obj);
1001 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001002 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001003 }
1004 }
1005
1006 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001007 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1008 JniAbort(NULL);
1009 } else {
1010 if (result != kInvalidIndirectRefObject) {
1011 Heap::VerifyObject(result);
1012 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001013 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001014 return result;
1015}
1016
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001017class CountStackDepthVisitor : public Thread::StackVisitor {
1018 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001019 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001020
Ian Rogersbdb03912011-09-14 00:55:44 -07001021 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001022 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001023 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001024
1025 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001026 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001027 }
1028
1029 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001030 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001031};
1032
Ian Rogersaaa20802011-09-11 21:47:37 -07001033//
1034class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001035 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001036 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1037 // Allocate method trace with an extra slot that will hold the PC trace
1038 method_trace_ = Runtime::Current()->GetClassLinker()->
1039 AllocObjectArray<Object>(depth + 1);
1040 // Register a local reference as IntArray::Alloc may trigger GC
1041 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1042 pc_trace_ = IntArray::Alloc(depth);
1043#ifdef MOVING_GARBAGE_COLLECTOR
1044 // Re-read after potential GC
1045 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1046#endif
1047 // Save PC trace in last element of method trace, also places it into the
1048 // object graph.
1049 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001050 }
1051
Ian Rogersaaa20802011-09-11 21:47:37 -07001052 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001053
Ian Rogersbdb03912011-09-14 00:55:44 -07001054 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001055 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001056 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001057 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001058 }
1059
Ian Rogersaaa20802011-09-11 21:47:37 -07001060 jobject GetInternalStackTrace() const {
1061 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001062 }
1063
1064 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001065 // Current position down stack trace
1066 uint32_t count_;
1067 // Array of return PC values
1068 IntArray* pc_trace_;
1069 // An array of the methods on the stack, the last entry is a reference to the
1070 // PC trace
1071 ObjectArray<Object>* method_trace_;
1072 // Local indirect reference table entry for method trace
1073 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001074};
1075
Ian Rogersaaa20802011-09-11 21:47:37 -07001076void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001077 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001078 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001079 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1080 // CHECK(native_to_managed_record_ != NULL);
1081 NativeToManagedRecord* record = native_to_managed_record_;
1082
Ian Rogersbdb03912011-09-14 00:55:44 -07001083 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001084 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001085 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1086 visitor->VisitFrame(frame, pc);
1087 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001088 }
1089 if (record == NULL) {
1090 break;
1091 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001092 // last_tos should return Frame instead of sp?
1093 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1094 pc = record->last_top_of_managed_stack_pc_;
1095 record = record->link_;
1096 }
1097}
1098
Ian Rogers67375ac2011-09-14 00:55:44 -07001099void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001100 Frame frame = GetTopOfStack();
1101 uintptr_t pc = top_of_managed_stack_pc_;
1102
1103 if (frame.GetSP() != 0) {
1104 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001105 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001106 visitor->VisitFrame(frame, pc);
1107 pc = frame.GetReturnPC();
1108 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001109 if (include_upcall) {
1110 visitor->VisitFrame(frame, pc);
1111 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001112 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001113}
1114
Ian Rogersaaa20802011-09-11 21:47:37 -07001115jobject Thread::CreateInternalStackTrace() const {
1116 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001117 CountStackDepthVisitor count_visitor;
1118 WalkStack(&count_visitor);
1119 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001120
Ian Rogersaaa20802011-09-11 21:47:37 -07001121 // Transition into runnable state to work on Object*/Array*
1122 ScopedJniThreadState ts(jni_env_);
1123
1124 // Build internal stack trace
1125 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001126 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001127
Ian Rogersaaa20802011-09-11 21:47:37 -07001128 return build_trace_visitor.GetInternalStackTrace();
1129}
1130
1131jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1132 JNIEnv* env) {
1133 // Transition into runnable state to work on Object*/Array*
1134 ScopedJniThreadState ts(env);
1135
1136 // Decode the internal stack trace into the depth, method trace and PC trace
1137 ObjectArray<Object>* method_trace =
1138 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1139 int32_t depth = method_trace->GetLength()-1;
1140 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1141
1142 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1143
1144 // Create java_trace array and place in local reference table
1145 ObjectArray<StackTraceElement>* java_traces =
1146 class_linker->AllocStackTraceElementArray(depth);
1147 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001148
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001149 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001150 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1151 Method* method = down_cast<Method*>(method_trace->Get(i));
1152 uint32_t native_pc = pc_trace->Get(i);
1153 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001154 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001155 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001156
Ian Rogersaaa20802011-09-11 21:47:37 -07001157 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001158 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001159 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001160 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001161 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001162 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001163 method->ToDexPC(native_pc)));
1164#ifdef MOVING_GARBAGE_COLLECTOR
1165 // Re-read after potential GC
1166 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1167 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1168 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1169#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001170 java_traces->Set(i, obj);
1171 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001172 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001173}
1174
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001175void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001176 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001177 va_list args;
1178 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001179 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001180 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001181
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001182 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001183 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001184 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001185 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001186 descriptor.erase(descriptor.length() - 1);
1187
1188 JNIEnv* env = GetJniEnv();
1189 jclass exception_class = env->FindClass(descriptor.c_str());
1190 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1191 int rc = env->ThrowNew(exception_class, msg.c_str());
1192 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001193}
1194
Elliott Hughes79082e32011-08-25 12:07:32 -07001195void Thread::ThrowOutOfMemoryError() {
1196 UNIMPLEMENTED(FATAL);
1197}
1198
Ian Rogersbdb03912011-09-14 00:55:44 -07001199Method* Thread::CalleeSaveMethod() const {
1200 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001201 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001202#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001203 method->SetCode(NULL, art::kThumb2, NULL);
1204 method->SetFrameSizeInBytes(64);
1205 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001206 method->SetCoreSpillMask((1 << art::arm::R1) |
1207 (1 << art::arm::R2) |
1208 (1 << art::arm::R3) |
1209 (1 << art::arm::R4) |
1210 (1 << art::arm::R5) |
1211 (1 << art::arm::R6) |
1212 (1 << art::arm::R7) |
1213 (1 << art::arm::R8) |
1214 (1 << art::arm::R9) |
1215 (1 << art::arm::R10) |
1216 (1 << art::arm::R11) |
1217 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001218 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001219#elif defined(__i386__)
1220 method->SetCode(NULL, art::kX86, NULL);
1221 method->SetFrameSizeInBytes(32);
1222 method->SetReturnPcOffsetInBytes(28);
1223 method->SetCoreSpillMask((1 << art::x86::EBX) |
1224 (1 << art::x86::EBP) |
1225 (1 << art::x86::ESI) |
1226 (1 << art::x86::EDI));
1227 method->SetFpSpillMask(0);
1228#else
1229 UNIMPLEMENTED(FATAL);
1230#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001231 return method;
1232}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001233
Ian Rogersbdb03912011-09-14 00:55:44 -07001234class CatchBlockStackVisitor : public Thread::StackVisitor {
1235 public:
1236 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001237 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1238#ifndef NDEBUG
1239 handler_pc_ = 0xEBADC0DE;
1240 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1241#endif
1242 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001243
Ian Rogersbdb03912011-09-14 00:55:44 -07001244 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1245 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001246 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001247 if (method == NULL) {
1248 // This is the upcall, we remember the frame and last_pc so that we may
1249 // long jump to them
1250 handler_pc_ = pc;
1251 handler_frame_ = fr;
1252 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001253 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001254 uint32_t dex_pc = DexFile::kDexNoIndex;
1255 if (pc > 0) {
1256 if (method->IsNative()) {
1257 native_method_count_++;
1258 } else {
1259 // Move the PC back 2 bytes as a call will frequently terminate the
1260 // decoding of a particular instruction and we want to make sure we
1261 // get the Dex PC of the instruction with the call and not the
1262 // instruction following.
1263 pc -= 2;
1264 dex_pc = method->ToDexPC(pc);
1265 }
1266 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001267 if (dex_pc != DexFile::kDexNoIndex) {
1268 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1269 if (found_dex_pc != DexFile::kDexNoIndex) {
1270 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001271 handler_pc_ = method->ToNativePC(found_dex_pc);
1272 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001273 }
1274 }
1275 if (!found_) {
1276 // Caller may be handler, fill in callee saves in context
1277 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001278 }
1279 }
1280 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001281
1282 // Did we find a catch block yet?
1283 bool found_;
1284 // The type of the exception catch block to find
1285 Class* to_find_;
1286 // Frame with found handler or last frame if no handler found
1287 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001288 // PC to branch to for the handler
1289 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001290 // Context that will be the target of the long jump
1291 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001292 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1293 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001294};
1295
1296void Thread::DeliverException(Throwable* exception) {
1297 SetException(exception); // Set exception on thread
1298
1299 Context* long_jump_context = GetLongJumpContext();
1300 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001301 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001302
Ian Rogers67375ac2011-09-14 00:55:44 -07001303 // Pop any SIRT
1304 if (catch_finder.native_method_count_ == 1) {
1305 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001306 } else {
Ian Rogers67375ac2011-09-14 00:55:44 -07001307 // We only expect the stack crawl to have passed 1 native method as its terminated
1308 // by a up call
1309 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001310 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001311 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1312 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001313 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001314}
1315
Ian Rogersbdb03912011-09-14 00:55:44 -07001316Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001317 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001318 if (result == NULL) {
1319 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001320 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001321 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001322 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001323}
1324
Elliott Hughes5f791332011-09-15 17:45:30 -07001325bool Thread::HoldsLock(Object* object) {
1326 if (object == NULL) {
1327 return false;
1328 }
1329 return object->GetLockOwner() == thin_lock_id_;
1330}
1331
Elliott Hughes410c0c82011-09-01 17:58:25 -07001332void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001333 if (exception_ != NULL) {
1334 visitor(exception_, arg);
1335 }
1336 if (peer_ != NULL) {
1337 visitor(peer_, arg);
1338 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001339 jni_env_->locals.VisitRoots(visitor, arg);
1340 jni_env_->monitors.VisitRoots(visitor, arg);
1341 // visitThreadStack(visitor, thread, arg);
1342 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1343}
1344
Ian Rogersb033c752011-07-20 12:22:35 -07001345static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001346 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001347 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001348 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001349 "Blocked",
1350 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001351 "Initializing",
1352 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001353 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001354 "VmWait",
1355 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001356};
1357std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001358 int int_state = static_cast<int>(state);
1359 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1360 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001361 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001362 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001363 }
1364 return os;
1365}
1366
Elliott Hughes330304d2011-08-12 14:28:05 -07001367std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1368 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001369 << ",pthread_t=" << thread.GetImpl()
1370 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001371 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001372 << ",state=" << thread.GetState()
1373 << ",peer=" << thread.GetPeer()
1374 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001375 return os;
1376}
1377
Elliott Hughes8daa0922011-09-11 13:46:25 -07001378} // namespace art