blob: d879cea70960cf9a6904816551486bcd4fd8ae82 [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 Rogers408f79a2011-08-23 18:22:33 -070030#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070031#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070032#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070034#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070035#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070036#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070037#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070038
39namespace art {
40
41pthread_key_t Thread::pthread_key_self_;
42
buzbee4a3164f2011-09-03 11:25:10 -070043// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070044void DebugMe(Method* method, uint32_t info) {
buzbee4a3164f2011-09-03 11:25:10 -070045 LOG(INFO) << "DebugMe";
46 if (method != NULL)
47 LOG(INFO) << PrettyMethod(method);
48 LOG(INFO) << "Info: " << info;
49}
50
buzbee1b4c8592011-08-31 10:43:51 -070051// TODO: placeholder. This is what generated code will call to throw
Elliott Hughesd369bb72011-09-12 14:41:14 -070052void ThrowException(Thread* thread, Throwable* exception) {
53 /*
54 * exception may be NULL, in which case this routine should
55 * throw NPE. NOTE: this is a convenience for generated code,
56 * which previously did the null check inline and constructed
57 * and threw a NPE if NULL. This routine responsible for setting
58 * exception_ in thread.
59 */
60 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw: " << PrettyType(exception);
buzbee1b4c8592011-08-31 10:43:51 -070061}
62
63// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070064Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070065 /*
66 * Should initialize & fix up method->dex_cache_resolved_types_[].
67 * Returns initialized type. Does not return normally if an exception
68 * is thrown, but instead initiates the catch. Should be similar to
69 * ClassLinker::InitializeStaticStorageFromCode.
70 */
71 UNIMPLEMENTED(FATAL);
72 return NULL;
73}
74
buzbee561227c2011-09-02 15:28:19 -070075// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -070076void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -070077 /*
78 * Slow-path handler on invoke virtual method path in which
79 * base method is unresolved at compile-time. Doesn't need to
80 * return anything - just either ensure that
81 * method->dex_cache_resolved_methods_(method_idx) != NULL or
82 * throw and unwind. The caller will restart call sequence
83 * from the beginning.
84 */
85}
86
buzbee1da522d2011-09-04 11:22:20 -070087// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -070088Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -070089 /*
90 * Just a wrapper around Array::AllocFromCode() that additionally
91 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
92 */
93 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
94 return Array::AllocFromCode(type_index, method, component_count);
95}
96
buzbee2a475e72011-09-07 17:19:17 -070097// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -070098void CheckCastFromCode(const Class* a, const Class* b) {
buzbee2a475e72011-09-07 17:19:17 -070099 if (a->IsAssignableFrom(b)) {
100 return;
101 }
102 UNIMPLEMENTED(FATAL);
103}
104
Elliott Hughesd369bb72011-09-12 14:41:14 -0700105void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700106 // TODO: throw and unwind if lock not held
107 // TODO: throw and unwind on NPE
108 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700109}
110
Elliott Hughesd369bb72011-09-12 14:41:14 -0700111void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700112 obj->MonitorEnter(thread);
113 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700114}
115
Elliott Hughesd369bb72011-09-12 14:41:14 -0700116void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700117 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700118}
119
buzbeecefd1872011-09-09 09:59:52 -0700120// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700121void StackOverflowFromCode(Method* method) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700122 Thread::Current()->Dump(std::cerr);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700123 //NOTE: to save code space, this handler needs to look up its own Thread*
124 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700125}
126
buzbee5ade1d22011-09-09 14:44:52 -0700127// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700128void ThrowNullPointerFromCode() {
129 Thread::Current()->Dump(std::cerr);
130 //NOTE: to save code space, this handler must look up caller's Method*
131 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700132}
133
134// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700135void ThrowDivZeroFromCode() {
136 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700137}
138
139// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700140void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
141 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700142}
143
144// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700145void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700146 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
147 " ref: " << ref;
148}
149
150// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700151void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700152 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
153}
154
155// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700156void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700157 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
158}
159
160// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700161void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700162 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
163}
164
165// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700166void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700167 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
168}
169
170/*
171 * Temporary placeholder. Should include run-time checks for size
172 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
173 * As with other new "FromCode" routines, this should return to the caller
174 * only if no exception has been thrown.
175 *
176 * NOTE: When dealing with a raw dex file, the data to be copied uses
177 * little-endian ordering. Require that oat2dex do any required swapping
178 * so this routine can get by with a memcpy().
179 *
180 * Format of the data:
181 * ushort ident = 0x0300 magic value
182 * ushort width width of each element in the table
183 * uint size number of elements in the table
184 * ubyte data[size*width] table of data values (may contain a single-byte
185 * padding at the end)
186 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700187void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700188 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
189 uint32_t size_in_bytes = size * table[1];
190 if (static_cast<int32_t>(size) > array->GetLength()) {
191 ThrowArrayBoundsFromCode(array->GetLength(), size);
192 }
193 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
194 (char*)&table[4], size_in_bytes);
195}
196
Brian Carlstrom16192862011-09-12 17:50:06 -0700197/*
198 * TODO: placeholder for a method that can be called by the
199 * invoke-interface trampoline to unwind and handle exception. The
200 * trampoline will arrange it so that the caller appears to be the
201 * callsite of the failed invoke-interface. See comments in
202 * runtime_support.S
203 */
204extern "C" void artFailedInvokeInterface() {
205 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
206}
207
208// See comments in runtime_support.S
209extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
210 Object* this_object , Method* caller_method)
211{
212 if (this_object == NULL) {
213 ThrowNullPointerFromCode();
214 }
215 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
216 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
217 if (interface_method == NULL) {
218 UNIMPLEMENTED(FATAL) << "Could not resolve interface method. Throw error and unwind";
219 }
220 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
221 const void* code = method->GetCode();
222
223 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
224 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
225 uint64_t result = ((code_uint << 32) | method_uint);
226 return result;
227}
228
buzbee5ade1d22011-09-09 14:44:52 -0700229// TODO: move to more appropriate location
230/*
231 * Float/double conversion requires clamping to min and max of integer form. If
232 * target doesn't support this normally, use these.
233 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700234int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700235 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
236 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
237 if (d >= kMaxLong)
238 return (int64_t)0x7fffffffffffffffULL;
239 else if (d <= kMinLong)
240 return (int64_t)0x8000000000000000ULL;
241 else if (d != d) // NaN case
242 return 0;
243 else
244 return (int64_t)d;
245}
246
Elliott Hughesd369bb72011-09-12 14:41:14 -0700247int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700248 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
249 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
250 if (f >= kMaxLong)
251 return (int64_t)0x7fffffffffffffffULL;
252 else if (f <= kMinLong)
253 return (int64_t)0x8000000000000000ULL;
254 else if (f != f) // NaN case
255 return 0;
256 else
257 return (int64_t)f;
258}
259
Brian Carlstrom16192862011-09-12 17:50:06 -0700260// Return value helper for jobject return types
261static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
262 return thread->DecodeJObject(obj);
263}
264
buzbee3ea4ec52011-08-22 17:37:19 -0700265void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700266#if defined(__arm__)
267 pShlLong = art_shl_long;
268 pShrLong = art_shr_long;
269 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700270 pIdiv = __aeabi_idiv;
271 pIdivmod = __aeabi_idivmod;
272 pI2f = __aeabi_i2f;
273 pF2iz = __aeabi_f2iz;
274 pD2f = __aeabi_d2f;
275 pF2d = __aeabi_f2d;
276 pD2iz = __aeabi_d2iz;
277 pL2f = __aeabi_l2f;
278 pL2d = __aeabi_l2d;
279 pFadd = __aeabi_fadd;
280 pFsub = __aeabi_fsub;
281 pFdiv = __aeabi_fdiv;
282 pFmul = __aeabi_fmul;
283 pFmodf = fmodf;
284 pDadd = __aeabi_dadd;
285 pDsub = __aeabi_dsub;
286 pDdiv = __aeabi_ddiv;
287 pDmul = __aeabi_dmul;
288 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700289 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700290 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700291 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700292#endif
buzbeec396efc2011-09-11 09:36:41 -0700293 pF2l = F2L;
294 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700295 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700296 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700297 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700298 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700299 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700300 pGet32Static = Field::Get32StaticFromCode;
301 pSet32Static = Field::Set32StaticFromCode;
302 pGet64Static = Field::Get64StaticFromCode;
303 pSet64Static = Field::Set64StaticFromCode;
304 pGetObjStatic = Field::GetObjStaticFromCode;
305 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700306 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
307 pThrowException = ThrowException;
308 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700309 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700310 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700311 pInstanceofNonTrivialFromCode = Object::InstanceOf;
312 pCheckCastFromCode = CheckCastFromCode;
313 pLockObjectFromCode = LockObjectFromCode;
314 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700315 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700316 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700317 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700318 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
319 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
320 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
321 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
322 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
323 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
324 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
325 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700326 pFindNativeMethod = FindNativeMethod;
327 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700328 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700329}
330
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700331void Frame::Next() {
332 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700333 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700335}
336
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700337uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700338 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700339 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700340 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700341}
342
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700344 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700345 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700347}
348
Elliott Hughes93e74e82011-09-13 11:07:03 -0700349void* Thread::CreateCallback(void *arg) {
350 Thread* self = reinterpret_cast<Thread*>(arg);
351 Runtime* runtime = Runtime::Current();
352
353 self->Attach(runtime);
354
355 ClassLinker* class_linker = runtime->GetClassLinker();
356
357 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
358 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
359
360 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
361 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
362 if (thread_name != NULL) {
363 SetThreadName(thread_name->ToModifiedUtf8().c_str());
364 }
365
366 // Wait until it's safe to start running code. (There may have been a suspend-all
367 // in progress while we were starting up.)
368 runtime->GetThreadList()->WaitForGo();
369
370 // TODO: say "hi" to the debugger.
371 //if (gDvm.debuggerConnected) {
372 // dvmDbgPostThreadStart(self);
373 //}
374
375 // Invoke the 'run' method of our java.lang.Thread.
376 CHECK(self->peer_ != NULL);
377 Object* receiver = self->peer_;
378 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
379 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
380 m->Invoke(self, receiver, NULL, NULL);
381
382 // Detach.
383 runtime->GetThreadList()->Unregister();
384
Carl Shapirob5573532011-07-12 18:22:59 -0700385 return NULL;
386}
387
Elliott Hughes93e74e82011-09-13 11:07:03 -0700388void SetVmData(Object* managed_thread, Thread* native_thread) {
389 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
390
391 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
392 Class* int_class = class_linker->FindPrimitiveClass('I');
393
394 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
395
396 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
397}
398
Elliott Hughesd369bb72011-09-12 14:41:14 -0700399void Thread::Create(Object* peer, size_t stack_size) {
400 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700401
Elliott Hughesd369bb72011-09-12 14:41:14 -0700402 if (stack_size == 0) {
403 stack_size = Runtime::Current()->GetDefaultStackSize();
404 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700405
Elliott Hughes93e74e82011-09-13 11:07:03 -0700406 Thread* native_thread = new Thread;
407 native_thread->peer_ = peer;
408
409 // Thread.start is synchronized, so we know that vmData is 0,
410 // and know that we're not racing to assign it.
411 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700412
413 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700414 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
415 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
416 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
417 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
418 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700419
420 // Let the child know when it's safe to start running.
421 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700422}
423
Elliott Hughes93e74e82011-09-13 11:07:03 -0700424void Thread::Attach(const Runtime* runtime) {
425 InitCpu();
426 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700427
Elliott Hughes93e74e82011-09-13 11:07:03 -0700428 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700429
Elliott Hughes93e74e82011-09-13 11:07:03 -0700430 tid_ = ::art::GetTid();
431 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700432
Elliott Hughes93e74e82011-09-13 11:07:03 -0700433 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700434
Elliott Hughes8d768a92011-09-14 16:35:25 -0700435 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700436
Elliott Hughes93e74e82011-09-13 11:07:03 -0700437 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700438
Elliott Hughes93e74e82011-09-13 11:07:03 -0700439 runtime->GetThreadList()->Register(this);
440}
441
442Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
443 Thread* self = new Thread;
444 self->Attach(runtime);
445
446 self->SetState(Thread::kRunnable);
447
448 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700449
450 // If we're the main thread, ClassLinker won't be created until after we're attached,
451 // so that thread needs a two-stage attach. Regular threads don't need this hack.
452 if (self->thin_lock_id_ != ThreadList::kMainId) {
453 self->CreatePeer(name, as_daemon);
454 }
455
456 return self;
457}
458
Elliott Hughesd369bb72011-09-12 14:41:14 -0700459jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
460 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
461 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
462 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
463 // This will be null in the compiler (and tests), but never in a running system.
464 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
465 return thread_group;
466}
467
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700468void Thread::CreatePeer(const char* name, bool as_daemon) {
469 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
470
471 JNIEnv* env = jni_env_;
472
Elliott Hughesd369bb72011-09-12 14:41:14 -0700473 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
474 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700475 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700476 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700477 jboolean thread_is_daemon = as_daemon;
478
479 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700480 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700481
Elliott Hughes8daa0922011-09-11 13:46:25 -0700482 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700483
484 // Because we mostly run without code available (in the compiler, in tests), we
485 // manually assign the fields the constructor should have set.
486 // TODO: lose this.
487 jfieldID fid;
488 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
489 env->SetObjectField(peer, fid, thread_group);
490 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
491 env->SetObjectField(peer, fid, thread_name);
492 fid = env->GetFieldID(c, "priority", "I");
493 env->SetIntField(peer, fid, thread_priority);
494 fid = env->GetFieldID(c, "daemon", "Z");
495 env->SetBooleanField(peer, fid, thread_is_daemon);
496
497 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700498}
499
Elliott Hughesbe759c62011-09-08 19:38:21 -0700500void Thread::InitStackHwm() {
501 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700502 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700503
Elliott Hughesbe759c62011-09-08 19:38:21 -0700504 void* stack_base;
505 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700506 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700507
Elliott Hughesbe759c62011-09-08 19:38:21 -0700508 if (stack_size <= kStackOverflowReservedBytes) {
509 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
510 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700511
512 // stack_base is the "lowest addressable byte" of the stack.
513 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
514 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700515 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700516
517 // Sanity check.
518 int stack_variable;
519 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700520
Elliott Hughes8d768a92011-09-14 16:35:25 -0700521 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700522}
523
Elliott Hughesa0957642011-09-02 14:27:33 -0700524void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700525 DumpState(os);
526 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700527}
528
Elliott Hughesd92bec42011-09-02 17:04:36 -0700529std::string GetSchedulerGroup(pid_t tid) {
530 // /proc/<pid>/group looks like this:
531 // 2:devices:/
532 // 1:cpuacct,cpu:/
533 // We want the third field from the line whose second field contains the "cpu" token.
534 std::string cgroup_file;
535 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
536 return "";
537 }
538 std::vector<std::string> cgroup_lines;
539 Split(cgroup_file, '\n', cgroup_lines);
540 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
541 std::vector<std::string> cgroup_fields;
542 Split(cgroup_lines[i], ':', cgroup_fields);
543 std::vector<std::string> cgroups;
544 Split(cgroup_fields[1], ',', cgroups);
545 for (size_t i = 0; i < cgroups.size(); ++i) {
546 if (cgroups[i] == "cpu") {
547 return cgroup_fields[2].substr(1); // Skip the leading slash.
548 }
549 }
550 }
551 return "";
552}
553
554void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700555 std::string thread_name("<native thread without managed peer>");
556 std::string group_name;
557 int priority;
558 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700559
Elliott Hughesd369bb72011-09-12 14:41:14 -0700560 if (peer_ != NULL) {
561 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
562
563 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
564 Class* int_class = class_linker->FindPrimitiveClass('I');
565 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
566 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
567 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
568
569 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
570 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
571 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
572 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
573
574 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
575 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
576 priority = priority_field->GetInt(peer_);
577 is_daemon = daemon_field->GetBoolean(peer_);
578
579 Object* thread_group = thread_group_field->GetObject(peer_);
580 if (thread_group != NULL) {
581 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
582 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
583 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
584 }
585 } else {
586 // 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 -0700587 std::string stats;
588 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
589 size_t start = stats.find('(') + 1;
590 size_t end = stats.find(')') - start;
591 thread_name = stats.substr(start, end);
592 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700593 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700594 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700595
596 int policy;
597 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700598 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700599
600 std::string scheduler_group(GetSchedulerGroup(GetTid()));
601 if (scheduler_group.empty()) {
602 scheduler_group = "default";
603 }
604
Elliott Hughesd92bec42011-09-02 17:04:36 -0700605 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700606 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700607 os << " daemon";
608 }
609 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700610 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700611 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700612
Elliott Hughesd92bec42011-09-02 17:04:36 -0700613 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700614 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700615 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700616 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700617 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700618 << " self=" << reinterpret_cast<const void*>(this) << "\n";
619 os << " | sysTid=" << GetTid()
620 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
621 << " sched=" << policy << "/" << sp.sched_priority
622 << " cgrp=" << scheduler_group
623 << " handle=" << GetImpl() << "\n";
624
625 // Grab the scheduler stats for this thread.
626 std::string scheduler_stats;
627 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
628 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
629 } else {
630 scheduler_stats = "0 0 0";
631 }
632
633 int utime = 0;
634 int stime = 0;
635 int task_cpu = 0;
636 std::string stats;
637 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
638 // Skip the command, which may contain spaces.
639 stats = stats.substr(stats.find(')') + 2);
640 // Extract the three fields we care about.
641 std::vector<std::string> fields;
642 Split(stats, ' ', fields);
643 utime = strtoull(fields[11].c_str(), NULL, 10);
644 stime = strtoull(fields[12].c_str(), NULL, 10);
645 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
646 }
647
648 os << " | schedstat=( " << scheduler_stats << " )"
649 << " utm=" << utime
650 << " stm=" << stime
651 << " core=" << task_cpu
652 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
653}
654
Elliott Hughesd369bb72011-09-12 14:41:14 -0700655struct StackDumpVisitor : public Thread::StackVisitor {
656 StackDumpVisitor(std::ostream& os) : os(os) {
657 }
658
659 ~StackDumpVisitor() {
660 }
661
662 void VisitFrame(const Frame& frame) {
663 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
664
665 Method* m = frame.GetMethod();
666 Class* c = m->GetDeclaringClass();
667 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
668
669 os << " at " << PrettyMethod(m, false);
670 if (m->IsNative()) {
671 os << "(Native method)";
672 } else {
673 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(frame.GetPC()));
674 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
675 }
676 os << "\n";
677 }
678
679 std::ostream& os;
680};
681
Elliott Hughesd92bec42011-09-02 17:04:36 -0700682void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700683 StackDumpVisitor dumper(os);
684 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700685}
686
Elliott Hughes8d768a92011-09-14 16:35:25 -0700687Thread::State Thread::SetState(Thread::State new_state) {
688 Thread::State old_state = state_;
689 if (old_state == new_state) {
690 return old_state;
691 }
692
693 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
694 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
695
696 if (new_state == Thread::kRunnable) {
697 /*
698 * Change our status to Thread::kRunnable. The transition requires
699 * that we check for pending suspension, because the VM considers
700 * us to be "asleep" in all other states, and another thread could
701 * be performing a GC now.
702 *
703 * The order of operations is very significant here. One way to
704 * do this wrong is:
705 *
706 * GCing thread Our thread (in kNative)
707 * ------------ ----------------------
708 * check suspend count (== 0)
709 * SuspendAllThreads()
710 * grab suspend-count lock
711 * increment all suspend counts
712 * release suspend-count lock
713 * check thread state (== kNative)
714 * all are suspended, begin GC
715 * set state to kRunnable
716 * (continue executing)
717 *
718 * We can correct this by grabbing the suspend-count lock and
719 * performing both of our operations (check suspend count, set
720 * state) while holding it, now we need to grab a mutex on every
721 * transition to kRunnable.
722 *
723 * What we do instead is change the order of operations so that
724 * the transition to kRunnable happens first. If we then detect
725 * that the suspend count is nonzero, we switch to kSuspended.
726 *
727 * Appropriate compiler and memory barriers are required to ensure
728 * that the operations are observed in the expected order.
729 *
730 * This does create a small window of opportunity where a GC in
731 * progress could observe what appears to be a running thread (if
732 * it happens to look between when we set to kRunnable and when we
733 * switch to kSuspended). At worst this only affects assertions
734 * and thread logging. (We could work around it with some sort
735 * of intermediate "pre-running" state that is generally treated
736 * as equivalent to running, but that doesn't seem worthwhile.)
737 *
738 * We can also solve this by combining the "status" and "suspend
739 * count" fields into a single 32-bit value. This trades the
740 * store/load barrier on transition to kRunnable for an atomic RMW
741 * op on all transitions and all suspend count updates (also, all
742 * accesses to status or the thread count require bit-fiddling).
743 * It also eliminates the brief transition through kRunnable when
744 * the thread is supposed to be suspended. This is possibly faster
745 * on SMP and slightly more correct, but less convenient.
746 */
747 android_atomic_acquire_store(new_state, addr);
748 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
749 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
750 }
751 } else {
752 /*
753 * Not changing to Thread::kRunnable. No additional work required.
754 *
755 * We use a releasing store to ensure that, if we were runnable,
756 * any updates we previously made to objects on the managed heap
757 * will be observed before the state change.
758 */
759 android_atomic_release_store(new_state, addr);
760 }
761
762 return old_state;
763}
764
765void Thread::WaitUntilSuspended() {
766 // TODO: dalvik dropped the waiting thread's priority after a while.
767 // TODO: dalvik timed out and aborted.
768 useconds_t delay = 0;
769 while (GetState() == Thread::kRunnable) {
770 useconds_t new_delay = delay * 2;
771 CHECK_GE(new_delay, delay);
772 delay = new_delay;
773 if (delay == 0) {
774 sched_yield();
775 delay = 10000;
776 } else {
777 usleep(delay);
778 }
779 }
780}
781
Elliott Hughesbe759c62011-09-08 19:38:21 -0700782void Thread::ThreadExitCallback(void* arg) {
783 Thread* self = reinterpret_cast<Thread*>(arg);
784 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700785}
786
Elliott Hughesbe759c62011-09-08 19:38:21 -0700787void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700788 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700789 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700790
791 // Double-check the TLS slot allocation.
792 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700793 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700794 }
795
796 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700797}
798
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700799void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700800 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700801}
802
Elliott Hughesdcc24742011-09-07 14:02:44 -0700803Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700804 : peer_(NULL),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700805 wait_mutex_("Thread wait mutex"),
806 wait_monitor_(NULL),
807 interrupted_(false),
808 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700809 top_of_managed_stack_(),
810 native_to_managed_record_(NULL),
811 top_sirt_(NULL),
812 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700813 state_(Thread::kUnknown),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700814 exception_(NULL),
815 suspend_count_(0),
816 class_loader_override_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700817}
818
Elliott Hughes02b48d12011-09-07 17:15:51 -0700819void MonitorExitVisitor(const Object* object, void*) {
820 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700821 entered_monitor->MonitorExit();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700822}
823
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700824Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700825 // TODO: check we're not calling the JNI DetachCurrentThread function from
826 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
827
828 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700829 if (jni_env_ != NULL) {
830 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
831 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700832
833 if (IsExceptionPending()) {
834 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
835 }
836
837 // TODO: ThreadGroup.removeThread(this);
838
Elliott Hughes93e74e82011-09-13 11:07:03 -0700839 if (peer_ != NULL) {
840 SetVmData(peer_, NULL);
841 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700842
843 // TODO: say "bye" to the debugger.
844 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700845 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700846 //}
847
848 // Thread.join() is implemented as an Object.wait() on the Thread.lock
849 // object. Signal anyone who is waiting.
850 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
851 //dvmLockObject(self, lock);
852 //dvmObjectNotifyAll(self, lock);
853 //dvmUnlockObject(self, lock);
854 //lock = NULL;
855
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700856 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700857 jni_env_ = NULL;
858
859 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700860}
861
Ian Rogers408f79a2011-08-23 18:22:33 -0700862size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700863 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700864 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700865 count += cur->NumberOfReferences();
866 }
867 return count;
868}
869
Ian Rogers408f79a2011-08-23 18:22:33 -0700870bool Thread::SirtContains(jobject obj) {
871 Object** sirt_entry = reinterpret_cast<Object**>(obj);
872 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700873 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700874 // A SIRT should always have a jobject/jclass as a native method is passed
875 // in a this pointer or a class
876 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700877 if ((&cur->References()[0] <= sirt_entry) &&
878 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700879 return true;
880 }
881 }
882 return false;
883}
884
Ian Rogers408f79a2011-08-23 18:22:33 -0700885Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700886 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700887 if (obj == NULL) {
888 return NULL;
889 }
890 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
891 IndirectRefKind kind = GetIndirectRefKind(ref);
892 Object* result;
893 switch (kind) {
894 case kLocal:
895 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700896 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700897 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700898 break;
899 }
900 case kGlobal:
901 {
902 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
903 IndirectReferenceTable& globals = vm->globals;
904 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700905 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700906 break;
907 }
908 case kWeakGlobal:
909 {
910 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
911 IndirectReferenceTable& weak_globals = vm->weak_globals;
912 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700913 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700914 if (result == kClearedJniWeakGlobal) {
915 // This is a special case where it's okay to return NULL.
916 return NULL;
917 }
918 break;
919 }
920 case kSirtOrInvalid:
921 default:
922 // TODO: make stack indirect reference table lookup more efficient
923 // Check if this is a local reference in the SIRT
924 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700925 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700926 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700927 // Assume an invalid local reference is actually a direct pointer.
928 result = reinterpret_cast<Object*>(obj);
929 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700930 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700931 }
932 }
933
934 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700935 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
936 JniAbort(NULL);
937 } else {
938 if (result != kInvalidIndirectRefObject) {
939 Heap::VerifyObject(result);
940 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700941 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700942 return result;
943}
944
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700945class CountStackDepthVisitor : public Thread::StackVisitor {
946 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700947 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700948
949 virtual void VisitFrame(const Frame&) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700950 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700951 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700952
953 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700954 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700955 }
956
957 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700958 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700959};
960
Ian Rogersaaa20802011-09-11 21:47:37 -0700961//
962class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700963 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700964 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
965 // Allocate method trace with an extra slot that will hold the PC trace
966 method_trace_ = Runtime::Current()->GetClassLinker()->
967 AllocObjectArray<Object>(depth + 1);
968 // Register a local reference as IntArray::Alloc may trigger GC
969 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
970 pc_trace_ = IntArray::Alloc(depth);
971#ifdef MOVING_GARBAGE_COLLECTOR
972 // Re-read after potential GC
973 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
974#endif
975 // Save PC trace in last element of method trace, also places it into the
976 // object graph.
977 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700978 }
979
Ian Rogersaaa20802011-09-11 21:47:37 -0700980 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700981
Elliott Hughesd369bb72011-09-12 14:41:14 -0700982 virtual void VisitFrame(const Frame& frame) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700983 method_trace_->Set(count_, frame.GetMethod());
984 pc_trace_->Set(count_, frame.GetPC());
985 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700986 }
987
Ian Rogersaaa20802011-09-11 21:47:37 -0700988 jobject GetInternalStackTrace() const {
989 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700990 }
991
992 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700993 // Current position down stack trace
994 uint32_t count_;
995 // Array of return PC values
996 IntArray* pc_trace_;
997 // An array of the methods on the stack, the last entry is a reference to the
998 // PC trace
999 ObjectArray<Object>* method_trace_;
1000 // Local indirect reference table entry for method trace
1001 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001002};
1003
Ian Rogersaaa20802011-09-11 21:47:37 -07001004void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001005 Frame frame = GetTopOfStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001006 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1007 // CHECK(native_to_managed_record_ != NULL);
1008 NativeToManagedRecord* record = native_to_managed_record_;
1009
1010 while (frame.GetSP()) {
1011 for ( ; frame.GetMethod() != 0; frame.Next()) {
1012 visitor->VisitFrame(frame);
1013 }
1014 if (record == NULL) {
1015 break;
1016 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001017 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack)); // last_tos should return Frame instead of sp?
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001018 record = record->link;
1019 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001020}
1021
Ian Rogersaaa20802011-09-11 21:47:37 -07001022jobject Thread::CreateInternalStackTrace() const {
1023 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001024 CountStackDepthVisitor count_visitor;
1025 WalkStack(&count_visitor);
1026 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001027
Ian Rogersaaa20802011-09-11 21:47:37 -07001028 // Transition into runnable state to work on Object*/Array*
1029 ScopedJniThreadState ts(jni_env_);
1030
1031 // Build internal stack trace
1032 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001033 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001034
Ian Rogersaaa20802011-09-11 21:47:37 -07001035 return build_trace_visitor.GetInternalStackTrace();
1036}
1037
1038jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1039 JNIEnv* env) {
1040 // Transition into runnable state to work on Object*/Array*
1041 ScopedJniThreadState ts(env);
1042
1043 // Decode the internal stack trace into the depth, method trace and PC trace
1044 ObjectArray<Object>* method_trace =
1045 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1046 int32_t depth = method_trace->GetLength()-1;
1047 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1048
1049 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1050
1051 // Create java_trace array and place in local reference table
1052 ObjectArray<StackTraceElement>* java_traces =
1053 class_linker->AllocStackTraceElementArray(depth);
1054 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001055
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001056 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001057 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1058 Method* method = down_cast<Method*>(method_trace->Get(i));
1059 uint32_t native_pc = pc_trace->Get(i);
1060 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001061 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -07001062 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001063 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001064
Ian Rogersaaa20802011-09-11 21:47:37 -07001065 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001066 StackTraceElement* obj =
1067 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -07001068 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001069 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001070 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001071 method->ToDexPC(native_pc)));
1072#ifdef MOVING_GARBAGE_COLLECTOR
1073 // Re-read after potential GC
1074 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1075 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1076 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1077#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001078 java_traces->Set(i, obj);
1079 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001080 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001081}
1082
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001083void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001084 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001085 va_list args;
1086 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001087 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001088 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001089
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001090 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001091 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001092 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001093 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001094 descriptor.erase(descriptor.length() - 1);
1095
1096 JNIEnv* env = GetJniEnv();
1097 jclass exception_class = env->FindClass(descriptor.c_str());
1098 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1099 int rc = env->ThrowNew(exception_class, msg.c_str());
1100 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001101}
1102
Elliott Hughes79082e32011-08-25 12:07:32 -07001103void Thread::ThrowOutOfMemoryError() {
1104 UNIMPLEMENTED(FATAL);
1105}
1106
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001107Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
1108 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1109 DCHECK(class_linker != NULL);
1110
1111 Frame cur_frame = GetTopOfStack();
1112 for (int unwind_depth = 0; ; unwind_depth++) {
1113 const Method* cur_method = cur_frame.GetMethod();
1114 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
1115 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1116
1117 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
1118 throw_pc,
1119 dex_file,
1120 class_linker);
1121 if (handler_addr) {
1122 *handler_pc = handler_addr;
1123 return cur_frame;
1124 } else {
1125 // Check if we are at the last frame
1126 if (cur_frame.HasNext()) {
1127 cur_frame.Next();
1128 } else {
1129 // Either at the top of stack or next frame is native.
1130 break;
1131 }
1132 }
1133 }
1134 *handler_pc = NULL;
1135 return Frame();
1136}
1137
1138void* Thread::FindExceptionHandlerInMethod(const Method* method,
1139 void* throw_pc,
1140 const DexFile& dex_file,
1141 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001142 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001143 exception_ = NULL;
1144
1145 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001146 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001147 DexFile::CatchHandlerIterator iter;
1148 for (iter = dex_file.dexFindCatchHandler(*code_item,
1149 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
1150 !iter.HasNext();
1151 iter.Next()) {
1152 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
1153 DCHECK(klass != NULL);
1154 if (exception_obj->InstanceOf(klass)) {
1155 dex_pc = iter.Get().address_;
1156 break;
1157 }
1158 }
1159
1160 exception_ = exception_obj;
1161 if (iter.HasNext()) {
1162 return NULL;
1163 } else {
1164 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
1165 }
1166}
1167
Elliott Hughes410c0c82011-09-01 17:58:25 -07001168void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001169 if (exception_ != NULL) {
1170 visitor(exception_, arg);
1171 }
1172 if (peer_ != NULL) {
1173 visitor(peer_, arg);
1174 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001175 jni_env_->locals.VisitRoots(visitor, arg);
1176 jni_env_->monitors.VisitRoots(visitor, arg);
1177 // visitThreadStack(visitor, thread, arg);
1178 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1179}
1180
Ian Rogersb033c752011-07-20 12:22:35 -07001181static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001182 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001183 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001184 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001185 "Blocked",
1186 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001187 "Initializing",
1188 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001189 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001190 "VmWait",
1191 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001192};
1193std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001194 int int_state = static_cast<int>(state);
1195 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1196 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001197 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001198 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001199 }
1200 return os;
1201}
1202
Elliott Hughes330304d2011-08-12 14:28:05 -07001203std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1204 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001205 << ",pthread_t=" << thread.GetImpl()
1206 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001207 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001208 << ",state=" << thread.GetState()
1209 << ",peer=" << thread.GetPeer()
1210 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001211 return os;
1212}
1213
Elliott Hughes8daa0922011-09-11 13:46:25 -07001214} // namespace art