blob: 0da46b61b4b22247cf355e5297eb064bda29f966 [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"),
834 wait_monitor_(NULL),
835 interrupted_(false),
836 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700837 top_of_managed_stack_(),
838 native_to_managed_record_(NULL),
839 top_sirt_(NULL),
840 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700841 state_(Thread::kUnknown),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700842 exception_(NULL),
843 suspend_count_(0),
844 class_loader_override_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700845}
846
Elliott Hughes02b48d12011-09-07 17:15:51 -0700847void MonitorExitVisitor(const Object* object, void*) {
848 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700849 entered_monitor->MonitorExit();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700850}
851
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700852Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700853 // TODO: check we're not calling the JNI DetachCurrentThread function from
854 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
855
856 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700857 if (jni_env_ != NULL) {
858 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
859 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700860
861 if (IsExceptionPending()) {
862 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
863 }
864
865 // TODO: ThreadGroup.removeThread(this);
866
Elliott Hughes93e74e82011-09-13 11:07:03 -0700867 if (peer_ != NULL) {
868 SetVmData(peer_, NULL);
869 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700870
871 // TODO: say "bye" to the debugger.
872 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700873 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700874 //}
875
876 // Thread.join() is implemented as an Object.wait() on the Thread.lock
877 // object. Signal anyone who is waiting.
878 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
879 //dvmLockObject(self, lock);
880 //dvmObjectNotifyAll(self, lock);
881 //dvmUnlockObject(self, lock);
882 //lock = NULL;
883
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700884 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700885 jni_env_ = NULL;
886
887 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700888}
889
Ian Rogers408f79a2011-08-23 18:22:33 -0700890size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700891 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700892 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700893 count += cur->NumberOfReferences();
894 }
895 return count;
896}
897
Ian Rogers408f79a2011-08-23 18:22:33 -0700898bool Thread::SirtContains(jobject obj) {
899 Object** sirt_entry = reinterpret_cast<Object**>(obj);
900 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700901 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700902 // A SIRT should always have a jobject/jclass as a native method is passed
903 // in a this pointer or a class
904 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700905 if ((&cur->References()[0] <= sirt_entry) &&
906 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700907 return true;
908 }
909 }
910 return false;
911}
912
Ian Rogers408f79a2011-08-23 18:22:33 -0700913Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700914 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700915 if (obj == NULL) {
916 return NULL;
917 }
918 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
919 IndirectRefKind kind = GetIndirectRefKind(ref);
920 Object* result;
921 switch (kind) {
922 case kLocal:
923 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700924 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700925 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700926 break;
927 }
928 case kGlobal:
929 {
930 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
931 IndirectReferenceTable& globals = vm->globals;
932 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700933 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700934 break;
935 }
936 case kWeakGlobal:
937 {
938 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
939 IndirectReferenceTable& weak_globals = vm->weak_globals;
940 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700941 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700942 if (result == kClearedJniWeakGlobal) {
943 // This is a special case where it's okay to return NULL.
944 return NULL;
945 }
946 break;
947 }
948 case kSirtOrInvalid:
949 default:
950 // TODO: make stack indirect reference table lookup more efficient
951 // Check if this is a local reference in the SIRT
952 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700954 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700955 // Assume an invalid local reference is actually a direct pointer.
956 result = reinterpret_cast<Object*>(obj);
957 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700958 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700959 }
960 }
961
962 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700963 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
964 JniAbort(NULL);
965 } else {
966 if (result != kInvalidIndirectRefObject) {
967 Heap::VerifyObject(result);
968 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700969 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700970 return result;
971}
972
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700973class CountStackDepthVisitor : public Thread::StackVisitor {
974 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700975 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700976
Ian Rogersbdb03912011-09-14 00:55:44 -0700977 virtual void VisitFrame(const Frame&, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700978 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700979 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700980
981 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700982 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700983 }
984
985 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700986 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700987};
988
Ian Rogersaaa20802011-09-11 21:47:37 -0700989//
990class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700991 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700992 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
993 // Allocate method trace with an extra slot that will hold the PC trace
994 method_trace_ = Runtime::Current()->GetClassLinker()->
995 AllocObjectArray<Object>(depth + 1);
996 // Register a local reference as IntArray::Alloc may trigger GC
997 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
998 pc_trace_ = IntArray::Alloc(depth);
999#ifdef MOVING_GARBAGE_COLLECTOR
1000 // Re-read after potential GC
1001 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1002#endif
1003 // Save PC trace in last element of method trace, also places it into the
1004 // object graph.
1005 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001006 }
1007
Ian Rogersaaa20802011-09-11 21:47:37 -07001008 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001009
Ian Rogersbdb03912011-09-14 00:55:44 -07001010 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001011 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001012 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001013 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001014 }
1015
Ian Rogersaaa20802011-09-11 21:47:37 -07001016 jobject GetInternalStackTrace() const {
1017 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001018 }
1019
1020 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001021 // Current position down stack trace
1022 uint32_t count_;
1023 // Array of return PC values
1024 IntArray* pc_trace_;
1025 // An array of the methods on the stack, the last entry is a reference to the
1026 // PC trace
1027 ObjectArray<Object>* method_trace_;
1028 // Local indirect reference table entry for method trace
1029 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001030};
1031
Ian Rogersaaa20802011-09-11 21:47:37 -07001032void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001033 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001034 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001035 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1036 // CHECK(native_to_managed_record_ != NULL);
1037 NativeToManagedRecord* record = native_to_managed_record_;
1038
Ian Rogersbdb03912011-09-14 00:55:44 -07001039 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001040 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001041 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1042 visitor->VisitFrame(frame, pc);
1043 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001044 }
1045 if (record == NULL) {
1046 break;
1047 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001048 // last_tos should return Frame instead of sp?
1049 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack_));
1050 pc = record->last_top_of_managed_stack_pc_;
1051 record = record->link_;
1052 }
1053}
1054
1055void Thread::WalkStackUntilUpCall(StackVisitor* visitor) const {
1056 Frame frame = GetTopOfStack();
1057 uintptr_t pc = top_of_managed_stack_pc_;
1058
1059 if (frame.GetSP() != 0) {
1060 for ( ; frame.GetMethod() != 0; frame.Next()) {
1061 visitor->VisitFrame(frame, pc);
1062 pc = frame.GetReturnPC();
1063 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001064 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001065}
1066
Ian Rogersaaa20802011-09-11 21:47:37 -07001067jobject Thread::CreateInternalStackTrace() const {
1068 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001069 CountStackDepthVisitor count_visitor;
1070 WalkStack(&count_visitor);
1071 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001072
Ian Rogersaaa20802011-09-11 21:47:37 -07001073 // Transition into runnable state to work on Object*/Array*
1074 ScopedJniThreadState ts(jni_env_);
1075
1076 // Build internal stack trace
1077 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001078 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001079
Ian Rogersaaa20802011-09-11 21:47:37 -07001080 return build_trace_visitor.GetInternalStackTrace();
1081}
1082
1083jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1084 JNIEnv* env) {
1085 // Transition into runnable state to work on Object*/Array*
1086 ScopedJniThreadState ts(env);
1087
1088 // Decode the internal stack trace into the depth, method trace and PC trace
1089 ObjectArray<Object>* method_trace =
1090 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1091 int32_t depth = method_trace->GetLength()-1;
1092 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1093
1094 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1095
1096 // Create java_trace array and place in local reference table
1097 ObjectArray<StackTraceElement>* java_traces =
1098 class_linker->AllocStackTraceElementArray(depth);
1099 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001100
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001101 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001102 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1103 Method* method = down_cast<Method*>(method_trace->Get(i));
1104 uint32_t native_pc = pc_trace->Get(i);
1105 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001106 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -07001107 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001108 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001109
Ian Rogersaaa20802011-09-11 21:47:37 -07001110 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001111 StackTraceElement* obj =
1112 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -07001113 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001114 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001115 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001116 method->ToDexPC(native_pc)));
1117#ifdef MOVING_GARBAGE_COLLECTOR
1118 // Re-read after potential GC
1119 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1120 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1121 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1122#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001123 java_traces->Set(i, obj);
1124 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001125 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001126}
1127
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001128void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001129 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001130 va_list args;
1131 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001132 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001133 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001134
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001135 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001136 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001137 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001138 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001139 descriptor.erase(descriptor.length() - 1);
1140
1141 JNIEnv* env = GetJniEnv();
1142 jclass exception_class = env->FindClass(descriptor.c_str());
1143 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1144 int rc = env->ThrowNew(exception_class, msg.c_str());
1145 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001146}
1147
Elliott Hughes79082e32011-08-25 12:07:32 -07001148void Thread::ThrowOutOfMemoryError() {
1149 UNIMPLEMENTED(FATAL);
1150}
1151
Ian Rogersbdb03912011-09-14 00:55:44 -07001152Method* Thread::CalleeSaveMethod() const {
1153 // TODO: we should only allocate this once
1154 // TODO: this code is ARM specific
1155 Method* method = Runtime::Current()->GetClassLinker()->AllocMethod();
1156 method->SetCode(NULL, art::kThumb2, NULL);
1157 method->SetFrameSizeInBytes(64);
1158 method->SetReturnPcOffsetInBytes(60);
1159 method->SetCoreSpillMask(0x4FFE);
1160 method->SetFpSpillMask(0);
1161 return method;
1162}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001163
Ian Rogersbdb03912011-09-14 00:55:44 -07001164class CatchBlockStackVisitor : public Thread::StackVisitor {
1165 public:
1166 CatchBlockStackVisitor(Class* to_find, Context* ljc)
1167 : found_(false), to_find_(to_find), long_jump_context_(ljc) {}
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001168
Ian Rogersbdb03912011-09-14 00:55:44 -07001169 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1170 if (!found_) {
1171 last_pc_ = pc;
1172 handler_frame_ = fr;
1173 Method* method = fr.GetMethod();
1174 if (pc > 0) {
1175 // Move the PC back 2 bytes as a call will frequently terminate the
1176 // decoding of a particular instruction and we want to make sure we
1177 // get the Dex PC of the instruction with the call and not the
1178 // instruction following.
1179 pc -= 2;
1180 }
1181 uint32_t dex_pc = method->ToDexPC(pc);
1182 if (dex_pc != DexFile::kDexNoIndex) {
1183 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1184 if (found_dex_pc != DexFile::kDexNoIndex) {
1185 found_ = true;
1186 handler_dex_pc_ = found_dex_pc;
1187 }
1188 }
1189 if (!found_) {
1190 // Caller may be handler, fill in callee saves in context
1191 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001192 }
1193 }
1194 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001195
1196 // Did we find a catch block yet?
1197 bool found_;
1198 // The type of the exception catch block to find
1199 Class* to_find_;
1200 // Frame with found handler or last frame if no handler found
1201 Frame handler_frame_;
1202 // Found dex PC of the handler block
1203 uint32_t handler_dex_pc_;
1204 // Context that will be the target of the long jump
1205 Context* long_jump_context_;
1206 uintptr_t last_pc_;
1207};
1208
1209void Thread::DeliverException(Throwable* exception) {
1210 SetException(exception); // Set exception on thread
1211
1212 Context* long_jump_context = GetLongJumpContext();
1213 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
1214 WalkStackUntilUpCall(&catch_finder);
1215
1216 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1217 uintptr_t long_jump_pc;
1218 if (catch_finder.found_) {
1219 long_jump_pc = catch_finder.handler_frame_.GetMethod()->ToNativePC(catch_finder.handler_dex_pc_);
1220 } else {
1221 long_jump_pc = catch_finder.last_pc_;
1222 }
1223 long_jump_context->SetPC(long_jump_pc);
1224 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001225}
1226
Ian Rogersbdb03912011-09-14 00:55:44 -07001227Context* Thread::GetLongJumpContext() {
1228 Context* result = long_jump_context_.get();
1229 if (result == NULL) {
1230 result = Context::Create();
1231 long_jump_context_.reset(result);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001232 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001233 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001234}
1235
Elliott Hughes410c0c82011-09-01 17:58:25 -07001236void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001237 if (exception_ != NULL) {
1238 visitor(exception_, arg);
1239 }
1240 if (peer_ != NULL) {
1241 visitor(peer_, arg);
1242 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001243 jni_env_->locals.VisitRoots(visitor, arg);
1244 jni_env_->monitors.VisitRoots(visitor, arg);
1245 // visitThreadStack(visitor, thread, arg);
1246 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1247}
1248
Ian Rogersb033c752011-07-20 12:22:35 -07001249static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001250 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001251 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001252 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001253 "Blocked",
1254 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001255 "Initializing",
1256 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001257 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001258 "VmWait",
1259 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001260};
1261std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001262 int int_state = static_cast<int>(state);
1263 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1264 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001265 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001266 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001267 }
1268 return os;
1269}
1270
Elliott Hughes330304d2011-08-12 14:28:05 -07001271std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1272 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001273 << ",pthread_t=" << thread.GetImpl()
1274 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001275 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001276 << ",state=" << thread.GetState()
1277 << ",peer=" << thread.GetPeer()
1278 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001279 return os;
1280}
1281
Elliott Hughes8daa0922011-09-11 13:46:25 -07001282} // namespace art