blob: dde0f66a3a7c0b982c66a69a91f687802142c68d [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
21#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070030#include "context.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070031#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070032#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070033#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070035#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070036#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070037#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070038#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070039
40namespace art {
41
42pthread_key_t Thread::pthread_key_self_;
43
Elliott Hughes038a8062011-09-18 14:12:41 -070044static Field* gThread_daemon = NULL;
45static Field* gThread_group = NULL;
46static Field* gThread_lock = NULL;
47static Field* gThread_name = NULL;
48static Field* gThread_priority = NULL;
49static Field* gThread_vmData = NULL;
50static Field* gThreadGroup_name = NULL;
51static Method* gThread_run = NULL;
52
buzbee4a3164f2011-09-03 11:25:10 -070053// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070054void DebugMe(Method* method, uint32_t info) {
buzbee4a3164f2011-09-03 11:25:10 -070055 LOG(INFO) << "DebugMe";
56 if (method != NULL)
57 LOG(INFO) << PrettyMethod(method);
58 LOG(INFO) << "Info: " << info;
59}
60
Ian Rogersbdb03912011-09-14 00:55:44 -070061} // namespace art
62
63// Called by generated call to throw an exception
Ian Rogers67375ac2011-09-14 00:55:44 -070064extern "C" void artDeliverExceptionHelper(art::Throwable* exception,
65 art::Thread* thread,
66 art::Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070067 /*
68 * exception may be NULL, in which case this routine should
69 * throw NPE. NOTE: this is a convenience for generated code,
70 * which previously did the null check inline and constructed
71 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070072 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070073 */
Ian Rogers67375ac2011-09-14 00:55:44 -070074#if defined(__i386__)
75 thread = art::Thread::Current(); // TODO: fix passing this in as an argument
76#endif
77 // Place a special frame at the TOS that will save all callee saves
Ian Rogersbdb03912011-09-14 00:55:44 -070078 *sp = thread->CalleeSaveMethod();
79 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070080 if (exception == NULL) {
81 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
82 exception = thread->GetException();
83 }
Ian Rogersbdb03912011-09-14 00:55:44 -070084 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070085}
86
Ian Rogersbdb03912011-09-14 00:55:44 -070087namespace art {
88
buzbee1b4c8592011-08-31 10:43:51 -070089// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070090Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070091 /*
92 * Should initialize & fix up method->dex_cache_resolved_types_[].
93 * Returns initialized type. Does not return normally if an exception
94 * is thrown, but instead initiates the catch. Should be similar to
95 * ClassLinker::InitializeStaticStorageFromCode.
96 */
97 UNIMPLEMENTED(FATAL);
98 return NULL;
99}
100
buzbee561227c2011-09-02 15:28:19 -0700101// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700102void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700103 /*
104 * Slow-path handler on invoke virtual method path in which
105 * base method is unresolved at compile-time. Doesn't need to
106 * return anything - just either ensure that
107 * method->dex_cache_resolved_methods_(method_idx) != NULL or
108 * throw and unwind. The caller will restart call sequence
109 * from the beginning.
110 */
111}
112
buzbee1da522d2011-09-04 11:22:20 -0700113// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700114Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700115 /*
116 * Just a wrapper around Array::AllocFromCode() that additionally
117 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
118 */
119 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
120 return Array::AllocFromCode(type_index, method, component_count);
121}
122
buzbee2a475e72011-09-07 17:19:17 -0700123// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700124void CheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700125 DCHECK(a->IsClass());
126 DCHECK(b->IsClass());
127 if (b->IsAssignableFrom(a)) {
128 return;
129 }
130 UNIMPLEMENTED(FATAL);
buzbee2a475e72011-09-07 17:19:17 -0700131}
132
Elliott Hughesd369bb72011-09-12 14:41:14 -0700133void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700134 // TODO: throw and unwind if lock not held
135 // TODO: throw and unwind on NPE
136 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700137}
138
Elliott Hughesd369bb72011-09-12 14:41:14 -0700139void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700140 obj->MonitorEnter(thread);
141 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700142}
143
Elliott Hughesd369bb72011-09-12 14:41:14 -0700144void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700145 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700146}
147
buzbeecefd1872011-09-09 09:59:52 -0700148// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700149void StackOverflowFromCode(Method* method) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700150 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700151 //NOTE: to save code space, this handler needs to look up its own Thread*
152 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700153}
154
buzbee5ade1d22011-09-09 14:44:52 -0700155// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700156void ThrowNullPointerFromCode() {
157 Thread::Current()->Dump(std::cerr);
158 //NOTE: to save code space, this handler must look up caller's Method*
159 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700160}
161
162// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700163void ThrowDivZeroFromCode() {
164 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700165}
166
167// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700168void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
169 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700170}
171
172// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700173void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700174 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
175 " ref: " << ref;
176}
177
178// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700179void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700180 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
181}
182
183// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700184void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700185 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
186}
187
188// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700189void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700190 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
191}
192
193// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700194void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700195 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
196}
197
Ian Rogersbdb03912011-09-14 00:55:44 -0700198void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
199 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
200 "abstract method \"%s\"",
201 PrettyMethod(method).c_str());
202 thread->DeliverException(thread->GetException());
203}
204
205
buzbee5ade1d22011-09-09 14:44:52 -0700206/*
207 * Temporary placeholder. Should include run-time checks for size
208 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
209 * As with other new "FromCode" routines, this should return to the caller
210 * only if no exception has been thrown.
211 *
212 * NOTE: When dealing with a raw dex file, the data to be copied uses
213 * little-endian ordering. Require that oat2dex do any required swapping
214 * so this routine can get by with a memcpy().
215 *
216 * Format of the data:
217 * ushort ident = 0x0300 magic value
218 * ushort width width of each element in the table
219 * uint size number of elements in the table
220 * ubyte data[size*width] table of data values (may contain a single-byte
221 * padding at the end)
222 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700223void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700224 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
225 uint32_t size_in_bytes = size * table[1];
226 if (static_cast<int32_t>(size) > array->GetLength()) {
227 ThrowArrayBoundsFromCode(array->GetLength(), size);
228 }
229 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
230 (char*)&table[4], size_in_bytes);
231}
232
Brian Carlstrom16192862011-09-12 17:50:06 -0700233/*
234 * TODO: placeholder for a method that can be called by the
235 * invoke-interface trampoline to unwind and handle exception. The
236 * trampoline will arrange it so that the caller appears to be the
237 * callsite of the failed invoke-interface. See comments in
238 * runtime_support.S
239 */
240extern "C" void artFailedInvokeInterface() {
241 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
242}
243
244// See comments in runtime_support.S
245extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
246 Object* this_object , Method* caller_method)
247{
248 if (this_object == NULL) {
249 ThrowNullPointerFromCode();
250 }
251 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
252 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
253 if (interface_method == NULL) {
254 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
255 }
256 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
257 const void* code = method->GetCode();
258
259 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
260 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
261 uint64_t result = ((code_uint << 32) | method_uint);
262 return result;
263}
264
buzbee5ade1d22011-09-09 14:44:52 -0700265// TODO: move to more appropriate location
266/*
267 * Float/double conversion requires clamping to min and max of integer form. If
268 * target doesn't support this normally, use these.
269 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700270int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700271 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
272 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
273 if (d >= kMaxLong)
274 return (int64_t)0x7fffffffffffffffULL;
275 else if (d <= kMinLong)
276 return (int64_t)0x8000000000000000ULL;
277 else if (d != d) // NaN case
278 return 0;
279 else
280 return (int64_t)d;
281}
282
Elliott Hughesd369bb72011-09-12 14:41:14 -0700283int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700284 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
285 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
286 if (f >= kMaxLong)
287 return (int64_t)0x7fffffffffffffffULL;
288 else if (f <= kMinLong)
289 return (int64_t)0x8000000000000000ULL;
290 else if (f != f) // NaN case
291 return 0;
292 else
293 return (int64_t)f;
294}
295
Brian Carlstrom16192862011-09-12 17:50:06 -0700296// Return value helper for jobject return types
297static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
298 return thread->DecodeJObject(obj);
299}
300
buzbee3ea4ec52011-08-22 17:37:19 -0700301void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700302#if defined(__arm__)
303 pShlLong = art_shl_long;
304 pShrLong = art_shr_long;
305 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700306 pIdiv = __aeabi_idiv;
307 pIdivmod = __aeabi_idivmod;
308 pI2f = __aeabi_i2f;
309 pF2iz = __aeabi_f2iz;
310 pD2f = __aeabi_d2f;
311 pF2d = __aeabi_f2d;
312 pD2iz = __aeabi_d2iz;
313 pL2f = __aeabi_l2f;
314 pL2d = __aeabi_l2d;
315 pFadd = __aeabi_fadd;
316 pFsub = __aeabi_fsub;
317 pFdiv = __aeabi_fdiv;
318 pFmul = __aeabi_fmul;
319 pFmodf = fmodf;
320 pDadd = __aeabi_dadd;
321 pDsub = __aeabi_dsub;
322 pDdiv = __aeabi_ddiv;
323 pDmul = __aeabi_dmul;
324 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700325 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700326 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700327 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700328#endif
Ian Rogers67375ac2011-09-14 00:55:44 -0700329 pDeliverException = art_deliver_exception;
buzbeec396efc2011-09-11 09:36:41 -0700330 pF2l = F2L;
331 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700332 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700333 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700334 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700335 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700336 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700337 pGet32Static = Field::Get32StaticFromCode;
338 pSet32Static = Field::Set32StaticFromCode;
339 pGet64Static = Field::Get64StaticFromCode;
340 pSet64Static = Field::Set64StaticFromCode;
341 pGetObjStatic = Field::GetObjStaticFromCode;
342 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700343 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700344 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700345 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700346 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700347 pInstanceofNonTrivialFromCode = Object::InstanceOf;
348 pCheckCastFromCode = CheckCastFromCode;
349 pLockObjectFromCode = LockObjectFromCode;
350 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700351 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700352 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700353 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700354 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
355 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
356 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
357 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
358 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
359 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
360 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
361 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700362 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700363 pFindNativeMethod = FindNativeMethod;
364 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700365 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700366}
367
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700368void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700369 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
370 DCHECK_NE(frame_size, 0u);
371 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700372 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700373 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700375 DCHECK(*sp_ == NULL ||
376 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700377}
378
Ian Rogersbdb03912011-09-14 00:55:44 -0700379uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700380 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700381 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700382 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700383}
384
Ian Rogersbdb03912011-09-14 00:55:44 -0700385uintptr_t Frame::LoadCalleeSave(int num) const {
386 // Callee saves are held at the top of the frame
387 Method* method = GetMethod();
388 DCHECK(method != NULL);
389 size_t frame_size = method->GetFrameSizeInBytes();
390 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
391 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700392#if defined(__i386__)
393 save_addr -= kPointerSize; // account for return address
394#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700395 return *reinterpret_cast<uintptr_t*>(save_addr);
396}
397
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700399 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700400 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700402}
403
Brian Carlstrom78128a62011-09-15 17:21:19 -0700404void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700405 Thread* self = reinterpret_cast<Thread*>(arg);
406 Runtime* runtime = Runtime::Current();
407
408 self->Attach(runtime);
409
Elliott Hughes038a8062011-09-18 14:12:41 -0700410 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700411 if (thread_name != NULL) {
412 SetThreadName(thread_name->ToModifiedUtf8().c_str());
413 }
414
415 // Wait until it's safe to start running code. (There may have been a suspend-all
416 // in progress while we were starting up.)
417 runtime->GetThreadList()->WaitForGo();
418
419 // TODO: say "hi" to the debugger.
420 //if (gDvm.debuggerConnected) {
421 // dvmDbgPostThreadStart(self);
422 //}
423
424 // Invoke the 'run' method of our java.lang.Thread.
425 CHECK(self->peer_ != NULL);
426 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700427 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700428 m->Invoke(self, receiver, NULL, NULL);
429
430 // Detach.
431 runtime->GetThreadList()->Unregister();
432
Carl Shapirob5573532011-07-12 18:22:59 -0700433 return NULL;
434}
435
Elliott Hughes93e74e82011-09-13 11:07:03 -0700436void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700437 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700438}
439
Elliott Hughesd369bb72011-09-12 14:41:14 -0700440void Thread::Create(Object* peer, size_t stack_size) {
441 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700442
Elliott Hughesd369bb72011-09-12 14:41:14 -0700443 if (stack_size == 0) {
444 stack_size = Runtime::Current()->GetDefaultStackSize();
445 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700446
Elliott Hughes93e74e82011-09-13 11:07:03 -0700447 Thread* native_thread = new Thread;
448 native_thread->peer_ = peer;
449
450 // Thread.start is synchronized, so we know that vmData is 0,
451 // and know that we're not racing to assign it.
452 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700453
454 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700455 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
456 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
457 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
458 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
459 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700460
461 // Let the child know when it's safe to start running.
462 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700463}
464
Elliott Hughes93e74e82011-09-13 11:07:03 -0700465void Thread::Attach(const Runtime* runtime) {
466 InitCpu();
467 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700468
Elliott Hughes93e74e82011-09-13 11:07:03 -0700469 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700470
Elliott Hughes93e74e82011-09-13 11:07:03 -0700471 tid_ = ::art::GetTid();
472 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700473
Elliott Hughes93e74e82011-09-13 11:07:03 -0700474 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700475
Elliott Hughes8d768a92011-09-14 16:35:25 -0700476 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700477
Elliott Hughes93e74e82011-09-13 11:07:03 -0700478 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700479
Elliott Hughes93e74e82011-09-13 11:07:03 -0700480 runtime->GetThreadList()->Register(this);
481}
482
483Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
484 Thread* self = new Thread;
485 self->Attach(runtime);
486
487 self->SetState(Thread::kRunnable);
488
489 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700490
491 // If we're the main thread, ClassLinker won't be created until after we're attached,
492 // so that thread needs a two-stage attach. Regular threads don't need this hack.
493 if (self->thin_lock_id_ != ThreadList::kMainId) {
494 self->CreatePeer(name, as_daemon);
495 }
496
497 return self;
498}
499
Elliott Hughesd369bb72011-09-12 14:41:14 -0700500jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
501 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
502 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
503 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
504 // This will be null in the compiler (and tests), but never in a running system.
505 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
506 return thread_group;
507}
508
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700509void Thread::CreatePeer(const char* name, bool as_daemon) {
510 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
511
512 JNIEnv* env = jni_env_;
513
Elliott Hughesd369bb72011-09-12 14:41:14 -0700514 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
515 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700516 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700517 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700518 jboolean thread_is_daemon = as_daemon;
519
520 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700521 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700522
Elliott Hughes8daa0922011-09-11 13:46:25 -0700523 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700524
525 // Because we mostly run without code available (in the compiler, in tests), we
526 // manually assign the fields the constructor should have set.
527 // TODO: lose this.
528 jfieldID fid;
529 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
530 env->SetObjectField(peer, fid, thread_group);
531 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
532 env->SetObjectField(peer, fid, thread_name);
533 fid = env->GetFieldID(c, "priority", "I");
534 env->SetIntField(peer, fid, thread_priority);
535 fid = env->GetFieldID(c, "daemon", "Z");
536 env->SetBooleanField(peer, fid, thread_is_daemon);
537
538 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700539}
540
Elliott Hughesbe759c62011-09-08 19:38:21 -0700541void Thread::InitStackHwm() {
542 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700543 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700544
Elliott Hughesbe759c62011-09-08 19:38:21 -0700545 void* stack_base;
546 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700547 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700548
Elliott Hughesbe759c62011-09-08 19:38:21 -0700549 if (stack_size <= kStackOverflowReservedBytes) {
550 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
551 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700552
553 // stack_base is the "lowest addressable byte" of the stack.
554 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
555 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700556 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700557
558 // Sanity check.
559 int stack_variable;
560 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700561
Elliott Hughes8d768a92011-09-14 16:35:25 -0700562 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700563}
564
Elliott Hughesa0957642011-09-02 14:27:33 -0700565void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700566 DumpState(os);
567 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700568}
569
Elliott Hughesd92bec42011-09-02 17:04:36 -0700570std::string GetSchedulerGroup(pid_t tid) {
571 // /proc/<pid>/group looks like this:
572 // 2:devices:/
573 // 1:cpuacct,cpu:/
574 // We want the third field from the line whose second field contains the "cpu" token.
575 std::string cgroup_file;
576 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
577 return "";
578 }
579 std::vector<std::string> cgroup_lines;
580 Split(cgroup_file, '\n', cgroup_lines);
581 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
582 std::vector<std::string> cgroup_fields;
583 Split(cgroup_lines[i], ':', cgroup_fields);
584 std::vector<std::string> cgroups;
585 Split(cgroup_fields[1], ',', cgroups);
586 for (size_t i = 0; i < cgroups.size(); ++i) {
587 if (cgroups[i] == "cpu") {
588 return cgroup_fields[2].substr(1); // Skip the leading slash.
589 }
590 }
591 }
592 return "";
593}
594
595void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700596 std::string thread_name("<native thread without managed peer>");
597 std::string group_name;
598 int priority;
599 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700600
Elliott Hughesd369bb72011-09-12 14:41:14 -0700601 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700602 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700603 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700604 priority = gThread_priority->GetInt(peer_);
605 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700606
Elliott Hughes038a8062011-09-18 14:12:41 -0700607 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700608 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700609 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700610 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
611 }
612 } else {
613 // 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 -0700614 std::string stats;
615 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
616 size_t start = stats.find('(') + 1;
617 size_t end = stats.find(')') - start;
618 thread_name = stats.substr(start, end);
619 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700620 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700621 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700622
623 int policy;
624 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700625 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700626
627 std::string scheduler_group(GetSchedulerGroup(GetTid()));
628 if (scheduler_group.empty()) {
629 scheduler_group = "default";
630 }
631
Elliott Hughesd92bec42011-09-02 17:04:36 -0700632 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700633 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700634 os << " daemon";
635 }
636 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700637 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700638 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700639
Elliott Hughesd92bec42011-09-02 17:04:36 -0700640 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700641 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700642 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700643 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700644 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700645 << " self=" << reinterpret_cast<const void*>(this) << "\n";
646 os << " | sysTid=" << GetTid()
647 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
648 << " sched=" << policy << "/" << sp.sched_priority
649 << " cgrp=" << scheduler_group
650 << " handle=" << GetImpl() << "\n";
651
652 // Grab the scheduler stats for this thread.
653 std::string scheduler_stats;
654 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
655 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
656 } else {
657 scheduler_stats = "0 0 0";
658 }
659
660 int utime = 0;
661 int stime = 0;
662 int task_cpu = 0;
663 std::string stats;
664 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
665 // Skip the command, which may contain spaces.
666 stats = stats.substr(stats.find(')') + 2);
667 // Extract the three fields we care about.
668 std::vector<std::string> fields;
669 Split(stats, ' ', fields);
670 utime = strtoull(fields[11].c_str(), NULL, 10);
671 stime = strtoull(fields[12].c_str(), NULL, 10);
672 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
673 }
674
675 os << " | schedstat=( " << scheduler_stats << " )"
676 << " utm=" << utime
677 << " stm=" << stime
678 << " core=" << task_cpu
679 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
680}
681
Elliott Hughesd369bb72011-09-12 14:41:14 -0700682struct StackDumpVisitor : public Thread::StackVisitor {
683 StackDumpVisitor(std::ostream& os) : os(os) {
684 }
685
Ian Rogersbdb03912011-09-14 00:55:44 -0700686 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700687 }
688
Ian Rogersbdb03912011-09-14 00:55:44 -0700689 void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700690 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
691
692 Method* m = frame.GetMethod();
693 Class* c = m->GetDeclaringClass();
694 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
695
696 os << " at " << PrettyMethod(m, false);
697 if (m->IsNative()) {
698 os << "(Native method)";
699 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700700 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700701 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
702 }
703 os << "\n";
704 }
705
706 std::ostream& os;
707};
708
Elliott Hughesd92bec42011-09-02 17:04:36 -0700709void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700710 StackDumpVisitor dumper(os);
711 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700712}
713
Elliott Hughes8d768a92011-09-14 16:35:25 -0700714Thread::State Thread::SetState(Thread::State new_state) {
715 Thread::State old_state = state_;
716 if (old_state == new_state) {
717 return old_state;
718 }
719
720 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
721 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
722
723 if (new_state == Thread::kRunnable) {
724 /*
725 * Change our status to Thread::kRunnable. The transition requires
726 * that we check for pending suspension, because the VM considers
727 * us to be "asleep" in all other states, and another thread could
728 * be performing a GC now.
729 *
730 * The order of operations is very significant here. One way to
731 * do this wrong is:
732 *
733 * GCing thread Our thread (in kNative)
734 * ------------ ----------------------
735 * check suspend count (== 0)
736 * SuspendAllThreads()
737 * grab suspend-count lock
738 * increment all suspend counts
739 * release suspend-count lock
740 * check thread state (== kNative)
741 * all are suspended, begin GC
742 * set state to kRunnable
743 * (continue executing)
744 *
745 * We can correct this by grabbing the suspend-count lock and
746 * performing both of our operations (check suspend count, set
747 * state) while holding it, now we need to grab a mutex on every
748 * transition to kRunnable.
749 *
750 * What we do instead is change the order of operations so that
751 * the transition to kRunnable happens first. If we then detect
752 * that the suspend count is nonzero, we switch to kSuspended.
753 *
754 * Appropriate compiler and memory barriers are required to ensure
755 * that the operations are observed in the expected order.
756 *
757 * This does create a small window of opportunity where a GC in
758 * progress could observe what appears to be a running thread (if
759 * it happens to look between when we set to kRunnable and when we
760 * switch to kSuspended). At worst this only affects assertions
761 * and thread logging. (We could work around it with some sort
762 * of intermediate "pre-running" state that is generally treated
763 * as equivalent to running, but that doesn't seem worthwhile.)
764 *
765 * We can also solve this by combining the "status" and "suspend
766 * count" fields into a single 32-bit value. This trades the
767 * store/load barrier on transition to kRunnable for an atomic RMW
768 * op on all transitions and all suspend count updates (also, all
769 * accesses to status or the thread count require bit-fiddling).
770 * It also eliminates the brief transition through kRunnable when
771 * the thread is supposed to be suspended. This is possibly faster
772 * on SMP and slightly more correct, but less convenient.
773 */
774 android_atomic_acquire_store(new_state, addr);
775 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
776 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
777 }
778 } else {
779 /*
780 * Not changing to Thread::kRunnable. No additional work required.
781 *
782 * We use a releasing store to ensure that, if we were runnable,
783 * any updates we previously made to objects on the managed heap
784 * will be observed before the state change.
785 */
786 android_atomic_release_store(new_state, addr);
787 }
788
789 return old_state;
790}
791
792void Thread::WaitUntilSuspended() {
793 // TODO: dalvik dropped the waiting thread's priority after a while.
794 // TODO: dalvik timed out and aborted.
795 useconds_t delay = 0;
796 while (GetState() == Thread::kRunnable) {
797 useconds_t new_delay = delay * 2;
798 CHECK_GE(new_delay, delay);
799 delay = new_delay;
800 if (delay == 0) {
801 sched_yield();
802 delay = 10000;
803 } else {
804 usleep(delay);
805 }
806 }
807}
808
Elliott Hughesbe759c62011-09-08 19:38:21 -0700809void Thread::ThreadExitCallback(void* arg) {
810 Thread* self = reinterpret_cast<Thread*>(arg);
811 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700812}
813
Elliott Hughesbe759c62011-09-08 19:38:21 -0700814void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700815 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700816 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700817
818 // Double-check the TLS slot allocation.
819 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700820 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700821 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700822}
Carl Shapirob5573532011-07-12 18:22:59 -0700823
Elliott Hughes038a8062011-09-18 14:12:41 -0700824void Thread::FinishStartup() {
825 // Finish attaching the main thread.
826 Thread::Current()->CreatePeer("main", false);
827
828 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
829 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
830 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
831 Class* int_class = class_linker->FindPrimitiveClass('I');
832 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
833 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
834 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
835 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
836 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
837 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
838 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
839 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
840 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
841 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
842 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
843 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Carl Shapirob5573532011-07-12 18:22:59 -0700844}
845
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700846void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700847 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700848}
849
Elliott Hughesdcc24742011-09-07 14:02:44 -0700850Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700851 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700852 wait_mutex_(new Mutex("Thread wait mutex")),
853 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700854 wait_monitor_(NULL),
855 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700856 wait_next_(NULL),
857 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700858 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700859 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700860 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700861 native_to_managed_record_(NULL),
862 top_sirt_(NULL),
863 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700864 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700865 self_(NULL),
866 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700867 exception_(NULL),
868 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700869 class_loader_override_(NULL),
870 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700871}
872
Elliott Hughes02b48d12011-09-07 17:15:51 -0700873void MonitorExitVisitor(const Object* object, void*) {
874 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700875 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700876}
877
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700878Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700879 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700880 if (jni_env_ != NULL) {
881 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
882 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700883
884 if (IsExceptionPending()) {
885 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
886 }
887
888 // TODO: ThreadGroup.removeThread(this);
889
Elliott Hughes93e74e82011-09-13 11:07:03 -0700890 if (peer_ != NULL) {
891 SetVmData(peer_, NULL);
892 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700893
894 // TODO: say "bye" to the debugger.
895 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700896 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700897 //}
898
899 // Thread.join() is implemented as an Object.wait() on the Thread.lock
900 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700901 if (peer_ != NULL) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700902 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700903 Object* lock = gThread_lock->GetObject(peer_);
904 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700905 if (lock != NULL) {
906 lock->MonitorEnter(self);
907 lock->NotifyAll();
908 lock->MonitorExit(self);
909 }
910 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700911
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700912 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700913 jni_env_ = NULL;
914
915 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700916
917 delete wait_cond_;
918 delete wait_mutex_;
919
920 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700921}
922
Ian Rogers408f79a2011-08-23 18:22:33 -0700923size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700924 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700925 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700926 count += cur->NumberOfReferences();
927 }
928 return count;
929}
930
Ian Rogers408f79a2011-08-23 18:22:33 -0700931bool Thread::SirtContains(jobject obj) {
932 Object** sirt_entry = reinterpret_cast<Object**>(obj);
933 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700934 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700935 // A SIRT should always have a jobject/jclass as a native method is passed
936 // in a this pointer or a class
937 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700938 if ((&cur->References()[0] <= sirt_entry) &&
939 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700940 return true;
941 }
942 }
943 return false;
944}
945
Ian Rogers67375ac2011-09-14 00:55:44 -0700946void Thread::PopSirt() {
947 CHECK(top_sirt_ != NULL);
948 top_sirt_ = top_sirt_->Link();
949}
950
Ian Rogers408f79a2011-08-23 18:22:33 -0700951Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700952 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700953 if (obj == NULL) {
954 return NULL;
955 }
956 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
957 IndirectRefKind kind = GetIndirectRefKind(ref);
958 Object* result;
959 switch (kind) {
960 case kLocal:
961 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700962 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700963 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700964 break;
965 }
966 case kGlobal:
967 {
968 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
969 IndirectReferenceTable& globals = vm->globals;
970 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700971 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700972 break;
973 }
974 case kWeakGlobal:
975 {
976 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
977 IndirectReferenceTable& weak_globals = vm->weak_globals;
978 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700979 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700980 if (result == kClearedJniWeakGlobal) {
981 // This is a special case where it's okay to return NULL.
982 return NULL;
983 }
984 break;
985 }
986 case kSirtOrInvalid:
987 default:
988 // TODO: make stack indirect reference table lookup more efficient
989 // Check if this is a local reference in the SIRT
990 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700991 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700992 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700993 // Assume an invalid local reference is actually a direct pointer.
994 result = reinterpret_cast<Object*>(obj);
995 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700996 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700997 }
998 }
999
1000 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001001 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1002 JniAbort(NULL);
1003 } else {
1004 if (result != kInvalidIndirectRefObject) {
1005 Heap::VerifyObject(result);
1006 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001007 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001008 return result;
1009}
1010
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001011class CountStackDepthVisitor : public Thread::StackVisitor {
1012 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001013 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001014
Ian Rogersbdb03912011-09-14 00:55:44 -07001015 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001016 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001017 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001018
1019 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001020 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001021 }
1022
1023 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001024 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001025};
1026
Ian Rogersaaa20802011-09-11 21:47:37 -07001027//
1028class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001029 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001030 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1031 // Allocate method trace with an extra slot that will hold the PC trace
1032 method_trace_ = Runtime::Current()->GetClassLinker()->
1033 AllocObjectArray<Object>(depth + 1);
1034 // Register a local reference as IntArray::Alloc may trigger GC
1035 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1036 pc_trace_ = IntArray::Alloc(depth);
1037#ifdef MOVING_GARBAGE_COLLECTOR
1038 // Re-read after potential GC
1039 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1040#endif
1041 // Save PC trace in last element of method trace, also places it into the
1042 // object graph.
1043 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001044 }
1045
Ian Rogersaaa20802011-09-11 21:47:37 -07001046 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001047
Ian Rogersbdb03912011-09-14 00:55:44 -07001048 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001049 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001050 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001051 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001052 }
1053
Ian Rogersaaa20802011-09-11 21:47:37 -07001054 jobject GetInternalStackTrace() const {
1055 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001056 }
1057
1058 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001059 // Current position down stack trace
1060 uint32_t count_;
1061 // Array of return PC values
1062 IntArray* pc_trace_;
1063 // An array of the methods on the stack, the last entry is a reference to the
1064 // PC trace
1065 ObjectArray<Object>* method_trace_;
1066 // Local indirect reference table entry for method trace
1067 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001068};
1069
Ian Rogersaaa20802011-09-11 21:47:37 -07001070void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001071 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001072 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001073 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1074 // CHECK(native_to_managed_record_ != NULL);
1075 NativeToManagedRecord* record = native_to_managed_record_;
1076
Ian Rogersbdb03912011-09-14 00:55:44 -07001077 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001078 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001079 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1080 visitor->VisitFrame(frame, pc);
1081 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001082 }
1083 if (record == NULL) {
1084 break;
1085 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001086 // last_tos should return Frame instead of sp?
1087 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1088 pc = record->last_top_of_managed_stack_pc_;
1089 record = record->link_;
1090 }
1091}
1092
Ian Rogers67375ac2011-09-14 00:55:44 -07001093void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001094 Frame frame = GetTopOfStack();
1095 uintptr_t pc = top_of_managed_stack_pc_;
1096
1097 if (frame.GetSP() != 0) {
1098 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001099 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001100 visitor->VisitFrame(frame, pc);
1101 pc = frame.GetReturnPC();
1102 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001103 if (include_upcall) {
1104 visitor->VisitFrame(frame, pc);
1105 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001106 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001107}
1108
Ian Rogersaaa20802011-09-11 21:47:37 -07001109jobject Thread::CreateInternalStackTrace() const {
1110 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001111 CountStackDepthVisitor count_visitor;
1112 WalkStack(&count_visitor);
1113 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001114
Ian Rogersaaa20802011-09-11 21:47:37 -07001115 // Transition into runnable state to work on Object*/Array*
1116 ScopedJniThreadState ts(jni_env_);
1117
1118 // Build internal stack trace
1119 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001120 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001121
Ian Rogersaaa20802011-09-11 21:47:37 -07001122 return build_trace_visitor.GetInternalStackTrace();
1123}
1124
1125jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1126 JNIEnv* env) {
1127 // Transition into runnable state to work on Object*/Array*
1128 ScopedJniThreadState ts(env);
1129
1130 // Decode the internal stack trace into the depth, method trace and PC trace
1131 ObjectArray<Object>* method_trace =
1132 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1133 int32_t depth = method_trace->GetLength()-1;
1134 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1135
1136 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1137
1138 // Create java_trace array and place in local reference table
1139 ObjectArray<StackTraceElement>* java_traces =
1140 class_linker->AllocStackTraceElementArray(depth);
1141 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001142
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001143 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001144 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1145 Method* method = down_cast<Method*>(method_trace->Get(i));
1146 uint32_t native_pc = pc_trace->Get(i);
1147 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001148 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001149 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001150
Ian Rogersaaa20802011-09-11 21:47:37 -07001151 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001152 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001153 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001154 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001155 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001156 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001157 method->ToDexPC(native_pc)));
1158#ifdef MOVING_GARBAGE_COLLECTOR
1159 // Re-read after potential GC
1160 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1161 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1162 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1163#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001164 java_traces->Set(i, obj);
1165 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001166 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001167}
1168
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001169void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001170 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001171 va_list args;
1172 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001173 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001174 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001175
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001176 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001177 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001178 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001179 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001180 descriptor.erase(descriptor.length() - 1);
1181
1182 JNIEnv* env = GetJniEnv();
1183 jclass exception_class = env->FindClass(descriptor.c_str());
1184 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1185 int rc = env->ThrowNew(exception_class, msg.c_str());
1186 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001187}
1188
Elliott Hughes79082e32011-08-25 12:07:32 -07001189void Thread::ThrowOutOfMemoryError() {
1190 UNIMPLEMENTED(FATAL);
1191}
1192
Ian Rogersbdb03912011-09-14 00:55:44 -07001193Method* Thread::CalleeSaveMethod() const {
1194 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001195 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001196#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001197 method->SetCode(NULL, art::kThumb2, NULL);
1198 method->SetFrameSizeInBytes(64);
1199 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001200 method->SetCoreSpillMask((1 << art::arm::R1) |
1201 (1 << art::arm::R2) |
1202 (1 << art::arm::R3) |
1203 (1 << art::arm::R4) |
1204 (1 << art::arm::R5) |
1205 (1 << art::arm::R6) |
1206 (1 << art::arm::R7) |
1207 (1 << art::arm::R8) |
1208 (1 << art::arm::R9) |
1209 (1 << art::arm::R10) |
1210 (1 << art::arm::R11) |
1211 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001212 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001213#elif defined(__i386__)
1214 method->SetCode(NULL, art::kX86, NULL);
1215 method->SetFrameSizeInBytes(32);
1216 method->SetReturnPcOffsetInBytes(28);
1217 method->SetCoreSpillMask((1 << art::x86::EBX) |
1218 (1 << art::x86::EBP) |
1219 (1 << art::x86::ESI) |
1220 (1 << art::x86::EDI));
1221 method->SetFpSpillMask(0);
1222#else
1223 UNIMPLEMENTED(FATAL);
1224#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001225 return method;
1226}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001227
Ian Rogersbdb03912011-09-14 00:55:44 -07001228class CatchBlockStackVisitor : public Thread::StackVisitor {
1229 public:
1230 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001231 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1232#ifndef NDEBUG
1233 handler_pc_ = 0xEBADC0DE;
1234 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1235#endif
1236 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001237
Ian Rogersbdb03912011-09-14 00:55:44 -07001238 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1239 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001240 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001241 if (method == NULL) {
1242 // This is the upcall, we remember the frame and last_pc so that we may
1243 // long jump to them
1244 handler_pc_ = pc;
1245 handler_frame_ = fr;
1246 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001247 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001248 uint32_t dex_pc = DexFile::kDexNoIndex;
1249 if (pc > 0) {
1250 if (method->IsNative()) {
1251 native_method_count_++;
1252 } else {
1253 // Move the PC back 2 bytes as a call will frequently terminate the
1254 // decoding of a particular instruction and we want to make sure we
1255 // get the Dex PC of the instruction with the call and not the
1256 // instruction following.
1257 pc -= 2;
1258 dex_pc = method->ToDexPC(pc);
1259 }
1260 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001261 if (dex_pc != DexFile::kDexNoIndex) {
1262 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1263 if (found_dex_pc != DexFile::kDexNoIndex) {
1264 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001265 handler_pc_ = method->ToNativePC(found_dex_pc);
1266 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001267 }
1268 }
1269 if (!found_) {
1270 // Caller may be handler, fill in callee saves in context
1271 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001272 }
1273 }
1274 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001275
1276 // Did we find a catch block yet?
1277 bool found_;
1278 // The type of the exception catch block to find
1279 Class* to_find_;
1280 // Frame with found handler or last frame if no handler found
1281 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001282 // PC to branch to for the handler
1283 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001284 // Context that will be the target of the long jump
1285 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001286 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1287 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001288};
1289
1290void Thread::DeliverException(Throwable* exception) {
1291 SetException(exception); // Set exception on thread
1292
1293 Context* long_jump_context = GetLongJumpContext();
1294 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001295 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001296
Ian Rogers67375ac2011-09-14 00:55:44 -07001297 // Pop any SIRT
1298 if (catch_finder.native_method_count_ == 1) {
1299 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001300 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001301 // We only expect the stack crawl to have passed 1 native method as it's terminated
1302 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001303 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001304 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001305 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1306 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001307 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001308}
1309
Ian Rogersbdb03912011-09-14 00:55:44 -07001310Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001311 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001312 if (result == NULL) {
1313 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001314 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001315 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001316 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001317}
1318
Elliott Hughes5f791332011-09-15 17:45:30 -07001319bool Thread::HoldsLock(Object* object) {
1320 if (object == NULL) {
1321 return false;
1322 }
1323 return object->GetLockOwner() == thin_lock_id_;
1324}
1325
Elliott Hughes038a8062011-09-18 14:12:41 -07001326bool Thread::IsDaemon() {
1327 return gThread_daemon->GetBoolean(peer_);
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