blob: 86994cf3bca8787b47526edeabc2cbcf3cfa42ce [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),
852 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700853 top_of_managed_stack_(),
854 native_to_managed_record_(NULL),
855 top_sirt_(NULL),
856 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700857 state_(Thread::kUnknown),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700858 exception_(NULL),
859 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700860 class_loader_override_(NULL),
861 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700862}
863
Elliott Hughes02b48d12011-09-07 17:15:51 -0700864void MonitorExitVisitor(const Object* object, void*) {
865 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700866 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700867}
868
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700869Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700870 // TODO: check we're not calling the JNI DetachCurrentThread function from
871 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
872
873 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700874 if (jni_env_ != NULL) {
875 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
876 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700877
878 if (IsExceptionPending()) {
879 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
880 }
881
882 // TODO: ThreadGroup.removeThread(this);
883
Elliott Hughes93e74e82011-09-13 11:07:03 -0700884 if (peer_ != NULL) {
885 SetVmData(peer_, NULL);
886 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700887
888 // TODO: say "bye" to the debugger.
889 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700890 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700891 //}
892
893 // Thread.join() is implemented as an Object.wait() on the Thread.lock
894 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700895 if (peer_ != NULL) {
896 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
897 Class* java_lang_Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
898 Class* java_lang_ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
899 Field* lock_field = java_lang_Thread_class->FindDeclaredInstanceField("lock", java_lang_ThreadLock_class);
900
901 Thread* self = Thread::Current();
902 Object* lock = lock_field->GetObject(peer_);
903 // This conditional is only needed for tests, where Thread.lock won't have been set.
904 if (lock != NULL) {
905 lock->MonitorEnter(self);
906 lock->NotifyAll();
907 lock->MonitorExit(self);
908 }
909 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700910
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700911 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700912 jni_env_ = NULL;
913
914 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700915
916 delete wait_cond_;
917 delete wait_mutex_;
918
919 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700920}
921
Ian Rogers408f79a2011-08-23 18:22:33 -0700922size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700923 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700924 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700925 count += cur->NumberOfReferences();
926 }
927 return count;
928}
929
Ian Rogers408f79a2011-08-23 18:22:33 -0700930bool Thread::SirtContains(jobject obj) {
931 Object** sirt_entry = reinterpret_cast<Object**>(obj);
932 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700933 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700934 // A SIRT should always have a jobject/jclass as a native method is passed
935 // in a this pointer or a class
936 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700937 if ((&cur->References()[0] <= sirt_entry) &&
938 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700939 return true;
940 }
941 }
942 return false;
943}
944
Ian Rogers67375ac2011-09-14 00:55:44 -0700945void Thread::PopSirt() {
946 CHECK(top_sirt_ != NULL);
947 top_sirt_ = top_sirt_->Link();
948}
949
Ian Rogers408f79a2011-08-23 18:22:33 -0700950Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700951 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700952 if (obj == NULL) {
953 return NULL;
954 }
955 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
956 IndirectRefKind kind = GetIndirectRefKind(ref);
957 Object* result;
958 switch (kind) {
959 case kLocal:
960 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700961 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700962 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700963 break;
964 }
965 case kGlobal:
966 {
967 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
968 IndirectReferenceTable& globals = vm->globals;
969 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700970 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700971 break;
972 }
973 case kWeakGlobal:
974 {
975 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
976 IndirectReferenceTable& weak_globals = vm->weak_globals;
977 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700978 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700979 if (result == kClearedJniWeakGlobal) {
980 // This is a special case where it's okay to return NULL.
981 return NULL;
982 }
983 break;
984 }
985 case kSirtOrInvalid:
986 default:
987 // TODO: make stack indirect reference table lookup more efficient
988 // Check if this is a local reference in the SIRT
989 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700990 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700991 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700992 // Assume an invalid local reference is actually a direct pointer.
993 result = reinterpret_cast<Object*>(obj);
994 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700995 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700996 }
997 }
998
999 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001000 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1001 JniAbort(NULL);
1002 } else {
1003 if (result != kInvalidIndirectRefObject) {
1004 Heap::VerifyObject(result);
1005 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001006 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001007 return result;
1008}
1009
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001010class CountStackDepthVisitor : public Thread::StackVisitor {
1011 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001012 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001013
Ian Rogersbdb03912011-09-14 00:55:44 -07001014 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001015 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001016 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001017
1018 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001019 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001020 }
1021
1022 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001023 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001024};
1025
Ian Rogersaaa20802011-09-11 21:47:37 -07001026//
1027class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001028 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001029 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1030 // Allocate method trace with an extra slot that will hold the PC trace
1031 method_trace_ = Runtime::Current()->GetClassLinker()->
1032 AllocObjectArray<Object>(depth + 1);
1033 // Register a local reference as IntArray::Alloc may trigger GC
1034 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1035 pc_trace_ = IntArray::Alloc(depth);
1036#ifdef MOVING_GARBAGE_COLLECTOR
1037 // Re-read after potential GC
1038 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1039#endif
1040 // Save PC trace in last element of method trace, also places it into the
1041 // object graph.
1042 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001043 }
1044
Ian Rogersaaa20802011-09-11 21:47:37 -07001045 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001046
Ian Rogersbdb03912011-09-14 00:55:44 -07001047 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001048 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001049 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001050 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001051 }
1052
Ian Rogersaaa20802011-09-11 21:47:37 -07001053 jobject GetInternalStackTrace() const {
1054 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001055 }
1056
1057 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001058 // Current position down stack trace
1059 uint32_t count_;
1060 // Array of return PC values
1061 IntArray* pc_trace_;
1062 // An array of the methods on the stack, the last entry is a reference to the
1063 // PC trace
1064 ObjectArray<Object>* method_trace_;
1065 // Local indirect reference table entry for method trace
1066 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001067};
1068
Ian Rogersaaa20802011-09-11 21:47:37 -07001069void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001070 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001071 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001072 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1073 // CHECK(native_to_managed_record_ != NULL);
1074 NativeToManagedRecord* record = native_to_managed_record_;
1075
Ian Rogersbdb03912011-09-14 00:55:44 -07001076 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001077 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001078 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1079 visitor->VisitFrame(frame, pc);
1080 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001081 }
1082 if (record == NULL) {
1083 break;
1084 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001085 // last_tos should return Frame instead of sp?
1086 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1087 pc = record->last_top_of_managed_stack_pc_;
1088 record = record->link_;
1089 }
1090}
1091
Ian Rogers67375ac2011-09-14 00:55:44 -07001092void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001093 Frame frame = GetTopOfStack();
1094 uintptr_t pc = top_of_managed_stack_pc_;
1095
1096 if (frame.GetSP() != 0) {
1097 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001098 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001099 visitor->VisitFrame(frame, pc);
1100 pc = frame.GetReturnPC();
1101 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001102 if (include_upcall) {
1103 visitor->VisitFrame(frame, pc);
1104 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001105 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001106}
1107
Ian Rogersaaa20802011-09-11 21:47:37 -07001108jobject Thread::CreateInternalStackTrace() const {
1109 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001110 CountStackDepthVisitor count_visitor;
1111 WalkStack(&count_visitor);
1112 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001113
Ian Rogersaaa20802011-09-11 21:47:37 -07001114 // Transition into runnable state to work on Object*/Array*
1115 ScopedJniThreadState ts(jni_env_);
1116
1117 // Build internal stack trace
1118 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001119 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001120
Ian Rogersaaa20802011-09-11 21:47:37 -07001121 return build_trace_visitor.GetInternalStackTrace();
1122}
1123
1124jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1125 JNIEnv* env) {
1126 // Transition into runnable state to work on Object*/Array*
1127 ScopedJniThreadState ts(env);
1128
1129 // Decode the internal stack trace into the depth, method trace and PC trace
1130 ObjectArray<Object>* method_trace =
1131 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1132 int32_t depth = method_trace->GetLength()-1;
1133 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1134
1135 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1136
1137 // Create java_trace array and place in local reference table
1138 ObjectArray<StackTraceElement>* java_traces =
1139 class_linker->AllocStackTraceElementArray(depth);
1140 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001141
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001142 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001143 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1144 Method* method = down_cast<Method*>(method_trace->Get(i));
1145 uint32_t native_pc = pc_trace->Get(i);
1146 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001147 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001148 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001149
Ian Rogersaaa20802011-09-11 21:47:37 -07001150 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001151 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001152 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001153 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001154 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001155 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001156 method->ToDexPC(native_pc)));
1157#ifdef MOVING_GARBAGE_COLLECTOR
1158 // Re-read after potential GC
1159 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1160 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1161 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1162#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001163 java_traces->Set(i, obj);
1164 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001165 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001166}
1167
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001168void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001169 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001170 va_list args;
1171 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001172 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001173 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001174
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001175 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001176 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001177 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001178 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001179 descriptor.erase(descriptor.length() - 1);
1180
1181 JNIEnv* env = GetJniEnv();
1182 jclass exception_class = env->FindClass(descriptor.c_str());
1183 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1184 int rc = env->ThrowNew(exception_class, msg.c_str());
1185 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001186}
1187
Elliott Hughes79082e32011-08-25 12:07:32 -07001188void Thread::ThrowOutOfMemoryError() {
1189 UNIMPLEMENTED(FATAL);
1190}
1191
Ian Rogersbdb03912011-09-14 00:55:44 -07001192Method* Thread::CalleeSaveMethod() const {
1193 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001194 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001195#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001196 method->SetCode(NULL, art::kThumb2, NULL);
1197 method->SetFrameSizeInBytes(64);
1198 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001199 method->SetCoreSpillMask((1 << art::arm::R1) |
1200 (1 << art::arm::R2) |
1201 (1 << art::arm::R3) |
1202 (1 << art::arm::R4) |
1203 (1 << art::arm::R5) |
1204 (1 << art::arm::R6) |
1205 (1 << art::arm::R7) |
1206 (1 << art::arm::R8) |
1207 (1 << art::arm::R9) |
1208 (1 << art::arm::R10) |
1209 (1 << art::arm::R11) |
1210 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001211 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001212#elif defined(__i386__)
1213 method->SetCode(NULL, art::kX86, NULL);
1214 method->SetFrameSizeInBytes(32);
1215 method->SetReturnPcOffsetInBytes(28);
1216 method->SetCoreSpillMask((1 << art::x86::EBX) |
1217 (1 << art::x86::EBP) |
1218 (1 << art::x86::ESI) |
1219 (1 << art::x86::EDI));
1220 method->SetFpSpillMask(0);
1221#else
1222 UNIMPLEMENTED(FATAL);
1223#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001224 return method;
1225}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001226
Ian Rogersbdb03912011-09-14 00:55:44 -07001227class CatchBlockStackVisitor : public Thread::StackVisitor {
1228 public:
1229 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001230 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1231#ifndef NDEBUG
1232 handler_pc_ = 0xEBADC0DE;
1233 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1234#endif
1235 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001236
Ian Rogersbdb03912011-09-14 00:55:44 -07001237 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1238 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001239 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001240 if (method == NULL) {
1241 // This is the upcall, we remember the frame and last_pc so that we may
1242 // long jump to them
1243 handler_pc_ = pc;
1244 handler_frame_ = fr;
1245 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001246 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001247 uint32_t dex_pc = DexFile::kDexNoIndex;
1248 if (pc > 0) {
1249 if (method->IsNative()) {
1250 native_method_count_++;
1251 } else {
1252 // Move the PC back 2 bytes as a call will frequently terminate the
1253 // decoding of a particular instruction and we want to make sure we
1254 // get the Dex PC of the instruction with the call and not the
1255 // instruction following.
1256 pc -= 2;
1257 dex_pc = method->ToDexPC(pc);
1258 }
1259 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001260 if (dex_pc != DexFile::kDexNoIndex) {
1261 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1262 if (found_dex_pc != DexFile::kDexNoIndex) {
1263 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001264 handler_pc_ = method->ToNativePC(found_dex_pc);
1265 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001266 }
1267 }
1268 if (!found_) {
1269 // Caller may be handler, fill in callee saves in context
1270 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001271 }
1272 }
1273 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001274
1275 // Did we find a catch block yet?
1276 bool found_;
1277 // The type of the exception catch block to find
1278 Class* to_find_;
1279 // Frame with found handler or last frame if no handler found
1280 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001281 // PC to branch to for the handler
1282 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001283 // Context that will be the target of the long jump
1284 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001285 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1286 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001287};
1288
1289void Thread::DeliverException(Throwable* exception) {
1290 SetException(exception); // Set exception on thread
1291
1292 Context* long_jump_context = GetLongJumpContext();
1293 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001294 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001295
Ian Rogers67375ac2011-09-14 00:55:44 -07001296 // Pop any SIRT
1297 if (catch_finder.native_method_count_ == 1) {
1298 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001299 } else {
Ian Rogers67375ac2011-09-14 00:55:44 -07001300 // We only expect the stack crawl to have passed 1 native method as its terminated
1301 // by a up call
1302 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001303 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001304 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1305 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001306 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001307}
1308
Ian Rogersbdb03912011-09-14 00:55:44 -07001309Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001310 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001311 if (result == NULL) {
1312 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001313 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001314 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001315 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001316}
1317
Elliott Hughes5f791332011-09-15 17:45:30 -07001318bool Thread::HoldsLock(Object* object) {
1319 if (object == NULL) {
1320 return false;
1321 }
1322 return object->GetLockOwner() == thin_lock_id_;
1323}
1324
Elliott Hughes410c0c82011-09-01 17:58:25 -07001325void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001326 if (exception_ != NULL) {
1327 visitor(exception_, arg);
1328 }
1329 if (peer_ != NULL) {
1330 visitor(peer_, arg);
1331 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001332 jni_env_->locals.VisitRoots(visitor, arg);
1333 jni_env_->monitors.VisitRoots(visitor, arg);
1334 // visitThreadStack(visitor, thread, arg);
1335 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1336}
1337
Ian Rogersb033c752011-07-20 12:22:35 -07001338static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001339 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001340 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001341 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001342 "Blocked",
1343 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001344 "Initializing",
1345 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001346 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001347 "VmWait",
1348 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001349};
1350std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001351 int int_state = static_cast<int>(state);
1352 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1353 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001354 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001355 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001356 }
1357 return os;
1358}
1359
Elliott Hughes330304d2011-08-12 14:28:05 -07001360std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1361 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001362 << ",pthread_t=" << thread.GetImpl()
1363 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001364 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001365 << ",state=" << thread.GetState()
1366 << ",peer=" << thread.GetPeer()
1367 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001368 return os;
1369}
1370
Elliott Hughes8daa0922011-09-11 13:46:25 -07001371} // namespace art