blob: e44590a8a838606f76785757eaae647b53c06ce3 [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) {
buzbee2a475e72011-09-07 17:19:17 -0700112 if (a->IsAssignableFrom(b)) {
113 return;
114 }
115 UNIMPLEMENTED(FATAL);
116}
117
Elliott Hughesd369bb72011-09-12 14:41:14 -0700118void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700119 // TODO: throw and unwind if lock not held
120 // TODO: throw and unwind on NPE
121 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700122}
123
Elliott Hughesd369bb72011-09-12 14:41:14 -0700124void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700125 obj->MonitorEnter(thread);
126 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700127}
128
Elliott Hughesd369bb72011-09-12 14:41:14 -0700129void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700130 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700131}
132
buzbeecefd1872011-09-09 09:59:52 -0700133// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700134void StackOverflowFromCode(Method* method) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700135 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700136 //NOTE: to save code space, this handler needs to look up its own Thread*
137 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700138}
139
buzbee5ade1d22011-09-09 14:44:52 -0700140// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700141void ThrowNullPointerFromCode() {
142 Thread::Current()->Dump(std::cerr);
143 //NOTE: to save code space, this handler must look up caller's Method*
144 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700145}
146
147// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700148void ThrowDivZeroFromCode() {
149 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700150}
151
152// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700153void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
154 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700155}
156
157// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700158void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700159 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
160 " ref: " << ref;
161}
162
163// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700164void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700165 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
166}
167
168// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700169void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700170 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
171}
172
173// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700174void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700175 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
176}
177
178// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700179void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700180 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
181}
182
Ian Rogersbdb03912011-09-14 00:55:44 -0700183void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
184 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
185 "abstract method \"%s\"",
186 PrettyMethod(method).c_str());
187 thread->DeliverException(thread->GetException());
188}
189
190
buzbee5ade1d22011-09-09 14:44:52 -0700191/*
192 * Temporary placeholder. Should include run-time checks for size
193 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
194 * As with other new "FromCode" routines, this should return to the caller
195 * only if no exception has been thrown.
196 *
197 * NOTE: When dealing with a raw dex file, the data to be copied uses
198 * little-endian ordering. Require that oat2dex do any required swapping
199 * so this routine can get by with a memcpy().
200 *
201 * Format of the data:
202 * ushort ident = 0x0300 magic value
203 * ushort width width of each element in the table
204 * uint size number of elements in the table
205 * ubyte data[size*width] table of data values (may contain a single-byte
206 * padding at the end)
207 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700208void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700209 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
210 uint32_t size_in_bytes = size * table[1];
211 if (static_cast<int32_t>(size) > array->GetLength()) {
212 ThrowArrayBoundsFromCode(array->GetLength(), size);
213 }
214 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
215 (char*)&table[4], size_in_bytes);
216}
217
Brian Carlstrom16192862011-09-12 17:50:06 -0700218/*
219 * TODO: placeholder for a method that can be called by the
220 * invoke-interface trampoline to unwind and handle exception. The
221 * trampoline will arrange it so that the caller appears to be the
222 * callsite of the failed invoke-interface. See comments in
223 * runtime_support.S
224 */
225extern "C" void artFailedInvokeInterface() {
226 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
227}
228
229// See comments in runtime_support.S
230extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
231 Object* this_object , Method* caller_method)
232{
233 if (this_object == NULL) {
234 ThrowNullPointerFromCode();
235 }
236 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
237 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
238 if (interface_method == NULL) {
239 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
240 }
241 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
242 const void* code = method->GetCode();
243
244 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
245 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
246 uint64_t result = ((code_uint << 32) | method_uint);
247 return result;
248}
249
buzbee5ade1d22011-09-09 14:44:52 -0700250// TODO: move to more appropriate location
251/*
252 * Float/double conversion requires clamping to min and max of integer form. If
253 * target doesn't support this normally, use these.
254 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700255int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700256 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
257 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
258 if (d >= kMaxLong)
259 return (int64_t)0x7fffffffffffffffULL;
260 else if (d <= kMinLong)
261 return (int64_t)0x8000000000000000ULL;
262 else if (d != d) // NaN case
263 return 0;
264 else
265 return (int64_t)d;
266}
267
Elliott Hughesd369bb72011-09-12 14:41:14 -0700268int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700269 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
270 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
271 if (f >= kMaxLong)
272 return (int64_t)0x7fffffffffffffffULL;
273 else if (f <= kMinLong)
274 return (int64_t)0x8000000000000000ULL;
275 else if (f != f) // NaN case
276 return 0;
277 else
278 return (int64_t)f;
279}
280
Brian Carlstrom16192862011-09-12 17:50:06 -0700281// Return value helper for jobject return types
282static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
283 return thread->DecodeJObject(obj);
284}
285
buzbee3ea4ec52011-08-22 17:37:19 -0700286void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700287#if defined(__arm__)
288 pShlLong = art_shl_long;
289 pShrLong = art_shr_long;
290 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700291 pIdiv = __aeabi_idiv;
292 pIdivmod = __aeabi_idivmod;
293 pI2f = __aeabi_i2f;
294 pF2iz = __aeabi_f2iz;
295 pD2f = __aeabi_d2f;
296 pF2d = __aeabi_f2d;
297 pD2iz = __aeabi_d2iz;
298 pL2f = __aeabi_l2f;
299 pL2d = __aeabi_l2d;
300 pFadd = __aeabi_fadd;
301 pFsub = __aeabi_fsub;
302 pFdiv = __aeabi_fdiv;
303 pFmul = __aeabi_fmul;
304 pFmodf = fmodf;
305 pDadd = __aeabi_dadd;
306 pDsub = __aeabi_dsub;
307 pDdiv = __aeabi_ddiv;
308 pDmul = __aeabi_dmul;
309 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700310 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700311 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700312 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700313 pDeliverException = art_deliver_exception;
314#endif
315#if defined(__i386__)
316 pDeliverException = art_deliver_exception;
buzbee54330722011-08-23 16:46:55 -0700317#endif
buzbeec396efc2011-09-11 09:36:41 -0700318 pF2l = F2L;
319 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700320 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700321 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700322 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700323 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700324 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700325 pGet32Static = Field::Get32StaticFromCode;
326 pSet32Static = Field::Set32StaticFromCode;
327 pGet64Static = Field::Get64StaticFromCode;
328 pSet64Static = Field::Set64StaticFromCode;
329 pGetObjStatic = Field::GetObjStaticFromCode;
330 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700331 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700332 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700333 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700334 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700335 pInstanceofNonTrivialFromCode = Object::InstanceOf;
336 pCheckCastFromCode = CheckCastFromCode;
337 pLockObjectFromCode = LockObjectFromCode;
338 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700339 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700340 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700341 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700342 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
343 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
344 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
345 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
346 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
347 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
348 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
349 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700350 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700351 pFindNativeMethod = FindNativeMethod;
352 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700353 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700354}
355
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700356void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700357 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
358 DCHECK_NE(frame_size, 0u);
359 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700360 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700361 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700363 DCHECK(*sp_ == NULL ||
364 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700365}
366
Ian Rogersbdb03912011-09-14 00:55:44 -0700367uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700368 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700369 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700370 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700371}
372
Ian Rogersbdb03912011-09-14 00:55:44 -0700373uintptr_t Frame::LoadCalleeSave(int num) const {
374 // Callee saves are held at the top of the frame
375 Method* method = GetMethod();
376 DCHECK(method != NULL);
377 size_t frame_size = method->GetFrameSizeInBytes();
378 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
379 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700380#if defined(__i386__)
381 save_addr -= kPointerSize; // account for return address
382#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700383 return *reinterpret_cast<uintptr_t*>(save_addr);
384}
385
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700387 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700388 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700390}
391
Brian Carlstrom78128a62011-09-15 17:21:19 -0700392void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700393 Thread* self = reinterpret_cast<Thread*>(arg);
394 Runtime* runtime = Runtime::Current();
395
396 self->Attach(runtime);
397
398 ClassLinker* class_linker = runtime->GetClassLinker();
399
400 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
401 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
402
403 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
404 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
405 if (thread_name != NULL) {
406 SetThreadName(thread_name->ToModifiedUtf8().c_str());
407 }
408
409 // Wait until it's safe to start running code. (There may have been a suspend-all
410 // in progress while we were starting up.)
411 runtime->GetThreadList()->WaitForGo();
412
413 // TODO: say "hi" to the debugger.
414 //if (gDvm.debuggerConnected) {
415 // dvmDbgPostThreadStart(self);
416 //}
417
418 // Invoke the 'run' method of our java.lang.Thread.
419 CHECK(self->peer_ != NULL);
420 Object* receiver = self->peer_;
421 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
422 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
423 m->Invoke(self, receiver, NULL, NULL);
424
425 // Detach.
426 runtime->GetThreadList()->Unregister();
427
Carl Shapirob5573532011-07-12 18:22:59 -0700428 return NULL;
429}
430
Elliott Hughes93e74e82011-09-13 11:07:03 -0700431void SetVmData(Object* managed_thread, Thread* native_thread) {
432 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
433
434 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
435 Class* int_class = class_linker->FindPrimitiveClass('I');
436
437 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
438
439 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
440}
441
Elliott Hughesd369bb72011-09-12 14:41:14 -0700442void Thread::Create(Object* peer, size_t stack_size) {
443 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700444
Elliott Hughesd369bb72011-09-12 14:41:14 -0700445 if (stack_size == 0) {
446 stack_size = Runtime::Current()->GetDefaultStackSize();
447 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700448
Elliott Hughes93e74e82011-09-13 11:07:03 -0700449 Thread* native_thread = new Thread;
450 native_thread->peer_ = peer;
451
452 // Thread.start is synchronized, so we know that vmData is 0,
453 // and know that we're not racing to assign it.
454 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700455
456 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700457 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
458 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
459 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
460 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
461 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700462
463 // Let the child know when it's safe to start running.
464 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700465}
466
Elliott Hughes93e74e82011-09-13 11:07:03 -0700467void Thread::Attach(const Runtime* runtime) {
468 InitCpu();
469 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700470
Elliott Hughes93e74e82011-09-13 11:07:03 -0700471 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700472
Elliott Hughes93e74e82011-09-13 11:07:03 -0700473 tid_ = ::art::GetTid();
474 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700475
Elliott Hughes93e74e82011-09-13 11:07:03 -0700476 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700477
Elliott Hughes8d768a92011-09-14 16:35:25 -0700478 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700479
Elliott Hughes93e74e82011-09-13 11:07:03 -0700480 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700481
Elliott Hughes93e74e82011-09-13 11:07:03 -0700482 runtime->GetThreadList()->Register(this);
483}
484
485Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
486 Thread* self = new Thread;
487 self->Attach(runtime);
488
489 self->SetState(Thread::kRunnable);
490
491 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700492
493 // If we're the main thread, ClassLinker won't be created until after we're attached,
494 // so that thread needs a two-stage attach. Regular threads don't need this hack.
495 if (self->thin_lock_id_ != ThreadList::kMainId) {
496 self->CreatePeer(name, as_daemon);
497 }
498
499 return self;
500}
501
Elliott Hughesd369bb72011-09-12 14:41:14 -0700502jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
503 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
504 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
505 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
506 // This will be null in the compiler (and tests), but never in a running system.
507 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
508 return thread_group;
509}
510
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700511void Thread::CreatePeer(const char* name, bool as_daemon) {
512 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
513
514 JNIEnv* env = jni_env_;
515
Elliott Hughesd369bb72011-09-12 14:41:14 -0700516 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
517 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700518 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700519 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700520 jboolean thread_is_daemon = as_daemon;
521
522 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700523 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700524
Elliott Hughes8daa0922011-09-11 13:46:25 -0700525 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700526
527 // Because we mostly run without code available (in the compiler, in tests), we
528 // manually assign the fields the constructor should have set.
529 // TODO: lose this.
530 jfieldID fid;
531 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
532 env->SetObjectField(peer, fid, thread_group);
533 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
534 env->SetObjectField(peer, fid, thread_name);
535 fid = env->GetFieldID(c, "priority", "I");
536 env->SetIntField(peer, fid, thread_priority);
537 fid = env->GetFieldID(c, "daemon", "Z");
538 env->SetBooleanField(peer, fid, thread_is_daemon);
539
540 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700541}
542
Elliott Hughesbe759c62011-09-08 19:38:21 -0700543void Thread::InitStackHwm() {
544 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700545 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700546
Elliott Hughesbe759c62011-09-08 19:38:21 -0700547 void* stack_base;
548 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700549 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700550
Elliott Hughesbe759c62011-09-08 19:38:21 -0700551 if (stack_size <= kStackOverflowReservedBytes) {
552 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
553 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700554
555 // stack_base is the "lowest addressable byte" of the stack.
556 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
557 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700558 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700559
560 // Sanity check.
561 int stack_variable;
562 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700563
Elliott Hughes8d768a92011-09-14 16:35:25 -0700564 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700565}
566
Elliott Hughesa0957642011-09-02 14:27:33 -0700567void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700568 DumpState(os);
569 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700570}
571
Elliott Hughesd92bec42011-09-02 17:04:36 -0700572std::string GetSchedulerGroup(pid_t tid) {
573 // /proc/<pid>/group looks like this:
574 // 2:devices:/
575 // 1:cpuacct,cpu:/
576 // We want the third field from the line whose second field contains the "cpu" token.
577 std::string cgroup_file;
578 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
579 return "";
580 }
581 std::vector<std::string> cgroup_lines;
582 Split(cgroup_file, '\n', cgroup_lines);
583 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
584 std::vector<std::string> cgroup_fields;
585 Split(cgroup_lines[i], ':', cgroup_fields);
586 std::vector<std::string> cgroups;
587 Split(cgroup_fields[1], ',', cgroups);
588 for (size_t i = 0; i < cgroups.size(); ++i) {
589 if (cgroups[i] == "cpu") {
590 return cgroup_fields[2].substr(1); // Skip the leading slash.
591 }
592 }
593 }
594 return "";
595}
596
597void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700598 std::string thread_name("<native thread without managed peer>");
599 std::string group_name;
600 int priority;
601 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700602
Elliott Hughesd369bb72011-09-12 14:41:14 -0700603 if (peer_ != NULL) {
604 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
605
606 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
607 Class* int_class = class_linker->FindPrimitiveClass('I');
608 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
609 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
610 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
611
612 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
613 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
614 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
615 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
616
617 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
618 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
619 priority = priority_field->GetInt(peer_);
620 is_daemon = daemon_field->GetBoolean(peer_);
621
622 Object* thread_group = thread_group_field->GetObject(peer_);
623 if (thread_group != NULL) {
624 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
625 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
626 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
627 }
628 } else {
629 // 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 -0700630 std::string stats;
631 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
632 size_t start = stats.find('(') + 1;
633 size_t end = stats.find(')') - start;
634 thread_name = stats.substr(start, end);
635 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700636 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700637 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700638
639 int policy;
640 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700641 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700642
643 std::string scheduler_group(GetSchedulerGroup(GetTid()));
644 if (scheduler_group.empty()) {
645 scheduler_group = "default";
646 }
647
Elliott Hughesd92bec42011-09-02 17:04:36 -0700648 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700649 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700650 os << " daemon";
651 }
652 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700653 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700654 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700655
Elliott Hughesd92bec42011-09-02 17:04:36 -0700656 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700657 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700658 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700659 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700660 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700661 << " self=" << reinterpret_cast<const void*>(this) << "\n";
662 os << " | sysTid=" << GetTid()
663 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
664 << " sched=" << policy << "/" << sp.sched_priority
665 << " cgrp=" << scheduler_group
666 << " handle=" << GetImpl() << "\n";
667
668 // Grab the scheduler stats for this thread.
669 std::string scheduler_stats;
670 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
671 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
672 } else {
673 scheduler_stats = "0 0 0";
674 }
675
676 int utime = 0;
677 int stime = 0;
678 int task_cpu = 0;
679 std::string stats;
680 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
681 // Skip the command, which may contain spaces.
682 stats = stats.substr(stats.find(')') + 2);
683 // Extract the three fields we care about.
684 std::vector<std::string> fields;
685 Split(stats, ' ', fields);
686 utime = strtoull(fields[11].c_str(), NULL, 10);
687 stime = strtoull(fields[12].c_str(), NULL, 10);
688 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
689 }
690
691 os << " | schedstat=( " << scheduler_stats << " )"
692 << " utm=" << utime
693 << " stm=" << stime
694 << " core=" << task_cpu
695 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
696}
697
Elliott Hughesd369bb72011-09-12 14:41:14 -0700698struct StackDumpVisitor : public Thread::StackVisitor {
699 StackDumpVisitor(std::ostream& os) : os(os) {
700 }
701
Ian Rogersbdb03912011-09-14 00:55:44 -0700702 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700703 }
704
Ian Rogersbdb03912011-09-14 00:55:44 -0700705 void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700706 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
707
708 Method* m = frame.GetMethod();
709 Class* c = m->GetDeclaringClass();
710 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
711
712 os << " at " << PrettyMethod(m, false);
713 if (m->IsNative()) {
714 os << "(Native method)";
715 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700716 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700717 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
718 }
719 os << "\n";
720 }
721
722 std::ostream& os;
723};
724
Elliott Hughesd92bec42011-09-02 17:04:36 -0700725void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700726 StackDumpVisitor dumper(os);
727 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700728}
729
Elliott Hughes8d768a92011-09-14 16:35:25 -0700730Thread::State Thread::SetState(Thread::State new_state) {
731 Thread::State old_state = state_;
732 if (old_state == new_state) {
733 return old_state;
734 }
735
736 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
737 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
738
739 if (new_state == Thread::kRunnable) {
740 /*
741 * Change our status to Thread::kRunnable. The transition requires
742 * that we check for pending suspension, because the VM considers
743 * us to be "asleep" in all other states, and another thread could
744 * be performing a GC now.
745 *
746 * The order of operations is very significant here. One way to
747 * do this wrong is:
748 *
749 * GCing thread Our thread (in kNative)
750 * ------------ ----------------------
751 * check suspend count (== 0)
752 * SuspendAllThreads()
753 * grab suspend-count lock
754 * increment all suspend counts
755 * release suspend-count lock
756 * check thread state (== kNative)
757 * all are suspended, begin GC
758 * set state to kRunnable
759 * (continue executing)
760 *
761 * We can correct this by grabbing the suspend-count lock and
762 * performing both of our operations (check suspend count, set
763 * state) while holding it, now we need to grab a mutex on every
764 * transition to kRunnable.
765 *
766 * What we do instead is change the order of operations so that
767 * the transition to kRunnable happens first. If we then detect
768 * that the suspend count is nonzero, we switch to kSuspended.
769 *
770 * Appropriate compiler and memory barriers are required to ensure
771 * that the operations are observed in the expected order.
772 *
773 * This does create a small window of opportunity where a GC in
774 * progress could observe what appears to be a running thread (if
775 * it happens to look between when we set to kRunnable and when we
776 * switch to kSuspended). At worst this only affects assertions
777 * and thread logging. (We could work around it with some sort
778 * of intermediate "pre-running" state that is generally treated
779 * as equivalent to running, but that doesn't seem worthwhile.)
780 *
781 * We can also solve this by combining the "status" and "suspend
782 * count" fields into a single 32-bit value. This trades the
783 * store/load barrier on transition to kRunnable for an atomic RMW
784 * op on all transitions and all suspend count updates (also, all
785 * accesses to status or the thread count require bit-fiddling).
786 * It also eliminates the brief transition through kRunnable when
787 * the thread is supposed to be suspended. This is possibly faster
788 * on SMP and slightly more correct, but less convenient.
789 */
790 android_atomic_acquire_store(new_state, addr);
791 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
792 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
793 }
794 } else {
795 /*
796 * Not changing to Thread::kRunnable. No additional work required.
797 *
798 * We use a releasing store to ensure that, if we were runnable,
799 * any updates we previously made to objects on the managed heap
800 * will be observed before the state change.
801 */
802 android_atomic_release_store(new_state, addr);
803 }
804
805 return old_state;
806}
807
808void Thread::WaitUntilSuspended() {
809 // TODO: dalvik dropped the waiting thread's priority after a while.
810 // TODO: dalvik timed out and aborted.
811 useconds_t delay = 0;
812 while (GetState() == Thread::kRunnable) {
813 useconds_t new_delay = delay * 2;
814 CHECK_GE(new_delay, delay);
815 delay = new_delay;
816 if (delay == 0) {
817 sched_yield();
818 delay = 10000;
819 } else {
820 usleep(delay);
821 }
822 }
823}
824
Elliott Hughesbe759c62011-09-08 19:38:21 -0700825void Thread::ThreadExitCallback(void* arg) {
826 Thread* self = reinterpret_cast<Thread*>(arg);
827 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700828}
829
Elliott Hughesbe759c62011-09-08 19:38:21 -0700830void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700831 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700832 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700833
834 // Double-check the TLS slot allocation.
835 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700836 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700837 }
838
839 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700840}
841
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700842void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700843 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700844}
845
Elliott Hughesdcc24742011-09-07 14:02:44 -0700846Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700847 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700848 wait_mutex_(new Mutex("Thread wait mutex")),
849 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700850 wait_monitor_(NULL),
851 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700852 wait_next_(NULL),
853 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700854 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700855 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700856 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700857 native_to_managed_record_(NULL),
858 top_sirt_(NULL),
859 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700860 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700861 self_(NULL),
862 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700863 exception_(NULL),
864 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700865 class_loader_override_(NULL),
866 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700867}
868
Elliott Hughes02b48d12011-09-07 17:15:51 -0700869void MonitorExitVisitor(const Object* object, void*) {
870 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700871 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700872}
873
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700874Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700875 // TODO: check we're not calling the JNI DetachCurrentThread function from
876 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
877
878 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700879 if (jni_env_ != NULL) {
880 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
881 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700882
883 if (IsExceptionPending()) {
884 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
885 }
886
887 // TODO: ThreadGroup.removeThread(this);
888
Elliott Hughes93e74e82011-09-13 11:07:03 -0700889 if (peer_ != NULL) {
890 SetVmData(peer_, NULL);
891 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700892
893 // TODO: say "bye" to the debugger.
894 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700895 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700896 //}
897
898 // Thread.join() is implemented as an Object.wait() on the Thread.lock
899 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700900 if (peer_ != NULL) {
901 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
902 Class* java_lang_Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
903 Class* java_lang_ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
904 Field* lock_field = java_lang_Thread_class->FindDeclaredInstanceField("lock", java_lang_ThreadLock_class);
905
906 Thread* self = Thread::Current();
907 Object* lock = lock_field->GetObject(peer_);
908 // This conditional is only needed for tests, where Thread.lock won't have been set.
909 if (lock != NULL) {
910 lock->MonitorEnter(self);
911 lock->NotifyAll();
912 lock->MonitorExit(self);
913 }
914 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700915
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700916 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700917 jni_env_ = NULL;
918
919 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700920
921 delete wait_cond_;
922 delete wait_mutex_;
923
924 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700925}
926
Ian Rogers408f79a2011-08-23 18:22:33 -0700927size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700928 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700929 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700930 count += cur->NumberOfReferences();
931 }
932 return count;
933}
934
Ian Rogers408f79a2011-08-23 18:22:33 -0700935bool Thread::SirtContains(jobject obj) {
936 Object** sirt_entry = reinterpret_cast<Object**>(obj);
937 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700938 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700939 // A SIRT should always have a jobject/jclass as a native method is passed
940 // in a this pointer or a class
941 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700942 if ((&cur->References()[0] <= sirt_entry) &&
943 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700944 return true;
945 }
946 }
947 return false;
948}
949
Ian Rogers67375ac2011-09-14 00:55:44 -0700950void Thread::PopSirt() {
951 CHECK(top_sirt_ != NULL);
952 top_sirt_ = top_sirt_->Link();
953}
954
Ian Rogers408f79a2011-08-23 18:22:33 -0700955Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700956 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700957 if (obj == NULL) {
958 return NULL;
959 }
960 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
961 IndirectRefKind kind = GetIndirectRefKind(ref);
962 Object* result;
963 switch (kind) {
964 case kLocal:
965 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700966 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700967 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700968 break;
969 }
970 case kGlobal:
971 {
972 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
973 IndirectReferenceTable& globals = vm->globals;
974 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700975 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700976 break;
977 }
978 case kWeakGlobal:
979 {
980 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
981 IndirectReferenceTable& weak_globals = vm->weak_globals;
982 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700983 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700984 if (result == kClearedJniWeakGlobal) {
985 // This is a special case where it's okay to return NULL.
986 return NULL;
987 }
988 break;
989 }
990 case kSirtOrInvalid:
991 default:
992 // TODO: make stack indirect reference table lookup more efficient
993 // Check if this is a local reference in the SIRT
994 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700995 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700996 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700997 // Assume an invalid local reference is actually a direct pointer.
998 result = reinterpret_cast<Object*>(obj);
999 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001000 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001001 }
1002 }
1003
1004 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001005 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1006 JniAbort(NULL);
1007 } else {
1008 if (result != kInvalidIndirectRefObject) {
1009 Heap::VerifyObject(result);
1010 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001011 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001012 return result;
1013}
1014
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001015class CountStackDepthVisitor : public Thread::StackVisitor {
1016 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001017 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001018
Ian Rogersbdb03912011-09-14 00:55:44 -07001019 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001020 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001021 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001022
1023 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001024 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001025 }
1026
1027 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001028 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001029};
1030
Ian Rogersaaa20802011-09-11 21:47:37 -07001031//
1032class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001033 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001034 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1035 // Allocate method trace with an extra slot that will hold the PC trace
1036 method_trace_ = Runtime::Current()->GetClassLinker()->
1037 AllocObjectArray<Object>(depth + 1);
1038 // Register a local reference as IntArray::Alloc may trigger GC
1039 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1040 pc_trace_ = IntArray::Alloc(depth);
1041#ifdef MOVING_GARBAGE_COLLECTOR
1042 // Re-read after potential GC
1043 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1044#endif
1045 // Save PC trace in last element of method trace, also places it into the
1046 // object graph.
1047 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001048 }
1049
Ian Rogersaaa20802011-09-11 21:47:37 -07001050 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001051
Ian Rogersbdb03912011-09-14 00:55:44 -07001052 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001053 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001054 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001055 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001056 }
1057
Ian Rogersaaa20802011-09-11 21:47:37 -07001058 jobject GetInternalStackTrace() const {
1059 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001060 }
1061
1062 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001063 // Current position down stack trace
1064 uint32_t count_;
1065 // Array of return PC values
1066 IntArray* pc_trace_;
1067 // An array of the methods on the stack, the last entry is a reference to the
1068 // PC trace
1069 ObjectArray<Object>* method_trace_;
1070 // Local indirect reference table entry for method trace
1071 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001072};
1073
Ian Rogersaaa20802011-09-11 21:47:37 -07001074void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001075 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001076 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001077 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1078 // CHECK(native_to_managed_record_ != NULL);
1079 NativeToManagedRecord* record = native_to_managed_record_;
1080
Ian Rogersbdb03912011-09-14 00:55:44 -07001081 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001082 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001083 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1084 visitor->VisitFrame(frame, pc);
1085 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001086 }
1087 if (record == NULL) {
1088 break;
1089 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001090 // last_tos should return Frame instead of sp?
1091 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1092 pc = record->last_top_of_managed_stack_pc_;
1093 record = record->link_;
1094 }
1095}
1096
Ian Rogers67375ac2011-09-14 00:55:44 -07001097void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001098 Frame frame = GetTopOfStack();
1099 uintptr_t pc = top_of_managed_stack_pc_;
1100
1101 if (frame.GetSP() != 0) {
1102 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001103 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001104 visitor->VisitFrame(frame, pc);
1105 pc = frame.GetReturnPC();
1106 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001107 if (include_upcall) {
1108 visitor->VisitFrame(frame, pc);
1109 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001110 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001111}
1112
Ian Rogersaaa20802011-09-11 21:47:37 -07001113jobject Thread::CreateInternalStackTrace() const {
1114 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001115 CountStackDepthVisitor count_visitor;
1116 WalkStack(&count_visitor);
1117 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001118
Ian Rogersaaa20802011-09-11 21:47:37 -07001119 // Transition into runnable state to work on Object*/Array*
1120 ScopedJniThreadState ts(jni_env_);
1121
1122 // Build internal stack trace
1123 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001124 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001125
Ian Rogersaaa20802011-09-11 21:47:37 -07001126 return build_trace_visitor.GetInternalStackTrace();
1127}
1128
1129jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1130 JNIEnv* env) {
1131 // Transition into runnable state to work on Object*/Array*
1132 ScopedJniThreadState ts(env);
1133
1134 // Decode the internal stack trace into the depth, method trace and PC trace
1135 ObjectArray<Object>* method_trace =
1136 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1137 int32_t depth = method_trace->GetLength()-1;
1138 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1139
1140 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1141
1142 // Create java_trace array and place in local reference table
1143 ObjectArray<StackTraceElement>* java_traces =
1144 class_linker->AllocStackTraceElementArray(depth);
1145 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001146
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001147 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001148 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1149 Method* method = down_cast<Method*>(method_trace->Get(i));
1150 uint32_t native_pc = pc_trace->Get(i);
1151 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001152 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001153 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001154
Ian Rogersaaa20802011-09-11 21:47:37 -07001155 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001156 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001157 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001158 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001159 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001160 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001161 method->ToDexPC(native_pc)));
1162#ifdef MOVING_GARBAGE_COLLECTOR
1163 // Re-read after potential GC
1164 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1165 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1166 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1167#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001168 java_traces->Set(i, obj);
1169 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001170 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001171}
1172
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001173void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001174 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001175 va_list args;
1176 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001177 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001178 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001179
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001180 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001181 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001182 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001183 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001184 descriptor.erase(descriptor.length() - 1);
1185
1186 JNIEnv* env = GetJniEnv();
1187 jclass exception_class = env->FindClass(descriptor.c_str());
1188 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1189 int rc = env->ThrowNew(exception_class, msg.c_str());
1190 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001191}
1192
Elliott Hughes79082e32011-08-25 12:07:32 -07001193void Thread::ThrowOutOfMemoryError() {
1194 UNIMPLEMENTED(FATAL);
1195}
1196
Ian Rogersbdb03912011-09-14 00:55:44 -07001197Method* Thread::CalleeSaveMethod() const {
1198 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001199 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001200#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001201 method->SetCode(NULL, art::kThumb2, NULL);
1202 method->SetFrameSizeInBytes(64);
1203 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001204 method->SetCoreSpillMask((1 << art::arm::R1) |
1205 (1 << art::arm::R2) |
1206 (1 << art::arm::R3) |
1207 (1 << art::arm::R4) |
1208 (1 << art::arm::R5) |
1209 (1 << art::arm::R6) |
1210 (1 << art::arm::R7) |
1211 (1 << art::arm::R8) |
1212 (1 << art::arm::R9) |
1213 (1 << art::arm::R10) |
1214 (1 << art::arm::R11) |
1215 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001216 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001217#elif defined(__i386__)
1218 method->SetCode(NULL, art::kX86, NULL);
1219 method->SetFrameSizeInBytes(32);
1220 method->SetReturnPcOffsetInBytes(28);
1221 method->SetCoreSpillMask((1 << art::x86::EBX) |
1222 (1 << art::x86::EBP) |
1223 (1 << art::x86::ESI) |
1224 (1 << art::x86::EDI));
1225 method->SetFpSpillMask(0);
1226#else
1227 UNIMPLEMENTED(FATAL);
1228#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001229 return method;
1230}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001231
Ian Rogersbdb03912011-09-14 00:55:44 -07001232class CatchBlockStackVisitor : public Thread::StackVisitor {
1233 public:
1234 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001235 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1236#ifndef NDEBUG
1237 handler_pc_ = 0xEBADC0DE;
1238 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1239#endif
1240 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001241
Ian Rogersbdb03912011-09-14 00:55:44 -07001242 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1243 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001244 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001245 if (method == NULL) {
1246 // This is the upcall, we remember the frame and last_pc so that we may
1247 // long jump to them
1248 handler_pc_ = pc;
1249 handler_frame_ = fr;
1250 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001251 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001252 uint32_t dex_pc = DexFile::kDexNoIndex;
1253 if (pc > 0) {
1254 if (method->IsNative()) {
1255 native_method_count_++;
1256 } else {
1257 // Move the PC back 2 bytes as a call will frequently terminate the
1258 // decoding of a particular instruction and we want to make sure we
1259 // get the Dex PC of the instruction with the call and not the
1260 // instruction following.
1261 pc -= 2;
1262 dex_pc = method->ToDexPC(pc);
1263 }
1264 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001265 if (dex_pc != DexFile::kDexNoIndex) {
1266 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1267 if (found_dex_pc != DexFile::kDexNoIndex) {
1268 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001269 handler_pc_ = method->ToNativePC(found_dex_pc);
1270 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001271 }
1272 }
1273 if (!found_) {
1274 // Caller may be handler, fill in callee saves in context
1275 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001276 }
1277 }
1278 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001279
1280 // Did we find a catch block yet?
1281 bool found_;
1282 // The type of the exception catch block to find
1283 Class* to_find_;
1284 // Frame with found handler or last frame if no handler found
1285 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001286 // PC to branch to for the handler
1287 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001288 // Context that will be the target of the long jump
1289 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001290 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1291 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001292};
1293
1294void Thread::DeliverException(Throwable* exception) {
1295 SetException(exception); // Set exception on thread
1296
1297 Context* long_jump_context = GetLongJumpContext();
1298 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001299 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001300
Ian Rogers67375ac2011-09-14 00:55:44 -07001301 // Pop any SIRT
1302 if (catch_finder.native_method_count_ == 1) {
1303 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001304 } else {
Ian Rogers67375ac2011-09-14 00:55:44 -07001305 // We only expect the stack crawl to have passed 1 native method as its terminated
1306 // by a up call
1307 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001308 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001309 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1310 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001311 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001312}
1313
Ian Rogersbdb03912011-09-14 00:55:44 -07001314Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001315 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001316 if (result == NULL) {
1317 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001318 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001319 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001320 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001321}
1322
Elliott Hughes5f791332011-09-15 17:45:30 -07001323bool Thread::HoldsLock(Object* object) {
1324 if (object == NULL) {
1325 return false;
1326 }
1327 return object->GetLockOwner() == thin_lock_id_;
1328}
1329
Elliott Hughes410c0c82011-09-01 17:58:25 -07001330void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001331 if (exception_ != NULL) {
1332 visitor(exception_, arg);
1333 }
1334 if (peer_ != NULL) {
1335 visitor(peer_, arg);
1336 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001337 jni_env_->locals.VisitRoots(visitor, arg);
1338 jni_env_->monitors.VisitRoots(visitor, arg);
1339 // visitThreadStack(visitor, thread, arg);
1340 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1341}
1342
Ian Rogersb033c752011-07-20 12:22:35 -07001343static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001344 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001345 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001346 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001347 "Blocked",
1348 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001349 "Initializing",
1350 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001351 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001352 "VmWait",
1353 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001354};
1355std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001356 int int_state = static_cast<int>(state);
1357 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1358 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001359 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001360 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001361 }
1362 return os;
1363}
1364
Elliott Hughes330304d2011-08-12 14:28:05 -07001365std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1366 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001367 << ",pthread_t=" << thread.GetImpl()
1368 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001369 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001370 << ",state=" << thread.GetState()
1371 << ",peer=" << thread.GetPeer()
1372 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001373 return os;
1374}
1375
Elliott Hughes8daa0922011-09-11 13:46:25 -07001376} // namespace art