blob: 49200c2cb3d4e5c89246289336e800b1887eff03 [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
21#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070030#include "context.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070031#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070032#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070033#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070035#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070036#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070037#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070038#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070039
40namespace art {
41
42pthread_key_t Thread::pthread_key_self_;
43
Elliott Hughes29f27422011-09-18 16:02:18 -070044static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070045static Field* gThread_daemon = NULL;
46static Field* gThread_group = NULL;
47static Field* gThread_lock = NULL;
48static Field* gThread_name = NULL;
49static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070050static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070051static Field* gThread_vmData = NULL;
52static Field* gThreadGroup_name = NULL;
53static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070054static Method* gThreadGroup_removeThread = NULL;
55static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070056
buzbee4a3164f2011-09-03 11:25:10 -070057// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070058void DebugMe(Method* method, uint32_t info) {
Elliott Hughes01158d72011-09-19 19:47:10 -070059 LOG(INFO) << "DebugMe";
60 if (method != NULL) {
61 LOG(INFO) << PrettyMethod(method);
62 }
63 LOG(INFO) << "Info: " << info;
buzbee4a3164f2011-09-03 11:25:10 -070064}
65
Ian Rogersbdb03912011-09-14 00:55:44 -070066// Called by generated call to throw an exception
Ian Rogersff1ed472011-09-20 13:46:24 -070067extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070068 /*
69 * exception may be NULL, in which case this routine should
70 * throw NPE. NOTE: this is a convenience for generated code,
71 * which previously did the null check inline and constructed
72 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070073 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070074 */
Ian Rogers67375ac2011-09-14 00:55:44 -070075 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070076 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogersbdb03912011-09-14 00:55:44 -070077 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070078 if (exception == NULL) {
79 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
Ian Rogersff1ed472011-09-20 13:46:24 -070080 } else {
81 thread->SetException(exception);
Ian Rogers93dd9662011-09-17 23:21:22 -070082 }
Ian Rogersff1ed472011-09-20 13:46:24 -070083 thread->DeliverException();
84}
85
86// Deliver an exception that's pending on thread helping set up a callee save frame on the way
87extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
88 *sp = Runtime::Current()->GetCalleeSaveMethod();
89 thread->SetTopOfStack(sp, 0);
90 thread->DeliverException();
buzbee1b4c8592011-08-31 10:43:51 -070091}
92
Ian Rogers9651f422011-09-19 20:26:07 -070093// Called by generated call to throw a NPE exception
Ian Rogersff1ed472011-09-20 13:46:24 -070094extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -070095 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070096 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -070097 thread->SetTopOfStack(sp, 0);
98 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
Ian Rogersff1ed472011-09-20 13:46:24 -070099 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700100}
101
102// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700103extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700104 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700105 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700106 thread->SetTopOfStack(sp, 0);
107 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
Ian Rogersff1ed472011-09-20 13:46:24 -0700108 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700109}
110
111// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700112extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700113 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700114 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700115 thread->SetTopOfStack(sp, 0);
116 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
117 "length=%d; index=%d", limit, index);
Ian Rogersff1ed472011-09-20 13:46:24 -0700118 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700119}
120
Ian Rogersff1ed472011-09-20 13:46:24 -0700121// Called by the AbstractMethodError stub (not runtime support)
122void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
123 *sp = Runtime::Current()->GetCalleeSaveMethod();
124 thread->SetTopOfStack(sp, 0);
Ian Rogersa0841a82011-09-22 14:16:31 -0700125 thread->ThrowNewException("Ljava/lang/AbstractMethodError;",
Ian Rogersff1ed472011-09-20 13:46:24 -0700126 "abstract method \"%s\"",
127 PrettyMethod(method).c_str());
128 thread->DeliverException();
129}
130
Ian Rogers932746a2011-09-22 18:57:50 -0700131extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
132 // Place a special frame at the TOS that will save all callee saves
133 Runtime* runtime = Runtime::Current();
134 *sp = runtime->GetCalleeSaveMethod();
135 thread->SetTopOfStack(sp, 0);
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700136 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Ian Rogers932746a2011-09-22 18:57:50 -0700137 thread->ThrowNewException("Ljava/lang/StackOverflowError;",
138 "stack size %zdkb; default stack size: %zdkb",
139 thread->GetStackSize() / KB, runtime->GetDefaultStackSize() / KB);
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700140 thread->ResetDefaultStackEnd(); // Return to default stack size
Ian Rogers932746a2011-09-22 18:57:50 -0700141 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700142}
143
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700144extern "C" void artThrowVerificationErrorFromCode(int32_t src1, int32_t ref, Thread* thread, Method** sp) {
145 // Place a special frame at the TOS that will save all callee saves
146 Runtime* runtime = Runtime::Current();
147 *sp = runtime->GetCalleeSaveMethod();
148 thread->SetTopOfStack(sp, 0);
149 LOG(WARNING) << "TODO: verifcation error detail message. src1=" << src1 << " ref=" << ref;
150 thread->ThrowNewException("Ljava/lang/VerifyError;",
151 "TODO: verifcation error detail message. src1=%d; ref=%d", src1, ref);
152 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700153}
154
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700155extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
156 // Place a special frame at the TOS that will save all callee saves
157 Runtime* runtime = Runtime::Current();
158 *sp = runtime->GetCalleeSaveMethod();
159 thread->SetTopOfStack(sp, 0);
160 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
161 thread->ThrowNewException("Ljava/lang/InternalError;", "errnum=%d", errnum);
162 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700163}
164
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700165extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
166 // Place a special frame at the TOS that will save all callee saves
167 Runtime* runtime = Runtime::Current();
168 *sp = runtime->GetCalleeSaveMethod();
169 thread->SetTopOfStack(sp, 0);
170 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
171 thread->ThrowNewException("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
172 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700173}
174
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700175extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* thread, Method** sp) {
176 // Place a special frame at the TOS that will save all callee saves
177 Runtime* runtime = Runtime::Current();
178 *sp = runtime->GetCalleeSaveMethod();
179 thread->SetTopOfStack(sp, 0);
180 LOG(WARNING) << "TODO: no such method exception detail message. method_idx=" << method_idx;
181 thread->ThrowNewException("Ljava/lang/NoSuchMethodError;", "method_idx=%d", method_idx);
182 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700183}
184
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700185extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
186 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
187 // Place a special frame at the TOS that will save all callee saves
188 Runtime* runtime = Runtime::Current();
189 *sp = runtime->GetCalleeSaveMethod();
190 thread->SetTopOfStack(sp, 0);
191 thread->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d", size);
192 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700193}
Ian Rogersbdb03912011-09-14 00:55:44 -0700194
buzbee1b4c8592011-08-31 10:43:51 -0700195// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700196Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700197 /*
198 * Should initialize & fix up method->dex_cache_resolved_types_[].
199 * Returns initialized type. Does not return normally if an exception
200 * is thrown, but instead initiates the catch. Should be similar to
201 * ClassLinker::InitializeStaticStorageFromCode.
202 */
203 UNIMPLEMENTED(FATAL);
204 return NULL;
205}
206
buzbee561227c2011-09-02 15:28:19 -0700207// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700208void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700209 /*
210 * Slow-path handler on invoke virtual method path in which
211 * base method is unresolved at compile-time. Doesn't need to
212 * return anything - just either ensure that
213 * method->dex_cache_resolved_methods_(method_idx) != NULL or
214 * throw and unwind. The caller will restart call sequence
215 * from the beginning.
216 */
217}
218
Ian Rogers21d9e832011-09-23 17:05:09 -0700219// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
220// cannot be resolved, throw an error. If it can, use it to create an instance.
221extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method) {
222 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
223 if (klass == NULL) {
224 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
225 if (klass == NULL) {
226 DCHECK(Thread::Current()->IsExceptionPending());
227 return NULL; // Failure
228 }
229 }
230 return klass->AllocObject();
231}
232
Ian Rogersb886da82011-09-23 16:27:54 -0700233// Helper function to alloc array for OP_FILLED_NEW_ARRAY
234extern "C" Array* artCheckAndArrayAllocFromCode(uint32_t type_idx, Method* method,
235 int32_t component_count) {
236 if (component_count < 0) {
237 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
238 component_count);
239 return NULL; // Failure
240 }
241 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
242 if (klass == NULL) { // Not in dex cache so try to resolve
243 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
244 if (klass == NULL) { // Error
245 DCHECK(Thread::Current()->IsExceptionPending());
246 return NULL; // Failure
247 }
248 }
249 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
250 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
251 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
252 "Bad filled array request for type %s",
253 PrettyDescriptor(klass->GetDescriptor()).c_str());
254 } else {
255 Thread::Current()->ThrowNewException("Ljava/lang/InternalError;",
256 "Found type %s; filled-new-array not implemented for anything but \'int\'",
257 PrettyDescriptor(klass->GetDescriptor()).c_str());
258 }
259 return NULL; // Failure
260 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700261 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700262 return Array::Alloc(klass, component_count);
263 }
264}
265
266// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
267// it cannot be resolved, throw an error. If it can, use it to create an array.
268extern "C" Array* artArrayAllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
269 if (component_count < 0) {
270 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
271 component_count);
272 return NULL; // Failure
273 }
274 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
275 if (klass == NULL) { // Not in dex cache so try to resolve
276 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
277 if (klass == NULL) { // Error
278 DCHECK(Thread::Current()->IsExceptionPending());
279 return NULL; // Failure
280 }
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700281 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700282 }
283 return Array::Alloc(klass, component_count);
buzbee1da522d2011-09-04 11:22:20 -0700284}
285
Ian Rogerse51a5112011-09-23 14:16:35 -0700286// Check whether it is safe to cast one class to the other, throw exception and return -1 on failure
Ian Rogersff1ed472011-09-20 13:46:24 -0700287extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700288 DCHECK(a->IsClass()) << PrettyClass(a);
289 DCHECK(b->IsClass()) << PrettyClass(b);
Brian Carlstromc2282522011-09-17 10:33:14 -0700290 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700291 return 0; // Success
292 } else {
293 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700294 "%s cannot be cast to %s",
295 PrettyDescriptor(a->GetDescriptor()).c_str(),
296 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700297 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700298 }
buzbee2a475e72011-09-07 17:19:17 -0700299}
300
Ian Rogerse51a5112011-09-23 14:16:35 -0700301// Tests whether 'element' can be assigned into an array of type 'array_class'.
302// Returns 0 on success and -1 if an exception is pending.
303extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
304 DCHECK(array_class != NULL);
305 // element can't be NULL as we catch this is screened in runtime_support
306 Class* element_class = element->GetClass();
307 Class* component_type = array_class->GetComponentType();
308 if (component_type->IsAssignableFrom(element_class)) {
309 return 0; // Success
310 } else {
311 Thread::Current()->ThrowNewException("Ljava/lang/ArrayStoreException;",
Ian Rogersb886da82011-09-23 16:27:54 -0700312 "Cannot store an object of type %s in to an array of type %s",
313 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
314 PrettyDescriptor(array_class->GetDescriptor()).c_str());
Ian Rogerse51a5112011-09-23 14:16:35 -0700315 return -1; // Failure
316 }
317}
318
Ian Rogersff1ed472011-09-20 13:46:24 -0700319extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
320 DCHECK(obj != NULL); // Assumed to have been checked before entry
321 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700322}
323
Elliott Hughesd369bb72011-09-12 14:41:14 -0700324void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700325 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700326 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700327 DCHECK(thread->HoldsLock(obj));
328 // Only possible exception is NPE and is handled before entry
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700329 DCHECK(!thread->IsExceptionPending());
buzbee2a475e72011-09-07 17:19:17 -0700330}
331
buzbeec1f45042011-09-21 16:03:19 -0700332extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700333 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700334}
335
buzbee5ade1d22011-09-09 14:44:52 -0700336/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700337 * Fill the array with predefined constant values, throwing exceptions if the array is null or
338 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700339 *
340 * NOTE: When dealing with a raw dex file, the data to be copied uses
341 * little-endian ordering. Require that oat2dex do any required swapping
342 * so this routine can get by with a memcpy().
343 *
344 * Format of the data:
345 * ushort ident = 0x0300 magic value
346 * ushort width width of each element in the table
347 * uint size number of elements in the table
348 * ubyte data[size*width] table of data values (may contain a single-byte
349 * padding at the end)
350 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700351extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
352 DCHECK_EQ(table[0], 0x0300);
353 if (array == NULL) {
354 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
355 "null array in fill array");
356 return -1; // Error
357 }
358 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
359 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
360 if (static_cast<int32_t>(size) > array->GetLength()) {
361 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
362 "failed array fill. length=%d; index=%d",
363 array->GetLength(), size);
364 return -1; // Error
365 }
366 uint16_t width = table[1];
367 uint32_t size_in_bytes = size * width;
368 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
369 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700370}
371
372// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700373extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
374 Object* this_object ,
375 Method* caller_method) {
376 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700377 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700378 thread->ThrowNewException("Ljava/lang/NullPointerException;",
379 "null receiver during interface dispatch");
380 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700381 }
382 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
383 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
384 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700385 // Could not resolve interface method. Throw error and unwind
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700386 CHECK(thread->IsExceptionPending());
Ian Rogersff1ed472011-09-20 13:46:24 -0700387 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700388 }
389 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700390 if (method == NULL) {
391 CHECK(thread->IsExceptionPending());
392 return 0;
393 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700394 const void* code = method->GetCode();
395
396 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
397 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
398 uint64_t result = ((code_uint << 32) | method_uint);
399 return result;
400}
401
buzbee5ade1d22011-09-09 14:44:52 -0700402// TODO: move to more appropriate location
403/*
404 * Float/double conversion requires clamping to min and max of integer form. If
405 * target doesn't support this normally, use these.
406 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700407int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700408 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
409 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
410 if (d >= kMaxLong)
411 return (int64_t)0x7fffffffffffffffULL;
412 else if (d <= kMinLong)
413 return (int64_t)0x8000000000000000ULL;
414 else if (d != d) // NaN case
415 return 0;
416 else
417 return (int64_t)d;
418}
419
Elliott Hughesd369bb72011-09-12 14:41:14 -0700420int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700421 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
422 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
423 if (f >= kMaxLong)
424 return (int64_t)0x7fffffffffffffffULL;
425 else if (f <= kMinLong)
426 return (int64_t)0x8000000000000000ULL;
427 else if (f != f) // NaN case
428 return 0;
429 else
430 return (int64_t)f;
431}
432
Brian Carlstrom16192862011-09-12 17:50:06 -0700433// Return value helper for jobject return types
434static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
435 return thread->DecodeJObject(obj);
436}
437
buzbee3ea4ec52011-08-22 17:37:19 -0700438void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700439#if defined(__arm__)
440 pShlLong = art_shl_long;
441 pShrLong = art_shr_long;
442 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700443 pIdiv = __aeabi_idiv;
444 pIdivmod = __aeabi_idivmod;
445 pI2f = __aeabi_i2f;
446 pF2iz = __aeabi_f2iz;
447 pD2f = __aeabi_d2f;
448 pF2d = __aeabi_f2d;
449 pD2iz = __aeabi_d2iz;
450 pL2f = __aeabi_l2f;
451 pL2d = __aeabi_l2d;
452 pFadd = __aeabi_fadd;
453 pFsub = __aeabi_fsub;
454 pFdiv = __aeabi_fdiv;
455 pFmul = __aeabi_fmul;
456 pFmodf = fmodf;
457 pDadd = __aeabi_dadd;
458 pDsub = __aeabi_dsub;
459 pDdiv = __aeabi_ddiv;
460 pDmul = __aeabi_dmul;
461 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700462 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700463 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700464 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700465 pArrayAllocFromCode = art_array_alloc_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700466 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700467 pCheckAndArrayAllocFromCode = art_check_and_array_alloc_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700468 pCheckCastFromCode = art_check_cast_from_code;
469 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700470 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700471 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700472 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700473 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
474 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700475 pThrowInternalErrorFromCode = art_throw_internal_error_from_code;
476 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
477 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700478 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700479 pThrowRuntimeExceptionFromCode = art_throw_runtime_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700480 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700481 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700482 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700483#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700484 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700485 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700486 pF2l = F2L;
487 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700488 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700489 pGet32Static = Field::Get32StaticFromCode;
490 pSet32Static = Field::Set32StaticFromCode;
491 pGet64Static = Field::Get64StaticFromCode;
492 pSet64Static = Field::Set64StaticFromCode;
493 pGetObjStatic = Field::GetObjStaticFromCode;
494 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700495 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700496 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700497 pInstanceofNonTrivialFromCode = Object::InstanceOf;
buzbee2a475e72011-09-07 17:19:17 -0700498 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700499 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700500 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700501 pFindNativeMethod = FindNativeMethod;
502 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700503 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700504}
505
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700506void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700507 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
508 DCHECK_NE(frame_size, 0u);
509 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700510 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511 sp_ = reinterpret_cast<Method**>(next_sp);
Elliott Hughes80609252011-09-23 17:24:51 -0700512 if (*sp_ != NULL) {
513 DCHECK((*sp_)->GetClass() == Method::GetMethodClass() ||
514 (*sp_)->GetClass() == Method::GetConstructorClass());
Ian Rogersff1ed472011-09-20 13:46:24 -0700515 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700516}
517
Ian Rogers90865722011-09-19 11:11:44 -0700518bool Frame::HasMethod() const {
519 return GetMethod() != NULL && (!GetMethod()->IsPhony());
520}
521
Ian Rogersbdb03912011-09-14 00:55:44 -0700522uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700523 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700524 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700525}
526
Ian Rogersbdb03912011-09-14 00:55:44 -0700527uintptr_t Frame::LoadCalleeSave(int num) const {
528 // Callee saves are held at the top of the frame
529 Method* method = GetMethod();
530 DCHECK(method != NULL);
531 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700532 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700533#if defined(__i386__)
534 save_addr -= kPointerSize; // account for return address
535#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700536 return *reinterpret_cast<uintptr_t*>(save_addr);
537}
538
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700539Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700540 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700541 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700543}
544
Brian Carlstrom78128a62011-09-15 17:21:19 -0700545void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700546 Thread* self = reinterpret_cast<Thread*>(arg);
547 Runtime* runtime = Runtime::Current();
548
549 self->Attach(runtime);
550
Elliott Hughes038a8062011-09-18 14:12:41 -0700551 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700552 if (thread_name != NULL) {
553 SetThreadName(thread_name->ToModifiedUtf8().c_str());
554 }
555
556 // Wait until it's safe to start running code. (There may have been a suspend-all
557 // in progress while we were starting up.)
558 runtime->GetThreadList()->WaitForGo();
559
560 // TODO: say "hi" to the debugger.
561 //if (gDvm.debuggerConnected) {
562 // dvmDbgPostThreadStart(self);
563 //}
564
565 // Invoke the 'run' method of our java.lang.Thread.
566 CHECK(self->peer_ != NULL);
567 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700568 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700569 m->Invoke(self, receiver, NULL, NULL);
570
571 // Detach.
572 runtime->GetThreadList()->Unregister();
573
Carl Shapirob5573532011-07-12 18:22:59 -0700574 return NULL;
575}
576
Elliott Hughes93e74e82011-09-13 11:07:03 -0700577void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700578 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700579}
580
Elliott Hughes01158d72011-09-19 19:47:10 -0700581Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
582 Object* thread = Decode<Object*>(env, java_thread);
583 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
584}
585
Elliott Hughesd369bb72011-09-12 14:41:14 -0700586void Thread::Create(Object* peer, size_t stack_size) {
587 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700588
Elliott Hughesd369bb72011-09-12 14:41:14 -0700589 if (stack_size == 0) {
590 stack_size = Runtime::Current()->GetDefaultStackSize();
591 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700592
Elliott Hughes93e74e82011-09-13 11:07:03 -0700593 Thread* native_thread = new Thread;
594 native_thread->peer_ = peer;
595
596 // Thread.start is synchronized, so we know that vmData is 0,
597 // and know that we're not racing to assign it.
598 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700599
600 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700601 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
602 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
603 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
604 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
605 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700606
607 // Let the child know when it's safe to start running.
608 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700609}
610
Elliott Hughes93e74e82011-09-13 11:07:03 -0700611void Thread::Attach(const Runtime* runtime) {
612 InitCpu();
613 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700614
Elliott Hughes93e74e82011-09-13 11:07:03 -0700615 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700616
Elliott Hughes93e74e82011-09-13 11:07:03 -0700617 tid_ = ::art::GetTid();
618 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700619
Elliott Hughes93e74e82011-09-13 11:07:03 -0700620 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700621
Elliott Hughes8d768a92011-09-14 16:35:25 -0700622 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700623
Elliott Hughes93e74e82011-09-13 11:07:03 -0700624 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700625
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700626 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700627}
628
629Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700630 LOG(INFO) << "Thread::Attach '" << name << "'";
Elliott Hughes93e74e82011-09-13 11:07:03 -0700631 Thread* self = new Thread;
632 self->Attach(runtime);
633
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700634 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700635
636 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700637
638 // If we're the main thread, ClassLinker won't be created until after we're attached,
639 // so that thread needs a two-stage attach. Regular threads don't need this hack.
640 if (self->thin_lock_id_ != ThreadList::kMainId) {
641 self->CreatePeer(name, as_daemon);
642 }
643
644 return self;
645}
646
Elliott Hughesd369bb72011-09-12 14:41:14 -0700647jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
648 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
649 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
650 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
651 // This will be null in the compiler (and tests), but never in a running system.
652 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
653 return thread_group;
654}
655
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700656void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700657 JNIEnv* env = jni_env_;
658
Elliott Hughesd369bb72011-09-12 14:41:14 -0700659 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
660 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700661 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700662 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700663 jboolean thread_is_daemon = as_daemon;
664
665 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700666 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700667
Elliott Hughes8daa0922011-09-11 13:46:25 -0700668 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700669 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700670 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700671
672 // Because we mostly run without code available (in the compiler, in tests), we
673 // manually assign the fields the constructor should have set.
674 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700675 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
676 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
677 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
678 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700679}
680
Elliott Hughesbe759c62011-09-08 19:38:21 -0700681void Thread::InitStackHwm() {
682 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700683 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700684
Ian Rogers932746a2011-09-22 18:57:50 -0700685 void* temp_stack_base;
686 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
687 __FUNCTION__);
688 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700689
Ian Rogers932746a2011-09-22 18:57:50 -0700690 if (stack_size_ <= kStackOverflowReservedBytes) {
691 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700692 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700693
Ian Rogers932746a2011-09-22 18:57:50 -0700694 // Set stack_end_ to the bottom of the stack saving space of stack overflows
695 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700696
697 // Sanity check.
698 int stack_variable;
699 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700700
Elliott Hughes8d768a92011-09-14 16:35:25 -0700701 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700702}
703
Elliott Hughesa0957642011-09-02 14:27:33 -0700704void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700705 DumpState(os);
706 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700707}
708
Elliott Hughesd92bec42011-09-02 17:04:36 -0700709std::string GetSchedulerGroup(pid_t tid) {
710 // /proc/<pid>/group looks like this:
711 // 2:devices:/
712 // 1:cpuacct,cpu:/
713 // We want the third field from the line whose second field contains the "cpu" token.
714 std::string cgroup_file;
715 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
716 return "";
717 }
718 std::vector<std::string> cgroup_lines;
719 Split(cgroup_file, '\n', cgroup_lines);
720 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
721 std::vector<std::string> cgroup_fields;
722 Split(cgroup_lines[i], ':', cgroup_fields);
723 std::vector<std::string> cgroups;
724 Split(cgroup_fields[1], ',', cgroups);
725 for (size_t i = 0; i < cgroups.size(); ++i) {
726 if (cgroups[i] == "cpu") {
727 return cgroup_fields[2].substr(1); // Skip the leading slash.
728 }
729 }
730 }
731 return "";
732}
733
734void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700735 std::string thread_name("<native thread without managed peer>");
736 std::string group_name;
737 int priority;
738 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700739
Elliott Hughesd369bb72011-09-12 14:41:14 -0700740 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700741 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700742 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700743 priority = gThread_priority->GetInt(peer_);
744 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700745
Elliott Hughes038a8062011-09-18 14:12:41 -0700746 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700747 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700748 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700749 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
750 }
751 } else {
752 // 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 -0700753 std::string stats;
754 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
755 size_t start = stats.find('(') + 1;
756 size_t end = stats.find(')') - start;
757 thread_name = stats.substr(start, end);
758 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700759 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700760 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700761
762 int policy;
763 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700764 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700765
766 std::string scheduler_group(GetSchedulerGroup(GetTid()));
767 if (scheduler_group.empty()) {
768 scheduler_group = "default";
769 }
770
Elliott Hughesd92bec42011-09-02 17:04:36 -0700771 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700772 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700773 os << " daemon";
774 }
775 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700776 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700777 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700778
Elliott Hughesd92bec42011-09-02 17:04:36 -0700779 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700780 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700781 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700782 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700783 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700784 << " self=" << reinterpret_cast<const void*>(this) << "\n";
785 os << " | sysTid=" << GetTid()
786 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
787 << " sched=" << policy << "/" << sp.sched_priority
788 << " cgrp=" << scheduler_group
789 << " handle=" << GetImpl() << "\n";
790
791 // Grab the scheduler stats for this thread.
792 std::string scheduler_stats;
793 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
794 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
795 } else {
796 scheduler_stats = "0 0 0";
797 }
798
799 int utime = 0;
800 int stime = 0;
801 int task_cpu = 0;
802 std::string stats;
803 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
804 // Skip the command, which may contain spaces.
805 stats = stats.substr(stats.find(')') + 2);
806 // Extract the three fields we care about.
807 std::vector<std::string> fields;
808 Split(stats, ' ', fields);
809 utime = strtoull(fields[11].c_str(), NULL, 10);
810 stime = strtoull(fields[12].c_str(), NULL, 10);
811 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
812 }
813
814 os << " | schedstat=( " << scheduler_stats << " )"
815 << " utm=" << utime
816 << " stm=" << stime
817 << " core=" << task_cpu
818 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
819}
820
Elliott Hughesd369bb72011-09-12 14:41:14 -0700821struct StackDumpVisitor : public Thread::StackVisitor {
822 StackDumpVisitor(std::ostream& os) : os(os) {
823 }
824
Ian Rogersbdb03912011-09-14 00:55:44 -0700825 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700826 }
827
Ian Rogersbdb03912011-09-14 00:55:44 -0700828 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700829 if (!frame.HasMethod()) {
830 return;
831 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700832 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
833
834 Method* m = frame.GetMethod();
835 Class* c = m->GetDeclaringClass();
836 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
837
838 os << " at " << PrettyMethod(m, false);
839 if (m->IsNative()) {
840 os << "(Native method)";
841 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700842 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700843 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
844 }
845 os << "\n";
846 }
847
848 std::ostream& os;
849};
850
Elliott Hughesd92bec42011-09-02 17:04:36 -0700851void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700852 StackDumpVisitor dumper(os);
853 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700854}
855
Elliott Hughes8d768a92011-09-14 16:35:25 -0700856Thread::State Thread::SetState(Thread::State new_state) {
857 Thread::State old_state = state_;
858 if (old_state == new_state) {
859 return old_state;
860 }
861
862 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
863 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
864
865 if (new_state == Thread::kRunnable) {
866 /*
867 * Change our status to Thread::kRunnable. The transition requires
868 * that we check for pending suspension, because the VM considers
869 * us to be "asleep" in all other states, and another thread could
870 * be performing a GC now.
871 *
872 * The order of operations is very significant here. One way to
873 * do this wrong is:
874 *
875 * GCing thread Our thread (in kNative)
876 * ------------ ----------------------
877 * check suspend count (== 0)
878 * SuspendAllThreads()
879 * grab suspend-count lock
880 * increment all suspend counts
881 * release suspend-count lock
882 * check thread state (== kNative)
883 * all are suspended, begin GC
884 * set state to kRunnable
885 * (continue executing)
886 *
887 * We can correct this by grabbing the suspend-count lock and
888 * performing both of our operations (check suspend count, set
889 * state) while holding it, now we need to grab a mutex on every
890 * transition to kRunnable.
891 *
892 * What we do instead is change the order of operations so that
893 * the transition to kRunnable happens first. If we then detect
894 * that the suspend count is nonzero, we switch to kSuspended.
895 *
896 * Appropriate compiler and memory barriers are required to ensure
897 * that the operations are observed in the expected order.
898 *
899 * This does create a small window of opportunity where a GC in
900 * progress could observe what appears to be a running thread (if
901 * it happens to look between when we set to kRunnable and when we
902 * switch to kSuspended). At worst this only affects assertions
903 * and thread logging. (We could work around it with some sort
904 * of intermediate "pre-running" state that is generally treated
905 * as equivalent to running, but that doesn't seem worthwhile.)
906 *
907 * We can also solve this by combining the "status" and "suspend
908 * count" fields into a single 32-bit value. This trades the
909 * store/load barrier on transition to kRunnable for an atomic RMW
910 * op on all transitions and all suspend count updates (also, all
911 * accesses to status or the thread count require bit-fiddling).
912 * It also eliminates the brief transition through kRunnable when
913 * the thread is supposed to be suspended. This is possibly faster
914 * on SMP and slightly more correct, but less convenient.
915 */
916 android_atomic_acquire_store(new_state, addr);
917 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
918 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
919 }
920 } else {
921 /*
922 * Not changing to Thread::kRunnable. No additional work required.
923 *
924 * We use a releasing store to ensure that, if we were runnable,
925 * any updates we previously made to objects on the managed heap
926 * will be observed before the state change.
927 */
928 android_atomic_release_store(new_state, addr);
929 }
930
931 return old_state;
932}
933
934void Thread::WaitUntilSuspended() {
935 // TODO: dalvik dropped the waiting thread's priority after a while.
936 // TODO: dalvik timed out and aborted.
937 useconds_t delay = 0;
938 while (GetState() == Thread::kRunnable) {
939 useconds_t new_delay = delay * 2;
940 CHECK_GE(new_delay, delay);
941 delay = new_delay;
942 if (delay == 0) {
943 sched_yield();
944 delay = 10000;
945 } else {
946 usleep(delay);
947 }
948 }
949}
950
Elliott Hughesbe759c62011-09-08 19:38:21 -0700951void Thread::ThreadExitCallback(void* arg) {
952 Thread* self = reinterpret_cast<Thread*>(arg);
953 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700954}
955
Elliott Hughesbe759c62011-09-08 19:38:21 -0700956void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700957 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700958 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700959
960 // Double-check the TLS slot allocation.
961 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700962 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700963 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700964}
Carl Shapirob5573532011-07-12 18:22:59 -0700965
Elliott Hughes038a8062011-09-18 14:12:41 -0700966void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700967 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
968 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
969 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
970 Class* int_class = class_linker->FindPrimitiveClass('I');
971 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
972 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
973 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
974 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
Elliott Hughes29f27422011-09-18 16:02:18 -0700975 Class* UncaughtExceptionHandler_class = class_linker->FindSystemClass("Ljava/lang/Thread$UncaughtExceptionHandler;");
976 gThrowable = class_linker->FindSystemClass("Ljava/lang/Throwable;");
Elliott Hughes038a8062011-09-18 14:12:41 -0700977 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
978 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
979 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
980 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
981 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
982 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
Elliott Hughes29f27422011-09-18 16:02:18 -0700983 gThread_uncaughtHandler = Thread_class->FindDeclaredInstanceField("uncaughtHandler", UncaughtExceptionHandler_class);
Elliott Hughes038a8062011-09-18 14:12:41 -0700984 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
985 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Elliott Hughes29f27422011-09-18 16:02:18 -0700986 gThreadGroup_removeThread = ThreadGroup_class->FindVirtualMethod("removeThread", "(Ljava/lang/Thread;)V");
987 gUncaughtExceptionHandler_uncaughtException =
988 UncaughtExceptionHandler_class->FindVirtualMethod("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700989
990 // Finish attaching the main thread.
991 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700992}
993
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700994void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700995 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700996}
997
Elliott Hughesdcc24742011-09-07 14:02:44 -0700998Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700999 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -07001000 wait_mutex_(new Mutex("Thread wait mutex")),
1001 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001002 wait_monitor_(NULL),
1003 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001004 wait_next_(NULL),
1005 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001006 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001007 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001008 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001009 native_to_managed_record_(NULL),
1010 top_sirt_(NULL),
1011 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -07001012 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001013 self_(NULL),
1014 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001015 exception_(NULL),
1016 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001017 class_loader_override_(NULL),
1018 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -07001019}
1020
Elliott Hughes02b48d12011-09-07 17:15:51 -07001021void MonitorExitVisitor(const Object* object, void*) {
1022 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -07001023 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001024}
1025
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001026Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -07001027 SetState(Thread::kRunnable);
1028
Elliott Hughes02b48d12011-09-07 17:15:51 -07001029 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -07001030 if (jni_env_ != NULL) {
1031 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
1032 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001033
Elliott Hughes93e74e82011-09-13 11:07:03 -07001034 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001035 Object* group = gThread_group->GetObject(peer_);
1036
1037 // Handle any pending exception.
1038 if (IsExceptionPending()) {
1039 // Get and clear the exception.
1040 Object* exception = GetException();
1041 ClearException();
1042
1043 // If the thread has its own handler, use that.
1044 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1045 if (handler == NULL) {
1046 // Otherwise use the thread group's default handler.
1047 handler = group;
1048 }
1049
1050 // Call the handler.
1051 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
1052 Object* args[2];
1053 args[0] = peer_;
1054 args[1] = exception;
1055 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
1056
1057 // If the handler threw, clear that exception too.
1058 ClearException();
1059 }
1060
1061 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -07001062 // group can be null if we're in the compiler or a test.
1063 if (group != NULL) {
1064 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
1065 Object* args = peer_;
1066 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
1067 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001068
1069 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -07001070 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001071
Elliott Hughes29f27422011-09-18 16:02:18 -07001072 // TODO: say "bye" to the debugger.
1073 //if (gDvm.debuggerConnected) {
1074 // dvmDbgPostThreadDeath(self);
1075 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001076
Elliott Hughes29f27422011-09-18 16:02:18 -07001077 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1078 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -07001079 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -07001080 Object* lock = gThread_lock->GetObject(peer_);
1081 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -07001082 if (lock != NULL) {
1083 lock->MonitorEnter(self);
1084 lock->NotifyAll();
1085 lock->MonitorExit(self);
1086 }
1087 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001088
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001089 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001090 jni_env_ = NULL;
1091
1092 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001093
1094 delete wait_cond_;
1095 delete wait_mutex_;
1096
1097 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001098}
1099
Ian Rogers408f79a2011-08-23 18:22:33 -07001100size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001101 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001102 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001103 count += cur->NumberOfReferences();
1104 }
1105 return count;
1106}
1107
Ian Rogers408f79a2011-08-23 18:22:33 -07001108bool Thread::SirtContains(jobject obj) {
1109 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1110 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001111 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001112 // A SIRT should always have a jobject/jclass as a native method is passed
1113 // in a this pointer or a class
1114 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001115 if ((&cur->References()[0] <= sirt_entry) &&
1116 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001117 return true;
1118 }
1119 }
1120 return false;
1121}
1122
Ian Rogers67375ac2011-09-14 00:55:44 -07001123void Thread::PopSirt() {
1124 CHECK(top_sirt_ != NULL);
1125 top_sirt_ = top_sirt_->Link();
1126}
1127
Ian Rogers408f79a2011-08-23 18:22:33 -07001128Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001129 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001130 if (obj == NULL) {
1131 return NULL;
1132 }
1133 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1134 IndirectRefKind kind = GetIndirectRefKind(ref);
1135 Object* result;
1136 switch (kind) {
1137 case kLocal:
1138 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001139 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001140 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001141 break;
1142 }
1143 case kGlobal:
1144 {
1145 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1146 IndirectReferenceTable& globals = vm->globals;
1147 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001148 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001149 break;
1150 }
1151 case kWeakGlobal:
1152 {
1153 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1154 IndirectReferenceTable& weak_globals = vm->weak_globals;
1155 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001156 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001157 if (result == kClearedJniWeakGlobal) {
1158 // This is a special case where it's okay to return NULL.
1159 return NULL;
1160 }
1161 break;
1162 }
1163 case kSirtOrInvalid:
1164 default:
1165 // TODO: make stack indirect reference table lookup more efficient
1166 // Check if this is a local reference in the SIRT
1167 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001168 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001169 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001170 // Assume an invalid local reference is actually a direct pointer.
1171 result = reinterpret_cast<Object*>(obj);
1172 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001173 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001174 }
1175 }
1176
1177 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001178 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1179 JniAbort(NULL);
1180 } else {
1181 if (result != kInvalidIndirectRefObject) {
1182 Heap::VerifyObject(result);
1183 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001184 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001185 return result;
1186}
1187
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001188class CountStackDepthVisitor : public Thread::StackVisitor {
1189 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001190 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001191
Elliott Hughes29f27422011-09-18 16:02:18 -07001192 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1193 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001194 // Note we also skip the frame if it doesn't have a method (namely the callee
1195 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001196 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001197 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001198 skipping_ = false;
1199 }
1200 if (!skipping_) {
1201 ++depth_;
1202 } else {
1203 ++skip_depth_;
1204 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001205 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001206
1207 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001208 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001209 }
1210
Elliott Hughes29f27422011-09-18 16:02:18 -07001211 int GetSkipDepth() const {
1212 return skip_depth_;
1213 }
1214
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001215 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001216 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001217 uint32_t skip_depth_;
1218 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001219};
1220
Ian Rogersaaa20802011-09-11 21:47:37 -07001221class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001222 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001223 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1224 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001225 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001226 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001227 // Register a local reference as IntArray::Alloc may trigger GC
1228 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1229 pc_trace_ = IntArray::Alloc(depth);
1230#ifdef MOVING_GARBAGE_COLLECTOR
1231 // Re-read after potential GC
1232 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1233#endif
1234 // Save PC trace in last element of method trace, also places it into the
1235 // object graph.
1236 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001237 }
1238
Ian Rogersaaa20802011-09-11 21:47:37 -07001239 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001240
Ian Rogersbdb03912011-09-14 00:55:44 -07001241 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001242 if (skip_depth_ > 0) {
1243 skip_depth_--;
1244 return;
1245 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001246 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001247 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001248 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001249 }
1250
Ian Rogersaaa20802011-09-11 21:47:37 -07001251 jobject GetInternalStackTrace() const {
1252 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001253 }
1254
1255 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001256 // How many more frames to skip.
1257 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001258 // Current position down stack trace
1259 uint32_t count_;
1260 // Array of return PC values
1261 IntArray* pc_trace_;
1262 // An array of the methods on the stack, the last entry is a reference to the
1263 // PC trace
1264 ObjectArray<Object>* method_trace_;
1265 // Local indirect reference table entry for method trace
1266 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001267};
1268
Ian Rogersaaa20802011-09-11 21:47:37 -07001269void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001270 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001271 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001272 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1273 // CHECK(native_to_managed_record_ != NULL);
1274 NativeToManagedRecord* record = native_to_managed_record_;
1275
Ian Rogersbdb03912011-09-14 00:55:44 -07001276 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001277 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001278 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1279 visitor->VisitFrame(frame, pc);
1280 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001281 }
1282 if (record == NULL) {
1283 break;
1284 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001285 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001286 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001287 pc = record->last_top_of_managed_stack_pc_;
1288 record = record->link_;
1289 }
1290}
1291
Ian Rogers67375ac2011-09-14 00:55:44 -07001292void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001293 Frame frame = GetTopOfStack();
1294 uintptr_t pc = top_of_managed_stack_pc_;
1295
1296 if (frame.GetSP() != 0) {
1297 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001298 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001299 visitor->VisitFrame(frame, pc);
1300 pc = frame.GetReturnPC();
1301 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001302 if (include_upcall) {
1303 visitor->VisitFrame(frame, pc);
1304 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001305 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001306}
1307
Elliott Hughes01158d72011-09-19 19:47:10 -07001308jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001309 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001310 CountStackDepthVisitor count_visitor;
1311 WalkStack(&count_visitor);
1312 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001313 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001314
Ian Rogersaaa20802011-09-11 21:47:37 -07001315 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001316 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001317
1318 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001319 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001320 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001321
Ian Rogersaaa20802011-09-11 21:47:37 -07001322 return build_trace_visitor.GetInternalStackTrace();
1323}
1324
Elliott Hughes01158d72011-09-19 19:47:10 -07001325jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1326 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001327 // Transition into runnable state to work on Object*/Array*
1328 ScopedJniThreadState ts(env);
1329
1330 // Decode the internal stack trace into the depth, method trace and PC trace
1331 ObjectArray<Object>* method_trace =
1332 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1333 int32_t depth = method_trace->GetLength()-1;
1334 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1335
1336 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1337
Elliott Hughes01158d72011-09-19 19:47:10 -07001338 jobjectArray result;
1339 ObjectArray<StackTraceElement>* java_traces;
1340 if (output_array != NULL) {
1341 // Reuse the array we were given.
1342 result = output_array;
1343 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1344 output_array));
1345 // ...adjusting the number of frames we'll write to not exceed the array length.
1346 depth = std::min(depth, java_traces->GetLength());
1347 } else {
1348 // Create java_trace array and place in local reference table
1349 java_traces = class_linker->AllocStackTraceElementArray(depth);
1350 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1351 }
1352
1353 if (stack_depth != NULL) {
1354 *stack_depth = depth;
1355 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001356
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001357 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001358 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1359 Method* method = down_cast<Method*>(method_trace->Get(i));
1360 uint32_t native_pc = pc_trace->Get(i);
1361 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001362 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001363 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001364
Ian Rogersaaa20802011-09-11 21:47:37 -07001365 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001366 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001367 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001368 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001369 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001370 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001371 method->ToDexPC(native_pc)));
1372#ifdef MOVING_GARBAGE_COLLECTOR
1373 // Re-read after potential GC
1374 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1375 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1376 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1377#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001378 java_traces->Set(i, obj);
1379 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001380 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001381}
1382
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001383void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001384 va_list args;
1385 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001386 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001387 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001388}
1389
1390void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1391 std::string msg;
1392 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001393
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001394 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001395 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001396 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001397 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001398 descriptor.erase(descriptor.length() - 1);
1399
1400 JNIEnv* env = GetJniEnv();
1401 jclass exception_class = env->FindClass(descriptor.c_str());
1402 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1403 int rc = env->ThrowNew(exception_class, msg.c_str());
1404 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001405 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001406}
1407
Elliott Hughes79082e32011-08-25 12:07:32 -07001408void Thread::ThrowOutOfMemoryError() {
1409 UNIMPLEMENTED(FATAL);
1410}
1411
Ian Rogersbdb03912011-09-14 00:55:44 -07001412class CatchBlockStackVisitor : public Thread::StackVisitor {
1413 public:
1414 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001415 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1416#ifndef NDEBUG
1417 handler_pc_ = 0xEBADC0DE;
1418 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1419#endif
1420 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001421
Ian Rogersbdb03912011-09-14 00:55:44 -07001422 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1423 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001424 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001425 if (method == NULL) {
1426 // This is the upcall, we remember the frame and last_pc so that we may
1427 // long jump to them
1428 handler_pc_ = pc;
1429 handler_frame_ = fr;
1430 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001431 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001432 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001433 if (method->IsPhony()) {
1434 // ignore callee save method
1435 } else if (method->IsNative()) {
1436 native_method_count_++;
1437 } else {
1438 // Move the PC back 2 bytes as a call will frequently terminate the
1439 // decoding of a particular instruction and we want to make sure we
1440 // get the Dex PC of the instruction with the call and not the
1441 // instruction following.
1442 pc -= 2;
1443 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001444 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001445 if (dex_pc != DexFile::kDexNoIndex) {
1446 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1447 if (found_dex_pc != DexFile::kDexNoIndex) {
1448 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001449 handler_pc_ = method->ToNativePC(found_dex_pc);
1450 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001451 }
1452 }
1453 if (!found_) {
1454 // Caller may be handler, fill in callee saves in context
1455 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001456 }
1457 }
1458 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001459
1460 // Did we find a catch block yet?
1461 bool found_;
1462 // The type of the exception catch block to find
1463 Class* to_find_;
1464 // Frame with found handler or last frame if no handler found
1465 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001466 // PC to branch to for the handler
1467 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001468 // Context that will be the target of the long jump
1469 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001470 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1471 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001472};
1473
Ian Rogersff1ed472011-09-20 13:46:24 -07001474void Thread::DeliverException() {
1475 Throwable *exception = GetException(); // Set exception on thread
1476 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001477
1478 Context* long_jump_context = GetLongJumpContext();
1479 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001480 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001481
Ian Rogers67375ac2011-09-14 00:55:44 -07001482 // Pop any SIRT
1483 if (catch_finder.native_method_count_ == 1) {
1484 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001485 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001486 // We only expect the stack crawl to have passed 1 native method as it's terminated
1487 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001488 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001489 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001490 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1491 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001492 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001493}
1494
Ian Rogersbdb03912011-09-14 00:55:44 -07001495Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001496 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001497 if (result == NULL) {
1498 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001499 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001500 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001501 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001502}
1503
Elliott Hughes5f791332011-09-15 17:45:30 -07001504bool Thread::HoldsLock(Object* object) {
1505 if (object == NULL) {
1506 return false;
1507 }
1508 return object->GetLockOwner() == thin_lock_id_;
1509}
1510
Elliott Hughes038a8062011-09-18 14:12:41 -07001511bool Thread::IsDaemon() {
1512 return gThread_daemon->GetBoolean(peer_);
1513}
1514
Elliott Hughes410c0c82011-09-01 17:58:25 -07001515void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001516 if (exception_ != NULL) {
1517 visitor(exception_, arg);
1518 }
1519 if (peer_ != NULL) {
1520 visitor(peer_, arg);
1521 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001522 jni_env_->locals.VisitRoots(visitor, arg);
1523 jni_env_->monitors.VisitRoots(visitor, arg);
1524 // visitThreadStack(visitor, thread, arg);
1525 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1526}
1527
Ian Rogersb033c752011-07-20 12:22:35 -07001528static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001529 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001530 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001531 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001532 "Blocked",
1533 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001534 "Initializing",
1535 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001536 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001537 "VmWait",
1538 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001539};
1540std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001541 int int_state = static_cast<int>(state);
1542 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1543 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001544 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001545 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001546 }
1547 return os;
1548}
1549
Elliott Hughes330304d2011-08-12 14:28:05 -07001550std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1551 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001552 << ",pthread_t=" << thread.GetImpl()
1553 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001554 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001555 << ",state=" << thread.GetState()
1556 << ",peer=" << thread.GetPeer()
1557 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001558 return os;
1559}
1560
Elliott Hughes8daa0922011-09-11 13:46:25 -07001561} // namespace art