blob: e1207d0518dfcef9b43836deb14b3408213ca127 [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);
Ian Rogers93dd9662011-09-17 23:21:22 -070071 if (exception == NULL) {
72 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
73 exception = thread->GetException();
74 }
Ian Rogersbdb03912011-09-14 00:55:44 -070075 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070076}
77
Ian Rogersbdb03912011-09-14 00:55:44 -070078namespace art {
79
buzbee1b4c8592011-08-31 10:43:51 -070080// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070081Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070082 /*
83 * Should initialize & fix up method->dex_cache_resolved_types_[].
84 * Returns initialized type. Does not return normally if an exception
85 * is thrown, but instead initiates the catch. Should be similar to
86 * ClassLinker::InitializeStaticStorageFromCode.
87 */
88 UNIMPLEMENTED(FATAL);
89 return NULL;
90}
91
buzbee561227c2011-09-02 15:28:19 -070092// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -070093void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -070094 /*
95 * Slow-path handler on invoke virtual method path in which
96 * base method is unresolved at compile-time. Doesn't need to
97 * return anything - just either ensure that
98 * method->dex_cache_resolved_methods_(method_idx) != NULL or
99 * throw and unwind. The caller will restart call sequence
100 * from the beginning.
101 */
102}
103
buzbee1da522d2011-09-04 11:22:20 -0700104// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700105Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700106 /*
107 * Just a wrapper around Array::AllocFromCode() that additionally
108 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
109 */
110 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
111 return Array::AllocFromCode(type_index, method, component_count);
112}
113
buzbee2a475e72011-09-07 17:19:17 -0700114// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700115void CheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700116 DCHECK(a->IsClass());
117 DCHECK(b->IsClass());
118 if (b->IsAssignableFrom(a)) {
119 return;
120 }
121 UNIMPLEMENTED(FATAL);
buzbee2a475e72011-09-07 17:19:17 -0700122}
123
Elliott Hughesd369bb72011-09-12 14:41:14 -0700124void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700125 // TODO: throw and unwind if lock not held
126 // TODO: throw and unwind on NPE
127 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700128}
129
Elliott Hughesd369bb72011-09-12 14:41:14 -0700130void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700131 obj->MonitorEnter(thread);
132 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700133}
134
Elliott Hughesd369bb72011-09-12 14:41:14 -0700135void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700136 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700137}
138
buzbeecefd1872011-09-09 09:59:52 -0700139// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700140void StackOverflowFromCode(Method* method) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700141 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700142 //NOTE: to save code space, this handler needs to look up its own Thread*
143 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700144}
145
buzbee5ade1d22011-09-09 14:44:52 -0700146// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700147void ThrowNullPointerFromCode() {
148 Thread::Current()->Dump(std::cerr);
149 //NOTE: to save code space, this handler must look up caller's Method*
150 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700151}
152
153// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700154void ThrowDivZeroFromCode() {
155 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700156}
157
158// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700159void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
160 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700161}
162
163// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700164void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700165 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
166 " ref: " << ref;
167}
168
169// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700170void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700171 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
172}
173
174// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700175void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700176 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
177}
178
179// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700180void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700181 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
182}
183
184// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700185void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700186 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
187}
188
Ian Rogersbdb03912011-09-14 00:55:44 -0700189void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
190 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
191 "abstract method \"%s\"",
192 PrettyMethod(method).c_str());
193 thread->DeliverException(thread->GetException());
194}
195
196
buzbee5ade1d22011-09-09 14:44:52 -0700197/*
198 * Temporary placeholder. Should include run-time checks for size
199 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
200 * As with other new "FromCode" routines, this should return to the caller
201 * only if no exception has been thrown.
202 *
203 * NOTE: When dealing with a raw dex file, the data to be copied uses
204 * little-endian ordering. Require that oat2dex do any required swapping
205 * so this routine can get by with a memcpy().
206 *
207 * Format of the data:
208 * ushort ident = 0x0300 magic value
209 * ushort width width of each element in the table
210 * uint size number of elements in the table
211 * ubyte data[size*width] table of data values (may contain a single-byte
212 * padding at the end)
213 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700214void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700215 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
216 uint32_t size_in_bytes = size * table[1];
217 if (static_cast<int32_t>(size) > array->GetLength()) {
218 ThrowArrayBoundsFromCode(array->GetLength(), size);
219 }
220 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
221 (char*)&table[4], size_in_bytes);
222}
223
Brian Carlstrom16192862011-09-12 17:50:06 -0700224/*
225 * TODO: placeholder for a method that can be called by the
226 * invoke-interface trampoline to unwind and handle exception. The
227 * trampoline will arrange it so that the caller appears to be the
228 * callsite of the failed invoke-interface. See comments in
229 * runtime_support.S
230 */
231extern "C" void artFailedInvokeInterface() {
232 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
233}
234
235// See comments in runtime_support.S
236extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
237 Object* this_object , Method* caller_method)
238{
239 if (this_object == NULL) {
240 ThrowNullPointerFromCode();
241 }
242 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
243 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
244 if (interface_method == NULL) {
245 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
246 }
247 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
248 const void* code = method->GetCode();
249
250 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
251 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
252 uint64_t result = ((code_uint << 32) | method_uint);
253 return result;
254}
255
buzbee5ade1d22011-09-09 14:44:52 -0700256// TODO: move to more appropriate location
257/*
258 * Float/double conversion requires clamping to min and max of integer form. If
259 * target doesn't support this normally, use these.
260 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700261int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700262 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
263 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
264 if (d >= kMaxLong)
265 return (int64_t)0x7fffffffffffffffULL;
266 else if (d <= kMinLong)
267 return (int64_t)0x8000000000000000ULL;
268 else if (d != d) // NaN case
269 return 0;
270 else
271 return (int64_t)d;
272}
273
Elliott Hughesd369bb72011-09-12 14:41:14 -0700274int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700275 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
276 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
277 if (f >= kMaxLong)
278 return (int64_t)0x7fffffffffffffffULL;
279 else if (f <= kMinLong)
280 return (int64_t)0x8000000000000000ULL;
281 else if (f != f) // NaN case
282 return 0;
283 else
284 return (int64_t)f;
285}
286
Brian Carlstrom16192862011-09-12 17:50:06 -0700287// Return value helper for jobject return types
288static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
289 return thread->DecodeJObject(obj);
290}
291
buzbee3ea4ec52011-08-22 17:37:19 -0700292void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700293#if defined(__arm__)
294 pShlLong = art_shl_long;
295 pShrLong = art_shr_long;
296 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700297 pIdiv = __aeabi_idiv;
298 pIdivmod = __aeabi_idivmod;
299 pI2f = __aeabi_i2f;
300 pF2iz = __aeabi_f2iz;
301 pD2f = __aeabi_d2f;
302 pF2d = __aeabi_f2d;
303 pD2iz = __aeabi_d2iz;
304 pL2f = __aeabi_l2f;
305 pL2d = __aeabi_l2d;
306 pFadd = __aeabi_fadd;
307 pFsub = __aeabi_fsub;
308 pFdiv = __aeabi_fdiv;
309 pFmul = __aeabi_fmul;
310 pFmodf = fmodf;
311 pDadd = __aeabi_dadd;
312 pDsub = __aeabi_dsub;
313 pDdiv = __aeabi_ddiv;
314 pDmul = __aeabi_dmul;
315 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700316 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700317 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700318 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogers67375ac2011-09-14 00:55:44 -0700319#endif
Ian Rogers67375ac2011-09-14 00:55:44 -0700320 pDeliverException = art_deliver_exception;
buzbeec396efc2011-09-11 09:36:41 -0700321 pF2l = F2L;
322 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700323 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700324 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700325 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700326 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700327 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700328 pGet32Static = Field::Get32StaticFromCode;
329 pSet32Static = Field::Set32StaticFromCode;
330 pGet64Static = Field::Get64StaticFromCode;
331 pSet64Static = Field::Set64StaticFromCode;
332 pGetObjStatic = Field::GetObjStaticFromCode;
333 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700334 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700335 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700336 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700337 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700338 pInstanceofNonTrivialFromCode = Object::InstanceOf;
339 pCheckCastFromCode = CheckCastFromCode;
340 pLockObjectFromCode = LockObjectFromCode;
341 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700342 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700343 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700344 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700345 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
346 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
347 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
348 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
349 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
350 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
351 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
352 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700353 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700354 pFindNativeMethod = FindNativeMethod;
355 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700356 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700357}
358
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700359void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700360 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
361 DCHECK_NE(frame_size, 0u);
362 DCHECK_LT(frame_size, 1024u);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700363 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Ian Rogers67375ac2011-09-14 00:55:44 -0700364 frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogers67375ac2011-09-14 00:55:44 -0700366 DCHECK(*sp_ == NULL ||
367 (*sp_)->GetClass()->GetDescriptor()->Equals("Ljava/lang/reflect/Method;"));
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700368}
369
Ian Rogersbdb03912011-09-14 00:55:44 -0700370uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700371 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700372 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700373 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700374}
375
Ian Rogersbdb03912011-09-14 00:55:44 -0700376uintptr_t Frame::LoadCalleeSave(int num) const {
377 // Callee saves are held at the top of the frame
378 Method* method = GetMethod();
379 DCHECK(method != NULL);
380 size_t frame_size = method->GetFrameSizeInBytes();
381 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
382 ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700383#if defined(__i386__)
384 save_addr -= kPointerSize; // account for return address
385#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700386 return *reinterpret_cast<uintptr_t*>(save_addr);
387}
388
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700390 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700391 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700393}
394
Brian Carlstrom78128a62011-09-15 17:21:19 -0700395void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700396 Thread* self = reinterpret_cast<Thread*>(arg);
397 Runtime* runtime = Runtime::Current();
398
399 self->Attach(runtime);
400
401 ClassLinker* class_linker = runtime->GetClassLinker();
402
403 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
404 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
405
406 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
407 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
408 if (thread_name != NULL) {
409 SetThreadName(thread_name->ToModifiedUtf8().c_str());
410 }
411
412 // Wait until it's safe to start running code. (There may have been a suspend-all
413 // in progress while we were starting up.)
414 runtime->GetThreadList()->WaitForGo();
415
416 // TODO: say "hi" to the debugger.
417 //if (gDvm.debuggerConnected) {
418 // dvmDbgPostThreadStart(self);
419 //}
420
421 // Invoke the 'run' method of our java.lang.Thread.
422 CHECK(self->peer_ != NULL);
423 Object* receiver = self->peer_;
424 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
425 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
426 m->Invoke(self, receiver, NULL, NULL);
427
428 // Detach.
429 runtime->GetThreadList()->Unregister();
430
Carl Shapirob5573532011-07-12 18:22:59 -0700431 return NULL;
432}
433
Elliott Hughes93e74e82011-09-13 11:07:03 -0700434void SetVmData(Object* managed_thread, Thread* native_thread) {
435 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
436
437 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
438 Class* int_class = class_linker->FindPrimitiveClass('I');
439
440 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
441
442 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
443}
444
Elliott Hughesd369bb72011-09-12 14:41:14 -0700445void Thread::Create(Object* peer, size_t stack_size) {
446 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700447
Elliott Hughesd369bb72011-09-12 14:41:14 -0700448 if (stack_size == 0) {
449 stack_size = Runtime::Current()->GetDefaultStackSize();
450 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700451
Elliott Hughes93e74e82011-09-13 11:07:03 -0700452 Thread* native_thread = new Thread;
453 native_thread->peer_ = peer;
454
455 // Thread.start is synchronized, so we know that vmData is 0,
456 // and know that we're not racing to assign it.
457 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700458
459 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700460 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
461 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
462 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
463 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
464 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700465
466 // Let the child know when it's safe to start running.
467 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700468}
469
Elliott Hughes93e74e82011-09-13 11:07:03 -0700470void Thread::Attach(const Runtime* runtime) {
471 InitCpu();
472 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700473
Elliott Hughes93e74e82011-09-13 11:07:03 -0700474 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700475
Elliott Hughes93e74e82011-09-13 11:07:03 -0700476 tid_ = ::art::GetTid();
477 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700478
Elliott Hughes93e74e82011-09-13 11:07:03 -0700479 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700480
Elliott Hughes8d768a92011-09-14 16:35:25 -0700481 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700482
Elliott Hughes93e74e82011-09-13 11:07:03 -0700483 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700484
Elliott Hughes93e74e82011-09-13 11:07:03 -0700485 runtime->GetThreadList()->Register(this);
486}
487
488Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
489 Thread* self = new Thread;
490 self->Attach(runtime);
491
492 self->SetState(Thread::kRunnable);
493
494 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700495
496 // If we're the main thread, ClassLinker won't be created until after we're attached,
497 // so that thread needs a two-stage attach. Regular threads don't need this hack.
498 if (self->thin_lock_id_ != ThreadList::kMainId) {
499 self->CreatePeer(name, as_daemon);
500 }
501
502 return self;
503}
504
Elliott Hughesd369bb72011-09-12 14:41:14 -0700505jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
506 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
507 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
508 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
509 // This will be null in the compiler (and tests), but never in a running system.
510 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
511 return thread_group;
512}
513
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700514void Thread::CreatePeer(const char* name, bool as_daemon) {
515 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
516
517 JNIEnv* env = jni_env_;
518
Elliott Hughesd369bb72011-09-12 14:41:14 -0700519 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
520 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700521 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700522 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700523 jboolean thread_is_daemon = as_daemon;
524
525 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700526 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700527
Elliott Hughes8daa0922011-09-11 13:46:25 -0700528 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700529
530 // Because we mostly run without code available (in the compiler, in tests), we
531 // manually assign the fields the constructor should have set.
532 // TODO: lose this.
533 jfieldID fid;
534 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
535 env->SetObjectField(peer, fid, thread_group);
536 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
537 env->SetObjectField(peer, fid, thread_name);
538 fid = env->GetFieldID(c, "priority", "I");
539 env->SetIntField(peer, fid, thread_priority);
540 fid = env->GetFieldID(c, "daemon", "Z");
541 env->SetBooleanField(peer, fid, thread_is_daemon);
542
543 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700544}
545
Elliott Hughesbe759c62011-09-08 19:38:21 -0700546void Thread::InitStackHwm() {
547 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700548 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700549
Elliott Hughesbe759c62011-09-08 19:38:21 -0700550 void* stack_base;
551 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700552 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700553
Elliott Hughesbe759c62011-09-08 19:38:21 -0700554 if (stack_size <= kStackOverflowReservedBytes) {
555 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
556 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700557
558 // stack_base is the "lowest addressable byte" of the stack.
559 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
560 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700561 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700562
563 // Sanity check.
564 int stack_variable;
565 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700566
Elliott Hughes8d768a92011-09-14 16:35:25 -0700567 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700568}
569
Elliott Hughesa0957642011-09-02 14:27:33 -0700570void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700571 DumpState(os);
572 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700573}
574
Elliott Hughesd92bec42011-09-02 17:04:36 -0700575std::string GetSchedulerGroup(pid_t tid) {
576 // /proc/<pid>/group looks like this:
577 // 2:devices:/
578 // 1:cpuacct,cpu:/
579 // We want the third field from the line whose second field contains the "cpu" token.
580 std::string cgroup_file;
581 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
582 return "";
583 }
584 std::vector<std::string> cgroup_lines;
585 Split(cgroup_file, '\n', cgroup_lines);
586 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
587 std::vector<std::string> cgroup_fields;
588 Split(cgroup_lines[i], ':', cgroup_fields);
589 std::vector<std::string> cgroups;
590 Split(cgroup_fields[1], ',', cgroups);
591 for (size_t i = 0; i < cgroups.size(); ++i) {
592 if (cgroups[i] == "cpu") {
593 return cgroup_fields[2].substr(1); // Skip the leading slash.
594 }
595 }
596 }
597 return "";
598}
599
600void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700601 std::string thread_name("<native thread without managed peer>");
602 std::string group_name;
603 int priority;
604 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700605
Elliott Hughesd369bb72011-09-12 14:41:14 -0700606 if (peer_ != NULL) {
607 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
608
609 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
610 Class* int_class = class_linker->FindPrimitiveClass('I');
611 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
612 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
613 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
614
615 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
616 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
617 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
618 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
619
620 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
621 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
622 priority = priority_field->GetInt(peer_);
623 is_daemon = daemon_field->GetBoolean(peer_);
624
625 Object* thread_group = thread_group_field->GetObject(peer_);
626 if (thread_group != NULL) {
627 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
628 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
629 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
630 }
631 } else {
632 // 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 -0700633 std::string stats;
634 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
635 size_t start = stats.find('(') + 1;
636 size_t end = stats.find(')') - start;
637 thread_name = stats.substr(start, end);
638 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700639 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700640 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700641
642 int policy;
643 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700644 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700645
646 std::string scheduler_group(GetSchedulerGroup(GetTid()));
647 if (scheduler_group.empty()) {
648 scheduler_group = "default";
649 }
650
Elliott Hughesd92bec42011-09-02 17:04:36 -0700651 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700652 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700653 os << " daemon";
654 }
655 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700656 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700657 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700658
Elliott Hughesd92bec42011-09-02 17:04:36 -0700659 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700660 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700661 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700662 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700663 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700664 << " self=" << reinterpret_cast<const void*>(this) << "\n";
665 os << " | sysTid=" << GetTid()
666 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
667 << " sched=" << policy << "/" << sp.sched_priority
668 << " cgrp=" << scheduler_group
669 << " handle=" << GetImpl() << "\n";
670
671 // Grab the scheduler stats for this thread.
672 std::string scheduler_stats;
673 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
674 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
675 } else {
676 scheduler_stats = "0 0 0";
677 }
678
679 int utime = 0;
680 int stime = 0;
681 int task_cpu = 0;
682 std::string stats;
683 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
684 // Skip the command, which may contain spaces.
685 stats = stats.substr(stats.find(')') + 2);
686 // Extract the three fields we care about.
687 std::vector<std::string> fields;
688 Split(stats, ' ', fields);
689 utime = strtoull(fields[11].c_str(), NULL, 10);
690 stime = strtoull(fields[12].c_str(), NULL, 10);
691 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
692 }
693
694 os << " | schedstat=( " << scheduler_stats << " )"
695 << " utm=" << utime
696 << " stm=" << stime
697 << " core=" << task_cpu
698 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
699}
700
Elliott Hughesd369bb72011-09-12 14:41:14 -0700701struct StackDumpVisitor : public Thread::StackVisitor {
702 StackDumpVisitor(std::ostream& os) : os(os) {
703 }
704
Ian Rogersbdb03912011-09-14 00:55:44 -0700705 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700706 }
707
Ian Rogersbdb03912011-09-14 00:55:44 -0700708 void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700709 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
710
711 Method* m = frame.GetMethod();
712 Class* c = m->GetDeclaringClass();
713 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
714
715 os << " at " << PrettyMethod(m, false);
716 if (m->IsNative()) {
717 os << "(Native method)";
718 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700719 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700720 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
721 }
722 os << "\n";
723 }
724
725 std::ostream& os;
726};
727
Elliott Hughesd92bec42011-09-02 17:04:36 -0700728void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700729 StackDumpVisitor dumper(os);
730 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700731}
732
Elliott Hughes8d768a92011-09-14 16:35:25 -0700733Thread::State Thread::SetState(Thread::State new_state) {
734 Thread::State old_state = state_;
735 if (old_state == new_state) {
736 return old_state;
737 }
738
739 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
740 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
741
742 if (new_state == Thread::kRunnable) {
743 /*
744 * Change our status to Thread::kRunnable. The transition requires
745 * that we check for pending suspension, because the VM considers
746 * us to be "asleep" in all other states, and another thread could
747 * be performing a GC now.
748 *
749 * The order of operations is very significant here. One way to
750 * do this wrong is:
751 *
752 * GCing thread Our thread (in kNative)
753 * ------------ ----------------------
754 * check suspend count (== 0)
755 * SuspendAllThreads()
756 * grab suspend-count lock
757 * increment all suspend counts
758 * release suspend-count lock
759 * check thread state (== kNative)
760 * all are suspended, begin GC
761 * set state to kRunnable
762 * (continue executing)
763 *
764 * We can correct this by grabbing the suspend-count lock and
765 * performing both of our operations (check suspend count, set
766 * state) while holding it, now we need to grab a mutex on every
767 * transition to kRunnable.
768 *
769 * What we do instead is change the order of operations so that
770 * the transition to kRunnable happens first. If we then detect
771 * that the suspend count is nonzero, we switch to kSuspended.
772 *
773 * Appropriate compiler and memory barriers are required to ensure
774 * that the operations are observed in the expected order.
775 *
776 * This does create a small window of opportunity where a GC in
777 * progress could observe what appears to be a running thread (if
778 * it happens to look between when we set to kRunnable and when we
779 * switch to kSuspended). At worst this only affects assertions
780 * and thread logging. (We could work around it with some sort
781 * of intermediate "pre-running" state that is generally treated
782 * as equivalent to running, but that doesn't seem worthwhile.)
783 *
784 * We can also solve this by combining the "status" and "suspend
785 * count" fields into a single 32-bit value. This trades the
786 * store/load barrier on transition to kRunnable for an atomic RMW
787 * op on all transitions and all suspend count updates (also, all
788 * accesses to status or the thread count require bit-fiddling).
789 * It also eliminates the brief transition through kRunnable when
790 * the thread is supposed to be suspended. This is possibly faster
791 * on SMP and slightly more correct, but less convenient.
792 */
793 android_atomic_acquire_store(new_state, addr);
794 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
795 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
796 }
797 } else {
798 /*
799 * Not changing to Thread::kRunnable. No additional work required.
800 *
801 * We use a releasing store to ensure that, if we were runnable,
802 * any updates we previously made to objects on the managed heap
803 * will be observed before the state change.
804 */
805 android_atomic_release_store(new_state, addr);
806 }
807
808 return old_state;
809}
810
811void Thread::WaitUntilSuspended() {
812 // TODO: dalvik dropped the waiting thread's priority after a while.
813 // TODO: dalvik timed out and aborted.
814 useconds_t delay = 0;
815 while (GetState() == Thread::kRunnable) {
816 useconds_t new_delay = delay * 2;
817 CHECK_GE(new_delay, delay);
818 delay = new_delay;
819 if (delay == 0) {
820 sched_yield();
821 delay = 10000;
822 } else {
823 usleep(delay);
824 }
825 }
826}
827
Elliott Hughesbe759c62011-09-08 19:38:21 -0700828void Thread::ThreadExitCallback(void* arg) {
829 Thread* self = reinterpret_cast<Thread*>(arg);
830 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700831}
832
Elliott Hughesbe759c62011-09-08 19:38:21 -0700833void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700834 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700835 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700836
837 // Double-check the TLS slot allocation.
838 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700839 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700840 }
841
842 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700843}
844
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700845void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700846 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700847}
848
Elliott Hughesdcc24742011-09-07 14:02:44 -0700849Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700850 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700851 wait_mutex_(new Mutex("Thread wait mutex")),
852 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700853 wait_monitor_(NULL),
854 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700855 wait_next_(NULL),
856 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700857 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700858 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700859 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700860 native_to_managed_record_(NULL),
861 top_sirt_(NULL),
862 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700863 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700864 self_(NULL),
865 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700866 exception_(NULL),
867 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700868 class_loader_override_(NULL),
869 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700870}
871
Elliott Hughes02b48d12011-09-07 17:15:51 -0700872void MonitorExitVisitor(const Object* object, void*) {
873 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700874 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700875}
876
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700877Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700878 // TODO: check we're not calling the JNI DetachCurrentThread function from
879 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
880
881 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700882 if (jni_env_ != NULL) {
883 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
884 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700885
886 if (IsExceptionPending()) {
887 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
888 }
889
890 // TODO: ThreadGroup.removeThread(this);
891
Elliott Hughes93e74e82011-09-13 11:07:03 -0700892 if (peer_ != NULL) {
893 SetVmData(peer_, NULL);
894 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700895
896 // TODO: say "bye" to the debugger.
897 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700898 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700899 //}
900
901 // Thread.join() is implemented as an Object.wait() on the Thread.lock
902 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700903 if (peer_ != NULL) {
904 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
905 Class* java_lang_Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
906 Class* java_lang_ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
907 Field* lock_field = java_lang_Thread_class->FindDeclaredInstanceField("lock", java_lang_ThreadLock_class);
908
909 Thread* self = Thread::Current();
910 Object* lock = lock_field->GetObject(peer_);
911 // This conditional is only needed for tests, where Thread.lock won't have been set.
912 if (lock != NULL) {
913 lock->MonitorEnter(self);
914 lock->NotifyAll();
915 lock->MonitorExit(self);
916 }
917 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700918
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700919 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700920 jni_env_ = NULL;
921
922 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700923
924 delete wait_cond_;
925 delete wait_mutex_;
926
927 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700928}
929
Ian Rogers408f79a2011-08-23 18:22:33 -0700930size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700931 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700932 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700933 count += cur->NumberOfReferences();
934 }
935 return count;
936}
937
Ian Rogers408f79a2011-08-23 18:22:33 -0700938bool Thread::SirtContains(jobject obj) {
939 Object** sirt_entry = reinterpret_cast<Object**>(obj);
940 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700941 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700942 // A SIRT should always have a jobject/jclass as a native method is passed
943 // in a this pointer or a class
944 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700945 if ((&cur->References()[0] <= sirt_entry) &&
946 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700947 return true;
948 }
949 }
950 return false;
951}
952
Ian Rogers67375ac2011-09-14 00:55:44 -0700953void Thread::PopSirt() {
954 CHECK(top_sirt_ != NULL);
955 top_sirt_ = top_sirt_->Link();
956}
957
Ian Rogers408f79a2011-08-23 18:22:33 -0700958Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700959 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700960 if (obj == NULL) {
961 return NULL;
962 }
963 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
964 IndirectRefKind kind = GetIndirectRefKind(ref);
965 Object* result;
966 switch (kind) {
967 case kLocal:
968 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700969 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700970 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700971 break;
972 }
973 case kGlobal:
974 {
975 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
976 IndirectReferenceTable& globals = vm->globals;
977 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700978 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700979 break;
980 }
981 case kWeakGlobal:
982 {
983 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
984 IndirectReferenceTable& weak_globals = vm->weak_globals;
985 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700986 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700987 if (result == kClearedJniWeakGlobal) {
988 // This is a special case where it's okay to return NULL.
989 return NULL;
990 }
991 break;
992 }
993 case kSirtOrInvalid:
994 default:
995 // TODO: make stack indirect reference table lookup more efficient
996 // Check if this is a local reference in the SIRT
997 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700998 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700999 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001000 // Assume an invalid local reference is actually a direct pointer.
1001 result = reinterpret_cast<Object*>(obj);
1002 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001003 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001004 }
1005 }
1006
1007 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001008 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1009 JniAbort(NULL);
1010 } else {
1011 if (result != kInvalidIndirectRefObject) {
1012 Heap::VerifyObject(result);
1013 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001014 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001015 return result;
1016}
1017
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001018class CountStackDepthVisitor : public Thread::StackVisitor {
1019 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001020 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001021
Ian Rogersbdb03912011-09-14 00:55:44 -07001022 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001023 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001024 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001025
1026 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001027 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001028 }
1029
1030 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001031 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001032};
1033
Ian Rogersaaa20802011-09-11 21:47:37 -07001034//
1035class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001036 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001037 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1038 // Allocate method trace with an extra slot that will hold the PC trace
1039 method_trace_ = Runtime::Current()->GetClassLinker()->
1040 AllocObjectArray<Object>(depth + 1);
1041 // Register a local reference as IntArray::Alloc may trigger GC
1042 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1043 pc_trace_ = IntArray::Alloc(depth);
1044#ifdef MOVING_GARBAGE_COLLECTOR
1045 // Re-read after potential GC
1046 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1047#endif
1048 // Save PC trace in last element of method trace, also places it into the
1049 // object graph.
1050 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001051 }
1052
Ian Rogersaaa20802011-09-11 21:47:37 -07001053 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001054
Ian Rogersbdb03912011-09-14 00:55:44 -07001055 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001056 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001057 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001058 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001059 }
1060
Ian Rogersaaa20802011-09-11 21:47:37 -07001061 jobject GetInternalStackTrace() const {
1062 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001063 }
1064
1065 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001066 // Current position down stack trace
1067 uint32_t count_;
1068 // Array of return PC values
1069 IntArray* pc_trace_;
1070 // An array of the methods on the stack, the last entry is a reference to the
1071 // PC trace
1072 ObjectArray<Object>* method_trace_;
1073 // Local indirect reference table entry for method trace
1074 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001075};
1076
Ian Rogersaaa20802011-09-11 21:47:37 -07001077void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001078 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001079 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001080 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1081 // CHECK(native_to_managed_record_ != NULL);
1082 NativeToManagedRecord* record = native_to_managed_record_;
1083
Ian Rogersbdb03912011-09-14 00:55:44 -07001084 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001085 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001086 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1087 visitor->VisitFrame(frame, pc);
1088 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001089 }
1090 if (record == NULL) {
1091 break;
1092 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001093 // last_tos should return Frame instead of sp?
1094 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1095 pc = record->last_top_of_managed_stack_pc_;
1096 record = record->link_;
1097 }
1098}
1099
Ian Rogers67375ac2011-09-14 00:55:44 -07001100void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001101 Frame frame = GetTopOfStack();
1102 uintptr_t pc = top_of_managed_stack_pc_;
1103
1104 if (frame.GetSP() != 0) {
1105 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001106 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001107 visitor->VisitFrame(frame, pc);
1108 pc = frame.GetReturnPC();
1109 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001110 if (include_upcall) {
1111 visitor->VisitFrame(frame, pc);
1112 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001113 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001114}
1115
Ian Rogersaaa20802011-09-11 21:47:37 -07001116jobject Thread::CreateInternalStackTrace() const {
1117 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001118 CountStackDepthVisitor count_visitor;
1119 WalkStack(&count_visitor);
1120 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001121
Ian Rogersaaa20802011-09-11 21:47:37 -07001122 // Transition into runnable state to work on Object*/Array*
1123 ScopedJniThreadState ts(jni_env_);
1124
1125 // Build internal stack trace
1126 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001127 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001128
Ian Rogersaaa20802011-09-11 21:47:37 -07001129 return build_trace_visitor.GetInternalStackTrace();
1130}
1131
1132jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1133 JNIEnv* env) {
1134 // Transition into runnable state to work on Object*/Array*
1135 ScopedJniThreadState ts(env);
1136
1137 // Decode the internal stack trace into the depth, method trace and PC trace
1138 ObjectArray<Object>* method_trace =
1139 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1140 int32_t depth = method_trace->GetLength()-1;
1141 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1142
1143 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1144
1145 // Create java_trace array and place in local reference table
1146 ObjectArray<StackTraceElement>* java_traces =
1147 class_linker->AllocStackTraceElementArray(depth);
1148 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001149
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001150 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001151 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1152 Method* method = down_cast<Method*>(method_trace->Get(i));
1153 uint32_t native_pc = pc_trace->Get(i);
1154 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001155 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001156 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001157
Ian Rogersaaa20802011-09-11 21:47:37 -07001158 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001159 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001160 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001161 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001162 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001163 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001164 method->ToDexPC(native_pc)));
1165#ifdef MOVING_GARBAGE_COLLECTOR
1166 // Re-read after potential GC
1167 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1168 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1169 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1170#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001171 java_traces->Set(i, obj);
1172 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001173 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001174}
1175
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001176void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001177 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001178 va_list args;
1179 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001180 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001181 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001182
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001183 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001184 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001185 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001186 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001187 descriptor.erase(descriptor.length() - 1);
1188
1189 JNIEnv* env = GetJniEnv();
1190 jclass exception_class = env->FindClass(descriptor.c_str());
1191 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1192 int rc = env->ThrowNew(exception_class, msg.c_str());
1193 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001194}
1195
Elliott Hughes79082e32011-08-25 12:07:32 -07001196void Thread::ThrowOutOfMemoryError() {
1197 UNIMPLEMENTED(FATAL);
1198}
1199
Ian Rogersbdb03912011-09-14 00:55:44 -07001200Method* Thread::CalleeSaveMethod() const {
1201 // TODO: we should only allocate this once
Ian Rogersbdb03912011-09-14 00:55:44 -07001202 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001203#if defined(__arm__)
Ian Rogersbdb03912011-09-14 00:55:44 -07001204 method->SetCode(NULL, art::kThumb2, NULL);
1205 method->SetFrameSizeInBytes(64);
1206 method->SetReturnPcOffsetInBytes(60);
Ian Rogers67375ac2011-09-14 00:55:44 -07001207 method->SetCoreSpillMask((1 << art::arm::R1) |
1208 (1 << art::arm::R2) |
1209 (1 << art::arm::R3) |
1210 (1 << art::arm::R4) |
1211 (1 << art::arm::R5) |
1212 (1 << art::arm::R6) |
1213 (1 << art::arm::R7) |
1214 (1 << art::arm::R8) |
1215 (1 << art::arm::R9) |
1216 (1 << art::arm::R10) |
1217 (1 << art::arm::R11) |
1218 (1 << art::arm::LR));
Ian Rogersbdb03912011-09-14 00:55:44 -07001219 method->SetFpSpillMask(0);
Ian Rogers67375ac2011-09-14 00:55:44 -07001220#elif defined(__i386__)
1221 method->SetCode(NULL, art::kX86, NULL);
1222 method->SetFrameSizeInBytes(32);
1223 method->SetReturnPcOffsetInBytes(28);
1224 method->SetCoreSpillMask((1 << art::x86::EBX) |
1225 (1 << art::x86::EBP) |
1226 (1 << art::x86::ESI) |
1227 (1 << art::x86::EDI));
1228 method->SetFpSpillMask(0);
1229#else
1230 UNIMPLEMENTED(FATAL);
1231#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001232 return method;
1233}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001234
Ian Rogersbdb03912011-09-14 00:55:44 -07001235class CatchBlockStackVisitor : public Thread::StackVisitor {
1236 public:
1237 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001238 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1239#ifndef NDEBUG
1240 handler_pc_ = 0xEBADC0DE;
1241 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1242#endif
1243 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001244
Ian Rogersbdb03912011-09-14 00:55:44 -07001245 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1246 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001247 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001248 if (method == NULL) {
1249 // This is the upcall, we remember the frame and last_pc so that we may
1250 // long jump to them
1251 handler_pc_ = pc;
1252 handler_frame_ = fr;
1253 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001254 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001255 uint32_t dex_pc = DexFile::kDexNoIndex;
1256 if (pc > 0) {
1257 if (method->IsNative()) {
1258 native_method_count_++;
1259 } else {
1260 // Move the PC back 2 bytes as a call will frequently terminate the
1261 // decoding of a particular instruction and we want to make sure we
1262 // get the Dex PC of the instruction with the call and not the
1263 // instruction following.
1264 pc -= 2;
1265 dex_pc = method->ToDexPC(pc);
1266 }
1267 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001268 if (dex_pc != DexFile::kDexNoIndex) {
1269 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1270 if (found_dex_pc != DexFile::kDexNoIndex) {
1271 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001272 handler_pc_ = method->ToNativePC(found_dex_pc);
1273 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001274 }
1275 }
1276 if (!found_) {
1277 // Caller may be handler, fill in callee saves in context
1278 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001279 }
1280 }
1281 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001282
1283 // Did we find a catch block yet?
1284 bool found_;
1285 // The type of the exception catch block to find
1286 Class* to_find_;
1287 // Frame with found handler or last frame if no handler found
1288 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001289 // PC to branch to for the handler
1290 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001291 // Context that will be the target of the long jump
1292 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001293 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1294 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001295};
1296
1297void Thread::DeliverException(Throwable* exception) {
1298 SetException(exception); // Set exception on thread
1299
1300 Context* long_jump_context = GetLongJumpContext();
1301 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001302 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001303
Ian Rogers67375ac2011-09-14 00:55:44 -07001304 // Pop any SIRT
1305 if (catch_finder.native_method_count_ == 1) {
1306 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001307 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001308 // We only expect the stack crawl to have passed 1 native method as it's terminated
1309 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001310 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001311 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001312 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1313 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001314 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001315}
1316
Ian Rogersbdb03912011-09-14 00:55:44 -07001317Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001318 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001319 if (result == NULL) {
1320 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001321 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001322 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001323 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001324}
1325
Elliott Hughes5f791332011-09-15 17:45:30 -07001326bool Thread::HoldsLock(Object* object) {
1327 if (object == NULL) {
1328 return false;
1329 }
1330 return object->GetLockOwner() == thin_lock_id_;
1331}
1332
Elliott Hughes410c0c82011-09-01 17:58:25 -07001333void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001334 if (exception_ != NULL) {
1335 visitor(exception_, arg);
1336 }
1337 if (peer_ != NULL) {
1338 visitor(peer_, arg);
1339 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001340 jni_env_->locals.VisitRoots(visitor, arg);
1341 jni_env_->monitors.VisitRoots(visitor, arg);
1342 // visitThreadStack(visitor, thread, arg);
1343 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1344}
1345
Ian Rogersb033c752011-07-20 12:22:35 -07001346static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001347 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001348 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001349 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001350 "Blocked",
1351 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001352 "Initializing",
1353 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001354 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001355 "VmWait",
1356 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001357};
1358std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001359 int int_state = static_cast<int>(state);
1360 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1361 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001362 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001363 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001364 }
1365 return os;
1366}
1367
Elliott Hughes330304d2011-08-12 14:28:05 -07001368std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1369 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001370 << ",pthread_t=" << thread.GetImpl()
1371 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001372 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001373 << ",state=" << thread.GetState()
1374 << ",peer=" << thread.GetPeer()
1375 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001376 return os;
1377}
1378
Elliott Hughes8daa0922011-09-11 13:46:25 -07001379} // namespace art