blob: 49c960552acd5f0c5926adefb1bd445801f31b02 [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
55extern "C" void artThrowExceptionHelper(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 Rogersbdb03912011-09-14 00:55:44 -070065 *sp = thread->CalleeSaveMethod();
66 thread->SetTopOfStack(sp, 0);
67 thread->DeliverException(exception);
buzbee1b4c8592011-08-31 10:43:51 -070068}
69
Ian Rogersbdb03912011-09-14 00:55:44 -070070namespace art {
71
buzbee1b4c8592011-08-31 10:43:51 -070072// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070073Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070074 /*
75 * Should initialize & fix up method->dex_cache_resolved_types_[].
76 * Returns initialized type. Does not return normally if an exception
77 * is thrown, but instead initiates the catch. Should be similar to
78 * ClassLinker::InitializeStaticStorageFromCode.
79 */
80 UNIMPLEMENTED(FATAL);
81 return NULL;
82}
83
buzbee561227c2011-09-02 15:28:19 -070084// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -070085void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -070086 /*
87 * Slow-path handler on invoke virtual method path in which
88 * base method is unresolved at compile-time. Doesn't need to
89 * return anything - just either ensure that
90 * method->dex_cache_resolved_methods_(method_idx) != NULL or
91 * throw and unwind. The caller will restart call sequence
92 * from the beginning.
93 */
94}
95
buzbee1da522d2011-09-04 11:22:20 -070096// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -070097Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -070098 /*
99 * Just a wrapper around Array::AllocFromCode() that additionally
100 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
101 */
102 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
103 return Array::AllocFromCode(type_index, method, component_count);
104}
105
buzbee2a475e72011-09-07 17:19:17 -0700106// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700107void CheckCastFromCode(const Class* a, const Class* b) {
buzbee2a475e72011-09-07 17:19:17 -0700108 if (a->IsAssignableFrom(b)) {
109 return;
110 }
111 UNIMPLEMENTED(FATAL);
112}
113
Elliott Hughesd369bb72011-09-12 14:41:14 -0700114void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700115 // TODO: throw and unwind if lock not held
116 // TODO: throw and unwind on NPE
117 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700118}
119
Elliott Hughesd369bb72011-09-12 14:41:14 -0700120void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700121 obj->MonitorEnter(thread);
122 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700123}
124
Elliott Hughesd369bb72011-09-12 14:41:14 -0700125void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700126 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700127}
128
buzbeecefd1872011-09-09 09:59:52 -0700129// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700130void StackOverflowFromCode(Method* method) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700131 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700132 //NOTE: to save code space, this handler needs to look up its own Thread*
133 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700134}
135
buzbee5ade1d22011-09-09 14:44:52 -0700136// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700137void ThrowNullPointerFromCode() {
138 Thread::Current()->Dump(std::cerr);
139 //NOTE: to save code space, this handler must look up caller's Method*
140 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700141}
142
143// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700144void ThrowDivZeroFromCode() {
145 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700146}
147
148// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700149void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
150 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700151}
152
153// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700154void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700155 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
156 " ref: " << ref;
157}
158
159// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700160void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700161 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
162}
163
164// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700165void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700166 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
167}
168
169// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700170void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700171 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
172}
173
174// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700175void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700176 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
177}
178
Ian Rogersbdb03912011-09-14 00:55:44 -0700179void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread) {
180 thread->ThrowNewException("Ljava/lang/AbstractMethodError",
181 "abstract method \"%s\"",
182 PrettyMethod(method).c_str());
183 thread->DeliverException(thread->GetException());
184}
185
186
buzbee5ade1d22011-09-09 14:44:52 -0700187/*
188 * Temporary placeholder. Should include run-time checks for size
189 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
190 * As with other new "FromCode" routines, this should return to the caller
191 * only if no exception has been thrown.
192 *
193 * NOTE: When dealing with a raw dex file, the data to be copied uses
194 * little-endian ordering. Require that oat2dex do any required swapping
195 * so this routine can get by with a memcpy().
196 *
197 * Format of the data:
198 * ushort ident = 0x0300 magic value
199 * ushort width width of each element in the table
200 * uint size number of elements in the table
201 * ubyte data[size*width] table of data values (may contain a single-byte
202 * padding at the end)
203 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700204void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700205 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
206 uint32_t size_in_bytes = size * table[1];
207 if (static_cast<int32_t>(size) > array->GetLength()) {
208 ThrowArrayBoundsFromCode(array->GetLength(), size);
209 }
210 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
211 (char*)&table[4], size_in_bytes);
212}
213
Brian Carlstrom16192862011-09-12 17:50:06 -0700214/*
215 * TODO: placeholder for a method that can be called by the
216 * invoke-interface trampoline to unwind and handle exception. The
217 * trampoline will arrange it so that the caller appears to be the
218 * callsite of the failed invoke-interface. See comments in
219 * runtime_support.S
220 */
221extern "C" void artFailedInvokeInterface() {
222 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
223}
224
225// See comments in runtime_support.S
226extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
227 Object* this_object , Method* caller_method)
228{
229 if (this_object == NULL) {
230 ThrowNullPointerFromCode();
231 }
232 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
233 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
234 if (interface_method == NULL) {
235 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
236 }
237 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
238 const void* code = method->GetCode();
239
240 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
241 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
242 uint64_t result = ((code_uint << 32) | method_uint);
243 return result;
244}
245
buzbee5ade1d22011-09-09 14:44:52 -0700246// TODO: move to more appropriate location
247/*
248 * Float/double conversion requires clamping to min and max of integer form. If
249 * target doesn't support this normally, use these.
250 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700251int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700252 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
253 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
254 if (d >= kMaxLong)
255 return (int64_t)0x7fffffffffffffffULL;
256 else if (d <= kMinLong)
257 return (int64_t)0x8000000000000000ULL;
258 else if (d != d) // NaN case
259 return 0;
260 else
261 return (int64_t)d;
262}
263
Elliott Hughesd369bb72011-09-12 14:41:14 -0700264int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700265 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
266 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
267 if (f >= kMaxLong)
268 return (int64_t)0x7fffffffffffffffULL;
269 else if (f <= kMinLong)
270 return (int64_t)0x8000000000000000ULL;
271 else if (f != f) // NaN case
272 return 0;
273 else
274 return (int64_t)f;
275}
276
Brian Carlstrom16192862011-09-12 17:50:06 -0700277// Return value helper for jobject return types
278static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
279 return thread->DecodeJObject(obj);
280}
281
buzbee3ea4ec52011-08-22 17:37:19 -0700282void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700283#if defined(__arm__)
284 pShlLong = art_shl_long;
285 pShrLong = art_shr_long;
286 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700287 pIdiv = __aeabi_idiv;
288 pIdivmod = __aeabi_idivmod;
289 pI2f = __aeabi_i2f;
290 pF2iz = __aeabi_f2iz;
291 pD2f = __aeabi_d2f;
292 pF2d = __aeabi_f2d;
293 pD2iz = __aeabi_d2iz;
294 pL2f = __aeabi_l2f;
295 pL2d = __aeabi_l2d;
296 pFadd = __aeabi_fadd;
297 pFsub = __aeabi_fsub;
298 pFdiv = __aeabi_fdiv;
299 pFmul = __aeabi_fmul;
300 pFmodf = fmodf;
301 pDadd = __aeabi_dadd;
302 pDsub = __aeabi_dsub;
303 pDdiv = __aeabi_ddiv;
304 pDmul = __aeabi_dmul;
305 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700306 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700307 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700308 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogersbdb03912011-09-14 00:55:44 -0700309 pThrowException = art_throw_exception;
buzbee54330722011-08-23 16:46:55 -0700310#endif
buzbeec396efc2011-09-11 09:36:41 -0700311 pF2l = F2L;
312 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700313 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700314 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700315 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700316 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700317 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700318 pGet32Static = Field::Get32StaticFromCode;
319 pSet32Static = Field::Set32StaticFromCode;
320 pGet64Static = Field::Get64StaticFromCode;
321 pSet64Static = Field::Set64StaticFromCode;
322 pGetObjStatic = Field::GetObjStaticFromCode;
323 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700324 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700325 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700326 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700327 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700328 pInstanceofNonTrivialFromCode = Object::InstanceOf;
329 pCheckCastFromCode = CheckCastFromCode;
330 pLockObjectFromCode = LockObjectFromCode;
331 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700332 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700333 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700334 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700335 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
336 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
337 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
338 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
339 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
340 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
341 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
342 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700343 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700344 pFindNativeMethod = FindNativeMethod;
345 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700346 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700347}
348
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700349void Frame::Next() {
350 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700351 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700353}
354
Ian Rogersbdb03912011-09-14 00:55:44 -0700355uintptr_t Frame::GetReturnPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700356 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700357 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700358 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700359}
360
Ian Rogersbdb03912011-09-14 00:55:44 -0700361uintptr_t Frame::LoadCalleeSave(int num) const {
362 // Callee saves are held at the top of the frame
363 Method* method = GetMethod();
364 DCHECK(method != NULL);
365 size_t frame_size = method->GetFrameSizeInBytes();
366 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size -
367 ((num + 1) * kPointerSize);
368 return *reinterpret_cast<uintptr_t*>(save_addr);
369}
370
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700372 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700373 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700375}
376
Brian Carlstrom78128a62011-09-15 17:21:19 -0700377void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700378 Thread* self = reinterpret_cast<Thread*>(arg);
379 Runtime* runtime = Runtime::Current();
380
381 self->Attach(runtime);
382
383 ClassLinker* class_linker = runtime->GetClassLinker();
384
385 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
386 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
387
388 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
389 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
390 if (thread_name != NULL) {
391 SetThreadName(thread_name->ToModifiedUtf8().c_str());
392 }
393
394 // Wait until it's safe to start running code. (There may have been a suspend-all
395 // in progress while we were starting up.)
396 runtime->GetThreadList()->WaitForGo();
397
398 // TODO: say "hi" to the debugger.
399 //if (gDvm.debuggerConnected) {
400 // dvmDbgPostThreadStart(self);
401 //}
402
403 // Invoke the 'run' method of our java.lang.Thread.
404 CHECK(self->peer_ != NULL);
405 Object* receiver = self->peer_;
406 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
407 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
408 m->Invoke(self, receiver, NULL, NULL);
409
410 // Detach.
411 runtime->GetThreadList()->Unregister();
412
Carl Shapirob5573532011-07-12 18:22:59 -0700413 return NULL;
414}
415
Elliott Hughes93e74e82011-09-13 11:07:03 -0700416void SetVmData(Object* managed_thread, Thread* native_thread) {
417 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
418
419 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
420 Class* int_class = class_linker->FindPrimitiveClass('I');
421
422 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
423
424 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
425}
426
Elliott Hughesd369bb72011-09-12 14:41:14 -0700427void Thread::Create(Object* peer, size_t stack_size) {
428 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700429
Elliott Hughesd369bb72011-09-12 14:41:14 -0700430 if (stack_size == 0) {
431 stack_size = Runtime::Current()->GetDefaultStackSize();
432 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700433
Elliott Hughes93e74e82011-09-13 11:07:03 -0700434 Thread* native_thread = new Thread;
435 native_thread->peer_ = peer;
436
437 // Thread.start is synchronized, so we know that vmData is 0,
438 // and know that we're not racing to assign it.
439 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700440
441 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700442 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
443 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
444 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
445 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
446 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700447
448 // Let the child know when it's safe to start running.
449 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700450}
451
Elliott Hughes93e74e82011-09-13 11:07:03 -0700452void Thread::Attach(const Runtime* runtime) {
453 InitCpu();
454 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700455
Elliott Hughes93e74e82011-09-13 11:07:03 -0700456 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700457
Elliott Hughes93e74e82011-09-13 11:07:03 -0700458 tid_ = ::art::GetTid();
459 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700460
Elliott Hughes93e74e82011-09-13 11:07:03 -0700461 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700462
Elliott Hughes8d768a92011-09-14 16:35:25 -0700463 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700464
Elliott Hughes93e74e82011-09-13 11:07:03 -0700465 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700466
Elliott Hughes93e74e82011-09-13 11:07:03 -0700467 runtime->GetThreadList()->Register(this);
468}
469
470Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
471 Thread* self = new Thread;
472 self->Attach(runtime);
473
474 self->SetState(Thread::kRunnable);
475
476 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700477
478 // If we're the main thread, ClassLinker won't be created until after we're attached,
479 // so that thread needs a two-stage attach. Regular threads don't need this hack.
480 if (self->thin_lock_id_ != ThreadList::kMainId) {
481 self->CreatePeer(name, as_daemon);
482 }
483
484 return self;
485}
486
Elliott Hughesd369bb72011-09-12 14:41:14 -0700487jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
488 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
489 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
490 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
491 // This will be null in the compiler (and tests), but never in a running system.
492 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
493 return thread_group;
494}
495
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700496void Thread::CreatePeer(const char* name, bool as_daemon) {
497 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
498
499 JNIEnv* env = jni_env_;
500
Elliott Hughesd369bb72011-09-12 14:41:14 -0700501 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
502 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700503 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700504 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700505 jboolean thread_is_daemon = as_daemon;
506
507 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700508 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700509
Elliott Hughes8daa0922011-09-11 13:46:25 -0700510 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700511
512 // Because we mostly run without code available (in the compiler, in tests), we
513 // manually assign the fields the constructor should have set.
514 // TODO: lose this.
515 jfieldID fid;
516 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
517 env->SetObjectField(peer, fid, thread_group);
518 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
519 env->SetObjectField(peer, fid, thread_name);
520 fid = env->GetFieldID(c, "priority", "I");
521 env->SetIntField(peer, fid, thread_priority);
522 fid = env->GetFieldID(c, "daemon", "Z");
523 env->SetBooleanField(peer, fid, thread_is_daemon);
524
525 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700526}
527
Elliott Hughesbe759c62011-09-08 19:38:21 -0700528void Thread::InitStackHwm() {
529 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700530 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700531
Elliott Hughesbe759c62011-09-08 19:38:21 -0700532 void* stack_base;
533 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700534 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700535
Elliott Hughesbe759c62011-09-08 19:38:21 -0700536 if (stack_size <= kStackOverflowReservedBytes) {
537 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
538 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700539
540 // stack_base is the "lowest addressable byte" of the stack.
541 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
542 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700543 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700544
545 // Sanity check.
546 int stack_variable;
547 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700548
Elliott Hughes8d768a92011-09-14 16:35:25 -0700549 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700550}
551
Elliott Hughesa0957642011-09-02 14:27:33 -0700552void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700553 DumpState(os);
554 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700555}
556
Elliott Hughesd92bec42011-09-02 17:04:36 -0700557std::string GetSchedulerGroup(pid_t tid) {
558 // /proc/<pid>/group looks like this:
559 // 2:devices:/
560 // 1:cpuacct,cpu:/
561 // We want the third field from the line whose second field contains the "cpu" token.
562 std::string cgroup_file;
563 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
564 return "";
565 }
566 std::vector<std::string> cgroup_lines;
567 Split(cgroup_file, '\n', cgroup_lines);
568 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
569 std::vector<std::string> cgroup_fields;
570 Split(cgroup_lines[i], ':', cgroup_fields);
571 std::vector<std::string> cgroups;
572 Split(cgroup_fields[1], ',', cgroups);
573 for (size_t i = 0; i < cgroups.size(); ++i) {
574 if (cgroups[i] == "cpu") {
575 return cgroup_fields[2].substr(1); // Skip the leading slash.
576 }
577 }
578 }
579 return "";
580}
581
582void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700583 std::string thread_name("<native thread without managed peer>");
584 std::string group_name;
585 int priority;
586 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700587
Elliott Hughesd369bb72011-09-12 14:41:14 -0700588 if (peer_ != NULL) {
589 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
590
591 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
592 Class* int_class = class_linker->FindPrimitiveClass('I');
593 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
594 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
595 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
596
597 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
598 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
599 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
600 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
601
602 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
603 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
604 priority = priority_field->GetInt(peer_);
605 is_daemon = daemon_field->GetBoolean(peer_);
606
607 Object* thread_group = thread_group_field->GetObject(peer_);
608 if (thread_group != NULL) {
609 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
610 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
611 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
612 }
613 } else {
614 // 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 -0700615 std::string stats;
616 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
617 size_t start = stats.find('(') + 1;
618 size_t end = stats.find(')') - start;
619 thread_name = stats.substr(start, end);
620 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700621 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700622 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700623
624 int policy;
625 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700626 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700627
628 std::string scheduler_group(GetSchedulerGroup(GetTid()));
629 if (scheduler_group.empty()) {
630 scheduler_group = "default";
631 }
632
Elliott Hughesd92bec42011-09-02 17:04:36 -0700633 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700634 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700635 os << " daemon";
636 }
637 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700638 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700639 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700640
Elliott Hughesd92bec42011-09-02 17:04:36 -0700641 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700642 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700643 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700644 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700645 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700646 << " self=" << reinterpret_cast<const void*>(this) << "\n";
647 os << " | sysTid=" << GetTid()
648 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
649 << " sched=" << policy << "/" << sp.sched_priority
650 << " cgrp=" << scheduler_group
651 << " handle=" << GetImpl() << "\n";
652
653 // Grab the scheduler stats for this thread.
654 std::string scheduler_stats;
655 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
656 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
657 } else {
658 scheduler_stats = "0 0 0";
659 }
660
661 int utime = 0;
662 int stime = 0;
663 int task_cpu = 0;
664 std::string stats;
665 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
666 // Skip the command, which may contain spaces.
667 stats = stats.substr(stats.find(')') + 2);
668 // Extract the three fields we care about.
669 std::vector<std::string> fields;
670 Split(stats, ' ', fields);
671 utime = strtoull(fields[11].c_str(), NULL, 10);
672 stime = strtoull(fields[12].c_str(), NULL, 10);
673 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
674 }
675
676 os << " | schedstat=( " << scheduler_stats << " )"
677 << " utm=" << utime
678 << " stm=" << stime
679 << " core=" << task_cpu
680 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
681}
682
Elliott Hughesd369bb72011-09-12 14:41:14 -0700683struct StackDumpVisitor : public Thread::StackVisitor {
684 StackDumpVisitor(std::ostream& os) : os(os) {
685 }
686
Ian Rogersbdb03912011-09-14 00:55:44 -0700687 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700688 }
689
Ian Rogersbdb03912011-09-14 00:55:44 -0700690 void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700691 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
692
693 Method* m = frame.GetMethod();
694 Class* c = m->GetDeclaringClass();
695 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
696
697 os << " at " << PrettyMethod(m, false);
698 if (m->IsNative()) {
699 os << "(Native method)";
700 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700701 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700702 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
703 }
704 os << "\n";
705 }
706
707 std::ostream& os;
708};
709
Elliott Hughesd92bec42011-09-02 17:04:36 -0700710void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700711 StackDumpVisitor dumper(os);
712 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700713}
714
Elliott Hughes8d768a92011-09-14 16:35:25 -0700715Thread::State Thread::SetState(Thread::State new_state) {
716 Thread::State old_state = state_;
717 if (old_state == new_state) {
718 return old_state;
719 }
720
721 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
722 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
723
724 if (new_state == Thread::kRunnable) {
725 /*
726 * Change our status to Thread::kRunnable. The transition requires
727 * that we check for pending suspension, because the VM considers
728 * us to be "asleep" in all other states, and another thread could
729 * be performing a GC now.
730 *
731 * The order of operations is very significant here. One way to
732 * do this wrong is:
733 *
734 * GCing thread Our thread (in kNative)
735 * ------------ ----------------------
736 * check suspend count (== 0)
737 * SuspendAllThreads()
738 * grab suspend-count lock
739 * increment all suspend counts
740 * release suspend-count lock
741 * check thread state (== kNative)
742 * all are suspended, begin GC
743 * set state to kRunnable
744 * (continue executing)
745 *
746 * We can correct this by grabbing the suspend-count lock and
747 * performing both of our operations (check suspend count, set
748 * state) while holding it, now we need to grab a mutex on every
749 * transition to kRunnable.
750 *
751 * What we do instead is change the order of operations so that
752 * the transition to kRunnable happens first. If we then detect
753 * that the suspend count is nonzero, we switch to kSuspended.
754 *
755 * Appropriate compiler and memory barriers are required to ensure
756 * that the operations are observed in the expected order.
757 *
758 * This does create a small window of opportunity where a GC in
759 * progress could observe what appears to be a running thread (if
760 * it happens to look between when we set to kRunnable and when we
761 * switch to kSuspended). At worst this only affects assertions
762 * and thread logging. (We could work around it with some sort
763 * of intermediate "pre-running" state that is generally treated
764 * as equivalent to running, but that doesn't seem worthwhile.)
765 *
766 * We can also solve this by combining the "status" and "suspend
767 * count" fields into a single 32-bit value. This trades the
768 * store/load barrier on transition to kRunnable for an atomic RMW
769 * op on all transitions and all suspend count updates (also, all
770 * accesses to status or the thread count require bit-fiddling).
771 * It also eliminates the brief transition through kRunnable when
772 * the thread is supposed to be suspended. This is possibly faster
773 * on SMP and slightly more correct, but less convenient.
774 */
775 android_atomic_acquire_store(new_state, addr);
776 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
777 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
778 }
779 } else {
780 /*
781 * Not changing to Thread::kRunnable. No additional work required.
782 *
783 * We use a releasing store to ensure that, if we were runnable,
784 * any updates we previously made to objects on the managed heap
785 * will be observed before the state change.
786 */
787 android_atomic_release_store(new_state, addr);
788 }
789
790 return old_state;
791}
792
793void Thread::WaitUntilSuspended() {
794 // TODO: dalvik dropped the waiting thread's priority after a while.
795 // TODO: dalvik timed out and aborted.
796 useconds_t delay = 0;
797 while (GetState() == Thread::kRunnable) {
798 useconds_t new_delay = delay * 2;
799 CHECK_GE(new_delay, delay);
800 delay = new_delay;
801 if (delay == 0) {
802 sched_yield();
803 delay = 10000;
804 } else {
805 usleep(delay);
806 }
807 }
808}
809
Elliott Hughesbe759c62011-09-08 19:38:21 -0700810void Thread::ThreadExitCallback(void* arg) {
811 Thread* self = reinterpret_cast<Thread*>(arg);
812 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700813}
814
Elliott Hughesbe759c62011-09-08 19:38:21 -0700815void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700816 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700817 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700818
819 // Double-check the TLS slot allocation.
820 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700821 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700822 }
823
824 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700825}
826
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700827void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700828 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700829}
830
Elliott Hughesdcc24742011-09-07 14:02:44 -0700831Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700832 : peer_(NULL),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700833 wait_mutex_("Thread wait mutex"),
Elliott Hughes5f791332011-09-15 17:45:30 -0700834 wait_cond_("Thread wait condition variable"),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700835 wait_monitor_(NULL),
836 interrupted_(false),
837 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700838 top_of_managed_stack_(),
839 native_to_managed_record_(NULL),
840 top_sirt_(NULL),
841 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700842 state_(Thread::kUnknown),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700843 exception_(NULL),
844 suspend_count_(0),
845 class_loader_override_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700846}
847
Elliott Hughes02b48d12011-09-07 17:15:51 -0700848void MonitorExitVisitor(const Object* object, void*) {
849 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700850 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700851}
852
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700853Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700854 // TODO: check we're not calling the JNI DetachCurrentThread function from
855 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
856
857 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700858 if (jni_env_ != NULL) {
859 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
860 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700861
862 if (IsExceptionPending()) {
863 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
864 }
865
866 // TODO: ThreadGroup.removeThread(this);
867
Elliott Hughes93e74e82011-09-13 11:07:03 -0700868 if (peer_ != NULL) {
869 SetVmData(peer_, NULL);
870 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700871
872 // TODO: say "bye" to the debugger.
873 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700874 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700875 //}
876
877 // Thread.join() is implemented as an Object.wait() on the Thread.lock
878 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700879 if (peer_ != NULL) {
880 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
881 Class* java_lang_Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
882 Class* java_lang_ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
883 Field* lock_field = java_lang_Thread_class->FindDeclaredInstanceField("lock", java_lang_ThreadLock_class);
884
885 Thread* self = Thread::Current();
886 Object* lock = lock_field->GetObject(peer_);
887 // This conditional is only needed for tests, where Thread.lock won't have been set.
888 if (lock != NULL) {
889 lock->MonitorEnter(self);
890 lock->NotifyAll();
891 lock->MonitorExit(self);
892 }
893 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700894
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700895 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700896 jni_env_ = NULL;
897
898 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700899}
900
Ian Rogers408f79a2011-08-23 18:22:33 -0700901size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700902 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700903 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700904 count += cur->NumberOfReferences();
905 }
906 return count;
907}
908
Ian Rogers408f79a2011-08-23 18:22:33 -0700909bool Thread::SirtContains(jobject obj) {
910 Object** sirt_entry = reinterpret_cast<Object**>(obj);
911 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700912 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700913 // A SIRT should always have a jobject/jclass as a native method is passed
914 // in a this pointer or a class
915 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700916 if ((&cur->References()[0] <= sirt_entry) &&
917 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700918 return true;
919 }
920 }
921 return false;
922}
923
Ian Rogers408f79a2011-08-23 18:22:33 -0700924Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700925 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700926 if (obj == NULL) {
927 return NULL;
928 }
929 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
930 IndirectRefKind kind = GetIndirectRefKind(ref);
931 Object* result;
932 switch (kind) {
933 case kLocal:
934 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700935 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700936 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700937 break;
938 }
939 case kGlobal:
940 {
941 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
942 IndirectReferenceTable& globals = vm->globals;
943 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700944 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700945 break;
946 }
947 case kWeakGlobal:
948 {
949 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
950 IndirectReferenceTable& weak_globals = vm->weak_globals;
951 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700952 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700953 if (result == kClearedJniWeakGlobal) {
954 // This is a special case where it's okay to return NULL.
955 return NULL;
956 }
957 break;
958 }
959 case kSirtOrInvalid:
960 default:
961 // TODO: make stack indirect reference table lookup more efficient
962 // Check if this is a local reference in the SIRT
963 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700964 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700965 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700966 // Assume an invalid local reference is actually a direct pointer.
967 result = reinterpret_cast<Object*>(obj);
968 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700969 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700970 }
971 }
972
973 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700974 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
975 JniAbort(NULL);
976 } else {
977 if (result != kInvalidIndirectRefObject) {
978 Heap::VerifyObject(result);
979 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700980 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700981 return result;
982}
983
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700984class CountStackDepthVisitor : public Thread::StackVisitor {
985 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700986 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700987
Ian Rogersbdb03912011-09-14 00:55:44 -0700988 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700989 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700990 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700991
992 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700993 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700994 }
995
996 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700997 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700998};
999
Ian Rogersaaa20802011-09-11 21:47:37 -07001000//
1001class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001002 public:
Ian Rogersaaa20802011-09-11 21:47:37 -07001003 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
1004 // Allocate method trace with an extra slot that will hold the PC trace
1005 method_trace_ = Runtime::Current()->GetClassLinker()->
1006 AllocObjectArray<Object>(depth + 1);
1007 // Register a local reference as IntArray::Alloc may trigger GC
1008 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1009 pc_trace_ = IntArray::Alloc(depth);
1010#ifdef MOVING_GARBAGE_COLLECTOR
1011 // Re-read after potential GC
1012 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1013#endif
1014 // Save PC trace in last element of method trace, also places it into the
1015 // object graph.
1016 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001017 }
1018
Ian Rogersaaa20802011-09-11 21:47:37 -07001019 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001020
Ian Rogersbdb03912011-09-14 00:55:44 -07001021 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001022 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001023 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001024 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001025 }
1026
Ian Rogersaaa20802011-09-11 21:47:37 -07001027 jobject GetInternalStackTrace() const {
1028 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001029 }
1030
1031 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001032 // Current position down stack trace
1033 uint32_t count_;
1034 // Array of return PC values
1035 IntArray* pc_trace_;
1036 // An array of the methods on the stack, the last entry is a reference to the
1037 // PC trace
1038 ObjectArray<Object>* method_trace_;
1039 // Local indirect reference table entry for method trace
1040 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001041};
1042
Ian Rogersaaa20802011-09-11 21:47:37 -07001043void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001044 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001045 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001046 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1047 // CHECK(native_to_managed_record_ != NULL);
1048 NativeToManagedRecord* record = native_to_managed_record_;
1049
Ian Rogersbdb03912011-09-14 00:55:44 -07001050 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001051 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001052 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1053 visitor->VisitFrame(frame, pc);
1054 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001055 }
1056 if (record == NULL) {
1057 break;
1058 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001059 // last_tos should return Frame instead of sp?
1060 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1061 pc = record->last_top_of_managed_stack_pc_;
1062 record = record->link_;
1063 }
1064}
1065
1066void Thread::WalkStackUntilUpCall(StackVisitor* visitor) const {
1067 Frame frame = GetTopOfStack();
1068 uintptr_t pc = top_of_managed_stack_pc_;
1069
1070 if (frame.GetSP() != 0) {
1071 for ( ; frame.GetMethod() != 0; frame.Next()) {
1072 visitor->VisitFrame(frame, pc);
1073 pc = frame.GetReturnPC();
1074 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001075 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001076}
1077
Ian Rogersaaa20802011-09-11 21:47:37 -07001078jobject Thread::CreateInternalStackTrace() const {
1079 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001080 CountStackDepthVisitor count_visitor;
1081 WalkStack(&count_visitor);
1082 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001083
Ian Rogersaaa20802011-09-11 21:47:37 -07001084 // Transition into runnable state to work on Object*/Array*
1085 ScopedJniThreadState ts(jni_env_);
1086
1087 // Build internal stack trace
1088 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001089 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001090
Ian Rogersaaa20802011-09-11 21:47:37 -07001091 return build_trace_visitor.GetInternalStackTrace();
1092}
1093
1094jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1095 JNIEnv* env) {
1096 // Transition into runnable state to work on Object*/Array*
1097 ScopedJniThreadState ts(env);
1098
1099 // Decode the internal stack trace into the depth, method trace and PC trace
1100 ObjectArray<Object>* method_trace =
1101 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1102 int32_t depth = method_trace->GetLength()-1;
1103 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1104
1105 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1106
1107 // Create java_trace array and place in local reference table
1108 ObjectArray<StackTraceElement>* java_traces =
1109 class_linker->AllocStackTraceElementArray(depth);
1110 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001111
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001112 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001113 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1114 Method* method = down_cast<Method*>(method_trace->Get(i));
1115 uint32_t native_pc = pc_trace->Get(i);
1116 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001117 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001118 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001119
Ian Rogersaaa20802011-09-11 21:47:37 -07001120 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001121 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001122 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001123 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001124 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001125 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001126 method->ToDexPC(native_pc)));
1127#ifdef MOVING_GARBAGE_COLLECTOR
1128 // Re-read after potential GC
1129 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1130 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1131 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1132#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001133 java_traces->Set(i, obj);
1134 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001135 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001136}
1137
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001138void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001139 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001140 va_list args;
1141 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001142 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001143 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001144
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001145 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001146 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001147 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001148 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001149 descriptor.erase(descriptor.length() - 1);
1150
1151 JNIEnv* env = GetJniEnv();
1152 jclass exception_class = env->FindClass(descriptor.c_str());
1153 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1154 int rc = env->ThrowNew(exception_class, msg.c_str());
1155 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001156}
1157
Elliott Hughes79082e32011-08-25 12:07:32 -07001158void Thread::ThrowOutOfMemoryError() {
1159 UNIMPLEMENTED(FATAL);
1160}
1161
Ian Rogersbdb03912011-09-14 00:55:44 -07001162Method* Thread::CalleeSaveMethod() const {
1163 // TODO: we should only allocate this once
1164 // TODO: this code is ARM specific
1165 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
1166 method->SetCode(NULL, art::kThumb2, NULL);
1167 method->SetFrameSizeInBytes(64);
1168 method->SetReturnPcOffsetInBytes(60);
1169 method->SetCoreSpillMask(0x4FFE);
1170 method->SetFpSpillMask(0);
1171 return method;
1172}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001173
Ian Rogersbdb03912011-09-14 00:55:44 -07001174class CatchBlockStackVisitor : public Thread::StackVisitor {
1175 public:
1176 CatchBlockStackVisitor(Class* to_find, Context* ljc)
1177 : found_(false), to_find_(to_find), long_jump_context_(ljc) {}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001178
Ian Rogersbdb03912011-09-14 00:55:44 -07001179 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1180 if (!found_) {
1181 last_pc_ = pc;
1182 handler_frame_ = fr;
1183 Method* method = fr.GetMethod();
1184 if (pc > 0) {
1185 // Move the PC back 2 bytes as a call will frequently terminate the
1186 // decoding of a particular instruction and we want to make sure we
1187 // get the Dex PC of the instruction with the call and not the
1188 // instruction following.
1189 pc -= 2;
1190 }
1191 uint32_t dex_pc = method->ToDexPC(pc);
1192 if (dex_pc != DexFile::kDexNoIndex) {
1193 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1194 if (found_dex_pc != DexFile::kDexNoIndex) {
1195 found_ = true;
1196 handler_dex_pc_ = found_dex_pc;
1197 }
1198 }
1199 if (!found_) {
1200 // Caller may be handler, fill in callee saves in context
1201 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001202 }
1203 }
1204 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001205
1206 // Did we find a catch block yet?
1207 bool found_;
1208 // The type of the exception catch block to find
1209 Class* to_find_;
1210 // Frame with found handler or last frame if no handler found
1211 Frame handler_frame_;
1212 // Found dex PC of the handler block
1213 uint32_t handler_dex_pc_;
1214 // Context that will be the target of the long jump
1215 Context* long_jump_context_;
1216 uintptr_t last_pc_;
1217};
1218
1219void Thread::DeliverException(Throwable* exception) {
1220 SetException(exception); // Set exception on thread
1221
1222 Context* long_jump_context = GetLongJumpContext();
1223 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
1224 WalkStackUntilUpCall(&catch_finder);
1225
1226 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1227 uintptr_t long_jump_pc;
1228 if (catch_finder.found_) {
1229 long_jump_pc = catch_finder.handler_frame_.GetMethod()->ToNativePC(catch_finder.handler_dex_pc_);
1230 } else {
1231 long_jump_pc = catch_finder.last_pc_;
1232 }
1233 long_jump_context->SetPC(long_jump_pc);
1234 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001235}
1236
Ian Rogersbdb03912011-09-14 00:55:44 -07001237Context* Thread::GetLongJumpContext() {
1238 Context* result = long_jump_context_.get();
1239 if (result == NULL) {
1240 result = Context::Create();
1241 long_jump_context_.reset(result);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001242 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001243 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001244}
1245
Elliott Hughes5f791332011-09-15 17:45:30 -07001246bool Thread::HoldsLock(Object* object) {
1247 if (object == NULL) {
1248 return false;
1249 }
1250 return object->GetLockOwner() == thin_lock_id_;
1251}
1252
Elliott Hughes410c0c82011-09-01 17:58:25 -07001253void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001254 if (exception_ != NULL) {
1255 visitor(exception_, arg);
1256 }
1257 if (peer_ != NULL) {
1258 visitor(peer_, arg);
1259 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001260 jni_env_->locals.VisitRoots(visitor, arg);
1261 jni_env_->monitors.VisitRoots(visitor, arg);
1262 // visitThreadStack(visitor, thread, arg);
1263 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1264}
1265
Ian Rogersb033c752011-07-20 12:22:35 -07001266static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001267 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001268 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001269 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001270 "Blocked",
1271 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001272 "Initializing",
1273 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001274 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001275 "VmWait",
1276 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001277};
1278std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001279 int int_state = static_cast<int>(state);
1280 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1281 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001282 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001283 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001284 }
1285 return os;
1286}
1287
Elliott Hughes330304d2011-08-12 14:28:05 -07001288std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1289 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001290 << ",pthread_t=" << thread.GetImpl()
1291 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001292 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001293 << ",state=" << thread.GetState()
1294 << ",peer=" << thread.GetPeer()
1295 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001296 return os;
1297}
1298
Elliott Hughes8daa0922011-09-11 13:46:25 -07001299} // namespace art