blob: dc08799f2211401dd5a6b4098fe4abcbaf059b4b [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 Rogersd6b1f612011-09-27 13:38:14 -070030#include "compiler.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070031#include "context.h"
Ian Rogersd6b1f612011-09-27 13:38:14 -070032#include "dex_verifier.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070033#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070034#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070035#include "monitor.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070036#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070038#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070039#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070040#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070041#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070042
43namespace art {
44
45pthread_key_t Thread::pthread_key_self_;
46
Elliott Hughes8e4aac52011-09-26 17:03:36 -070047static Class* gThreadLock = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070048static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070049static Field* gThread_daemon = NULL;
50static Field* gThread_group = NULL;
51static Field* gThread_lock = NULL;
52static Field* gThread_name = NULL;
53static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070054static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070055static Field* gThread_vmData = NULL;
56static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070057static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070058static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070059static Method* gThreadGroup_removeThread = NULL;
60static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070061
buzbee4a3164f2011-09-03 11:25:10 -070062// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070063void DebugMe(Method* method, uint32_t info) {
Elliott Hughes01158d72011-09-19 19:47:10 -070064 LOG(INFO) << "DebugMe";
65 if (method != NULL) {
66 LOG(INFO) << PrettyMethod(method);
67 }
68 LOG(INFO) << "Info: " << info;
buzbee4a3164f2011-09-03 11:25:10 -070069}
70
Ian Rogersbdb03912011-09-14 00:55:44 -070071// Called by generated call to throw an exception
Ian Rogersff1ed472011-09-20 13:46:24 -070072extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070073 /*
74 * exception may be NULL, in which case this routine should
75 * throw NPE. NOTE: this is a convenience for generated code,
76 * which previously did the null check inline and constructed
77 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070078 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070079 */
Ian Rogers67375ac2011-09-14 00:55:44 -070080 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070081 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogersbdb03912011-09-14 00:55:44 -070082 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070083 if (exception == NULL) {
84 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
Ian Rogersff1ed472011-09-20 13:46:24 -070085 } else {
86 thread->SetException(exception);
Ian Rogers93dd9662011-09-17 23:21:22 -070087 }
Ian Rogersff1ed472011-09-20 13:46:24 -070088 thread->DeliverException();
89}
90
91// Deliver an exception that's pending on thread helping set up a callee save frame on the way
92extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
93 *sp = Runtime::Current()->GetCalleeSaveMethod();
94 thread->SetTopOfStack(sp, 0);
95 thread->DeliverException();
buzbee1b4c8592011-08-31 10:43:51 -070096}
97
Ian Rogers9651f422011-09-19 20:26:07 -070098// Called by generated call to throw a NPE exception
Ian Rogersff1ed472011-09-20 13:46:24 -070099extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700100 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700101 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700102 thread->SetTopOfStack(sp, 0);
103 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
Ian Rogersff1ed472011-09-20 13:46:24 -0700104 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700105}
106
107// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700108extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700109 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700110 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700111 thread->SetTopOfStack(sp, 0);
112 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
Ian Rogersff1ed472011-09-20 13:46:24 -0700113 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700114}
115
116// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700117extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700118 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700119 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700120 thread->SetTopOfStack(sp, 0);
121 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
122 "length=%d; index=%d", limit, index);
Ian Rogersff1ed472011-09-20 13:46:24 -0700123 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700124}
125
Ian Rogersff1ed472011-09-20 13:46:24 -0700126// Called by the AbstractMethodError stub (not runtime support)
127void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
128 *sp = Runtime::Current()->GetCalleeSaveMethod();
129 thread->SetTopOfStack(sp, 0);
Ian Rogersa0841a82011-09-22 14:16:31 -0700130 thread->ThrowNewException("Ljava/lang/AbstractMethodError;",
Ian Rogersff1ed472011-09-20 13:46:24 -0700131 "abstract method \"%s\"",
132 PrettyMethod(method).c_str());
133 thread->DeliverException();
134}
135
Ian Rogers932746a2011-09-22 18:57:50 -0700136extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
137 // Place a special frame at the TOS that will save all callee saves
138 Runtime* runtime = Runtime::Current();
139 *sp = runtime->GetCalleeSaveMethod();
140 thread->SetTopOfStack(sp, 0);
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700141 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Ian Rogers932746a2011-09-22 18:57:50 -0700142 thread->ThrowNewException("Ljava/lang/StackOverflowError;",
143 "stack size %zdkb; default stack size: %zdkb",
144 thread->GetStackSize() / KB, runtime->GetDefaultStackSize() / KB);
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700145 thread->ResetDefaultStackEnd(); // Return to default stack size
Ian Rogers932746a2011-09-22 18:57:50 -0700146 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700147}
148
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700149extern "C" void artThrowVerificationErrorFromCode(int32_t src1, int32_t ref, Thread* thread, Method** sp) {
150 // Place a special frame at the TOS that will save all callee saves
151 Runtime* runtime = Runtime::Current();
152 *sp = runtime->GetCalleeSaveMethod();
153 thread->SetTopOfStack(sp, 0);
154 LOG(WARNING) << "TODO: verifcation error detail message. src1=" << src1 << " ref=" << ref;
155 thread->ThrowNewException("Ljava/lang/VerifyError;",
156 "TODO: verifcation error detail message. src1=%d; ref=%d", src1, ref);
157 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700158}
159
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700160extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
161 // Place a special frame at the TOS that will save all callee saves
162 Runtime* runtime = Runtime::Current();
163 *sp = runtime->GetCalleeSaveMethod();
164 thread->SetTopOfStack(sp, 0);
165 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
166 thread->ThrowNewException("Ljava/lang/InternalError;", "errnum=%d", errnum);
167 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700168}
169
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700170extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
171 // Place a special frame at the TOS that will save all callee saves
172 Runtime* runtime = Runtime::Current();
173 *sp = runtime->GetCalleeSaveMethod();
174 thread->SetTopOfStack(sp, 0);
175 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
176 thread->ThrowNewException("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
177 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700178}
179
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700180extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* thread, Method** sp) {
181 // Place a special frame at the TOS that will save all callee saves
182 Runtime* runtime = Runtime::Current();
183 *sp = runtime->GetCalleeSaveMethod();
184 thread->SetTopOfStack(sp, 0);
185 LOG(WARNING) << "TODO: no such method exception detail message. method_idx=" << method_idx;
186 thread->ThrowNewException("Ljava/lang/NoSuchMethodError;", "method_idx=%d", method_idx);
187 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700188}
189
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700190extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
191 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
192 // Place a special frame at the TOS that will save all callee saves
193 Runtime* runtime = Runtime::Current();
194 *sp = runtime->GetCalleeSaveMethod();
195 thread->SetTopOfStack(sp, 0);
196 thread->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d", size);
197 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700198}
Ian Rogersbdb03912011-09-14 00:55:44 -0700199
buzbee1b4c8592011-08-31 10:43:51 -0700200// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700201Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700202 /*
203 * Should initialize & fix up method->dex_cache_resolved_types_[].
204 * Returns initialized type. Does not return normally if an exception
205 * is thrown, but instead initiates the catch. Should be similar to
206 * ClassLinker::InitializeStaticStorageFromCode.
207 */
208 UNIMPLEMENTED(FATAL);
209 return NULL;
210}
211
buzbee561227c2011-09-02 15:28:19 -0700212// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700213void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700214 /*
215 * Slow-path handler on invoke virtual method path in which
216 * base method is unresolved at compile-time. Doesn't need to
217 * return anything - just either ensure that
218 * method->dex_cache_resolved_methods_(method_idx) != NULL or
219 * throw and unwind. The caller will restart call sequence
220 * from the beginning.
221 */
222}
223
Ian Rogers21d9e832011-09-23 17:05:09 -0700224// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
225// cannot be resolved, throw an error. If it can, use it to create an instance.
226extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method) {
227 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
228 if (klass == NULL) {
229 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
230 if (klass == NULL) {
231 DCHECK(Thread::Current()->IsExceptionPending());
232 return NULL; // Failure
233 }
234 }
Brian Carlstromd1422f82011-09-28 11:37:09 -0700235 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(klass, true)) {
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700236 DCHECK(Thread::Current()->IsExceptionPending());
237 return NULL; // Failure
238 }
Ian Rogers21d9e832011-09-23 17:05:09 -0700239 return klass->AllocObject();
240}
241
Ian Rogersb886da82011-09-23 16:27:54 -0700242// Helper function to alloc array for OP_FILLED_NEW_ARRAY
243extern "C" Array* artCheckAndArrayAllocFromCode(uint32_t type_idx, Method* method,
244 int32_t component_count) {
245 if (component_count < 0) {
246 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
247 component_count);
248 return NULL; // Failure
249 }
250 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
251 if (klass == NULL) { // Not in dex cache so try to resolve
252 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
253 if (klass == NULL) { // Error
254 DCHECK(Thread::Current()->IsExceptionPending());
255 return NULL; // Failure
256 }
257 }
258 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
259 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
260 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
261 "Bad filled array request for type %s",
262 PrettyDescriptor(klass->GetDescriptor()).c_str());
263 } else {
264 Thread::Current()->ThrowNewException("Ljava/lang/InternalError;",
265 "Found type %s; filled-new-array not implemented for anything but \'int\'",
266 PrettyDescriptor(klass->GetDescriptor()).c_str());
267 }
268 return NULL; // Failure
269 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700270 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700271 return Array::Alloc(klass, component_count);
272 }
273}
274
275// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
276// it cannot be resolved, throw an error. If it can, use it to create an array.
277extern "C" Array* artArrayAllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
278 if (component_count < 0) {
279 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
280 component_count);
281 return NULL; // Failure
282 }
283 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
284 if (klass == NULL) { // Not in dex cache so try to resolve
285 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
286 if (klass == NULL) { // Error
287 DCHECK(Thread::Current()->IsExceptionPending());
288 return NULL; // Failure
289 }
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700290 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700291 }
292 return Array::Alloc(klass, component_count);
buzbee1da522d2011-09-04 11:22:20 -0700293}
294
Ian Rogerse51a5112011-09-23 14:16:35 -0700295// 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 -0700296extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700297 DCHECK(a->IsClass()) << PrettyClass(a);
298 DCHECK(b->IsClass()) << PrettyClass(b);
Brian Carlstromc2282522011-09-17 10:33:14 -0700299 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700300 return 0; // Success
301 } else {
302 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700303 "%s cannot be cast to %s",
304 PrettyDescriptor(a->GetDescriptor()).c_str(),
305 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700306 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700307 }
buzbee2a475e72011-09-07 17:19:17 -0700308}
309
Ian Rogerse51a5112011-09-23 14:16:35 -0700310// Tests whether 'element' can be assigned into an array of type 'array_class'.
311// Returns 0 on success and -1 if an exception is pending.
312extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
313 DCHECK(array_class != NULL);
314 // element can't be NULL as we catch this is screened in runtime_support
315 Class* element_class = element->GetClass();
316 Class* component_type = array_class->GetComponentType();
317 if (component_type->IsAssignableFrom(element_class)) {
318 return 0; // Success
319 } else {
320 Thread::Current()->ThrowNewException("Ljava/lang/ArrayStoreException;",
Ian Rogersb886da82011-09-23 16:27:54 -0700321 "Cannot store an object of type %s in to an array of type %s",
322 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
323 PrettyDescriptor(array_class->GetDescriptor()).c_str());
Ian Rogerse51a5112011-09-23 14:16:35 -0700324 return -1; // Failure
325 }
326}
327
Ian Rogersff1ed472011-09-20 13:46:24 -0700328extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
329 DCHECK(obj != NULL); // Assumed to have been checked before entry
330 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700331}
332
Elliott Hughesd369bb72011-09-12 14:41:14 -0700333void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700334 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700335 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700336 DCHECK(thread->HoldsLock(obj));
337 // Only possible exception is NPE and is handled before entry
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700338 DCHECK(!thread->IsExceptionPending());
buzbee2a475e72011-09-07 17:19:17 -0700339}
340
buzbeec1f45042011-09-21 16:03:19 -0700341extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700342 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700343}
344
buzbee5ade1d22011-09-09 14:44:52 -0700345/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700346 * Fill the array with predefined constant values, throwing exceptions if the array is null or
347 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700348 *
349 * NOTE: When dealing with a raw dex file, the data to be copied uses
350 * little-endian ordering. Require that oat2dex do any required swapping
351 * so this routine can get by with a memcpy().
352 *
353 * Format of the data:
354 * ushort ident = 0x0300 magic value
355 * ushort width width of each element in the table
356 * uint size number of elements in the table
357 * ubyte data[size*width] table of data values (may contain a single-byte
358 * padding at the end)
359 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700360extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
361 DCHECK_EQ(table[0], 0x0300);
362 if (array == NULL) {
363 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
364 "null array in fill array");
365 return -1; // Error
366 }
367 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
368 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
369 if (static_cast<int32_t>(size) > array->GetLength()) {
370 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
371 "failed array fill. length=%d; index=%d",
372 array->GetLength(), size);
373 return -1; // Error
374 }
375 uint16_t width = table[1];
376 uint32_t size_in_bytes = size * width;
377 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
378 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700379}
380
381// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700382extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
383 Object* this_object ,
384 Method* caller_method) {
385 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700386 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700387 thread->ThrowNewException("Ljava/lang/NullPointerException;",
388 "null receiver during interface dispatch");
389 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700390 }
391 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
392 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
393 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700394 // Could not resolve interface method. Throw error and unwind
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700395 CHECK(thread->IsExceptionPending());
Ian Rogersff1ed472011-09-20 13:46:24 -0700396 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700397 }
398 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700399 if (method == NULL) {
400 CHECK(thread->IsExceptionPending());
401 return 0;
402 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700403 const void* code = method->GetCode();
404
405 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
406 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
407 uint64_t result = ((code_uint << 32) | method_uint);
408 return result;
409}
410
buzbee5ade1d22011-09-09 14:44:52 -0700411// TODO: move to more appropriate location
412/*
413 * Float/double conversion requires clamping to min and max of integer form. If
414 * target doesn't support this normally, use these.
415 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700416int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700417 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
418 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
419 if (d >= kMaxLong)
420 return (int64_t)0x7fffffffffffffffULL;
421 else if (d <= kMinLong)
422 return (int64_t)0x8000000000000000ULL;
423 else if (d != d) // NaN case
424 return 0;
425 else
426 return (int64_t)d;
427}
428
Elliott Hughesd369bb72011-09-12 14:41:14 -0700429int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700430 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
431 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
432 if (f >= kMaxLong)
433 return (int64_t)0x7fffffffffffffffULL;
434 else if (f <= kMinLong)
435 return (int64_t)0x8000000000000000ULL;
436 else if (f != f) // NaN case
437 return 0;
438 else
439 return (int64_t)f;
440}
441
Brian Carlstrom16192862011-09-12 17:50:06 -0700442// Return value helper for jobject return types
443static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
444 return thread->DecodeJObject(obj);
445}
446
buzbee3ea4ec52011-08-22 17:37:19 -0700447void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700448#if defined(__arm__)
449 pShlLong = art_shl_long;
450 pShrLong = art_shr_long;
451 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700452 pIdiv = __aeabi_idiv;
453 pIdivmod = __aeabi_idivmod;
454 pI2f = __aeabi_i2f;
455 pF2iz = __aeabi_f2iz;
456 pD2f = __aeabi_d2f;
457 pF2d = __aeabi_f2d;
458 pD2iz = __aeabi_d2iz;
459 pL2f = __aeabi_l2f;
460 pL2d = __aeabi_l2d;
461 pFadd = __aeabi_fadd;
462 pFsub = __aeabi_fsub;
463 pFdiv = __aeabi_fdiv;
464 pFmul = __aeabi_fmul;
465 pFmodf = fmodf;
466 pDadd = __aeabi_dadd;
467 pDsub = __aeabi_dsub;
468 pDdiv = __aeabi_ddiv;
469 pDmul = __aeabi_dmul;
470 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700471 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700472 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700473 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700474 pArrayAllocFromCode = art_array_alloc_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700475 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700476 pCheckAndArrayAllocFromCode = art_check_and_array_alloc_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700477 pCheckCastFromCode = art_check_cast_from_code;
478 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700479 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700480 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700481 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700482 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
483 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700484 pThrowInternalErrorFromCode = art_throw_internal_error_from_code;
485 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
486 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700487 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700488 pThrowRuntimeExceptionFromCode = art_throw_runtime_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700489 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700490 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700491 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700492#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700493 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700494 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700495 pF2l = F2L;
496 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700497 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700498 pGet32Static = Field::Get32StaticFromCode;
499 pSet32Static = Field::Set32StaticFromCode;
500 pGet64Static = Field::Get64StaticFromCode;
501 pSet64Static = Field::Set64StaticFromCode;
502 pGetObjStatic = Field::GetObjStaticFromCode;
503 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700504 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700505 pResolveMethodFromCode = ResolveMethodFromCode;
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700506 pInstanceofNonTrivialFromCode = Object::InstanceOfFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700507 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700508 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700509 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700510 pFindNativeMethod = FindNativeMethod;
511 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700512 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700513}
514
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700515void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700516 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
517 DCHECK_NE(frame_size, 0u);
518 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700519 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520 sp_ = reinterpret_cast<Method**>(next_sp);
Elliott Hughes80609252011-09-23 17:24:51 -0700521 if (*sp_ != NULL) {
522 DCHECK((*sp_)->GetClass() == Method::GetMethodClass() ||
523 (*sp_)->GetClass() == Method::GetConstructorClass());
Ian Rogersff1ed472011-09-20 13:46:24 -0700524 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700525}
526
Ian Rogers90865722011-09-19 11:11:44 -0700527bool Frame::HasMethod() const {
528 return GetMethod() != NULL && (!GetMethod()->IsPhony());
529}
530
Ian Rogersbdb03912011-09-14 00:55:44 -0700531uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700532 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700533 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700534}
535
Ian Rogersd6b1f612011-09-27 13:38:14 -0700536uintptr_t Frame::GetVReg(Method* method, int vreg) const {
537 DCHECK(method == GetMethod());
538 int offset = oatVRegOffsetFromMethod(method, vreg);
539 byte* vreg_addr = reinterpret_cast<byte*>(sp_) + offset;
540 return *reinterpret_cast<uintptr_t*>(vreg_addr);
541}
542
Ian Rogersbdb03912011-09-14 00:55:44 -0700543uintptr_t Frame::LoadCalleeSave(int num) const {
544 // Callee saves are held at the top of the frame
545 Method* method = GetMethod();
546 DCHECK(method != NULL);
547 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700548 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700549#if defined(__i386__)
550 save_addr -= kPointerSize; // account for return address
551#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700552 return *reinterpret_cast<uintptr_t*>(save_addr);
553}
554
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700556 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700557 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700559}
560
Brian Carlstrom78128a62011-09-15 17:21:19 -0700561void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700562 Thread* self = reinterpret_cast<Thread*>(arg);
563 Runtime* runtime = Runtime::Current();
564
565 self->Attach(runtime);
566
Elliott Hughes038a8062011-09-18 14:12:41 -0700567 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700568 if (thread_name != NULL) {
569 SetThreadName(thread_name->ToModifiedUtf8().c_str());
570 }
571
572 // Wait until it's safe to start running code. (There may have been a suspend-all
573 // in progress while we were starting up.)
574 runtime->GetThreadList()->WaitForGo();
575
576 // TODO: say "hi" to the debugger.
577 //if (gDvm.debuggerConnected) {
578 // dvmDbgPostThreadStart(self);
579 //}
580
581 // Invoke the 'run' method of our java.lang.Thread.
582 CHECK(self->peer_ != NULL);
583 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700584 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700585 m->Invoke(self, receiver, NULL, NULL);
586
587 // Detach.
588 runtime->GetThreadList()->Unregister();
589
Carl Shapirob5573532011-07-12 18:22:59 -0700590 return NULL;
591}
592
Elliott Hughes93e74e82011-09-13 11:07:03 -0700593void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700594 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700595}
596
Elliott Hughes01158d72011-09-19 19:47:10 -0700597Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
598 Object* thread = Decode<Object*>(env, java_thread);
599 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
600}
601
Elliott Hughesd369bb72011-09-12 14:41:14 -0700602void Thread::Create(Object* peer, size_t stack_size) {
603 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700604
Elliott Hughesd369bb72011-09-12 14:41:14 -0700605 if (stack_size == 0) {
606 stack_size = Runtime::Current()->GetDefaultStackSize();
607 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700608
Elliott Hughes93e74e82011-09-13 11:07:03 -0700609 Thread* native_thread = new Thread;
610 native_thread->peer_ = peer;
611
612 // Thread.start is synchronized, so we know that vmData is 0,
613 // and know that we're not racing to assign it.
614 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700615
616 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700617 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
618 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
619 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
620 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
621 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700622
623 // Let the child know when it's safe to start running.
624 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700625}
626
Elliott Hughes93e74e82011-09-13 11:07:03 -0700627void Thread::Attach(const Runtime* runtime) {
628 InitCpu();
629 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700630
Elliott Hughes93e74e82011-09-13 11:07:03 -0700631 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700632
Elliott Hughes93e74e82011-09-13 11:07:03 -0700633 tid_ = ::art::GetTid();
634 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700635
Elliott Hughes93e74e82011-09-13 11:07:03 -0700636 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700637
Elliott Hughes8d768a92011-09-14 16:35:25 -0700638 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700639
Elliott Hughes93e74e82011-09-13 11:07:03 -0700640 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700641
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700642 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700643}
644
645Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
646 Thread* self = new Thread;
647 self->Attach(runtime);
648
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700649 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700650
651 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700652
653 // If we're the main thread, ClassLinker won't be created until after we're attached,
654 // so that thread needs a two-stage attach. Regular threads don't need this hack.
655 if (self->thin_lock_id_ != ThreadList::kMainId) {
656 self->CreatePeer(name, as_daemon);
657 }
658
659 return self;
660}
661
Elliott Hughesd369bb72011-09-12 14:41:14 -0700662jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
663 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
664 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
665 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
666 // This will be null in the compiler (and tests), but never in a running system.
667 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
668 return thread_group;
669}
670
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700671void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700672 JNIEnv* env = jni_env_;
673
Elliott Hughesd369bb72011-09-12 14:41:14 -0700674 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
675 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700676 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700677 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700678 jboolean thread_is_daemon = as_daemon;
679
680 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700681 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700682
Elliott Hughes8daa0922011-09-11 13:46:25 -0700683 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700684 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700685 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700686
687 // Because we mostly run without code available (in the compiler, in tests), we
688 // manually assign the fields the constructor should have set.
689 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700690 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
691 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
692 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
693 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700694}
695
Elliott Hughesbe759c62011-09-08 19:38:21 -0700696void Thread::InitStackHwm() {
697 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700698 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700699
Ian Rogers932746a2011-09-22 18:57:50 -0700700 void* temp_stack_base;
701 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
702 __FUNCTION__);
703 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700704
Ian Rogers932746a2011-09-22 18:57:50 -0700705 if (stack_size_ <= kStackOverflowReservedBytes) {
706 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700707 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700708
Ian Rogers932746a2011-09-22 18:57:50 -0700709 // Set stack_end_ to the bottom of the stack saving space of stack overflows
710 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700711
712 // Sanity check.
713 int stack_variable;
714 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700715
Elliott Hughes8d768a92011-09-14 16:35:25 -0700716 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700717}
718
Elliott Hughesa0957642011-09-02 14:27:33 -0700719void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700720 DumpState(os);
721 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700722}
723
Elliott Hughesd92bec42011-09-02 17:04:36 -0700724std::string GetSchedulerGroup(pid_t tid) {
725 // /proc/<pid>/group looks like this:
726 // 2:devices:/
727 // 1:cpuacct,cpu:/
728 // We want the third field from the line whose second field contains the "cpu" token.
729 std::string cgroup_file;
730 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
731 return "";
732 }
733 std::vector<std::string> cgroup_lines;
734 Split(cgroup_file, '\n', cgroup_lines);
735 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
736 std::vector<std::string> cgroup_fields;
737 Split(cgroup_lines[i], ':', cgroup_fields);
738 std::vector<std::string> cgroups;
739 Split(cgroup_fields[1], ',', cgroups);
740 for (size_t i = 0; i < cgroups.size(); ++i) {
741 if (cgroups[i] == "cpu") {
742 return cgroup_fields[2].substr(1); // Skip the leading slash.
743 }
744 }
745 }
746 return "";
747}
748
749void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700750 std::string thread_name("<native thread without managed peer>");
751 std::string group_name;
752 int priority;
753 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700754
Elliott Hughesd369bb72011-09-12 14:41:14 -0700755 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700756 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700757 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700758 priority = gThread_priority->GetInt(peer_);
759 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700760
Elliott Hughes038a8062011-09-18 14:12:41 -0700761 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700762 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700763 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700764 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
765 }
766 } else {
767 // 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 -0700768 std::string stats;
769 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
770 size_t start = stats.find('(') + 1;
771 size_t end = stats.find(')') - start;
772 thread_name = stats.substr(start, end);
773 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700774 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700775 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700776
777 int policy;
778 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700779 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700780
781 std::string scheduler_group(GetSchedulerGroup(GetTid()));
782 if (scheduler_group.empty()) {
783 scheduler_group = "default";
784 }
785
Elliott Hughesd92bec42011-09-02 17:04:36 -0700786 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700787 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700788 os << " daemon";
789 }
790 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700791 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700792 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700793
Elliott Hughesd92bec42011-09-02 17:04:36 -0700794 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700795 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700796 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700797 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700798 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700799 << " self=" << reinterpret_cast<const void*>(this) << "\n";
800 os << " | sysTid=" << GetTid()
801 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
802 << " sched=" << policy << "/" << sp.sched_priority
803 << " cgrp=" << scheduler_group
804 << " handle=" << GetImpl() << "\n";
805
806 // Grab the scheduler stats for this thread.
807 std::string scheduler_stats;
808 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
809 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
810 } else {
811 scheduler_stats = "0 0 0";
812 }
813
814 int utime = 0;
815 int stime = 0;
816 int task_cpu = 0;
817 std::string stats;
818 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
819 // Skip the command, which may contain spaces.
820 stats = stats.substr(stats.find(')') + 2);
821 // Extract the three fields we care about.
822 std::vector<std::string> fields;
823 Split(stats, ' ', fields);
824 utime = strtoull(fields[11].c_str(), NULL, 10);
825 stime = strtoull(fields[12].c_str(), NULL, 10);
826 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
827 }
828
829 os << " | schedstat=( " << scheduler_stats << " )"
830 << " utm=" << utime
831 << " stm=" << stime
832 << " core=" << task_cpu
833 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
834}
835
Elliott Hughesd369bb72011-09-12 14:41:14 -0700836struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700837 StackDumpVisitor(std::ostream& os, const Thread* thread)
838 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700839 }
840
Ian Rogersbdb03912011-09-14 00:55:44 -0700841 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700842 }
843
Ian Rogersbdb03912011-09-14 00:55:44 -0700844 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700845 if (!frame.HasMethod()) {
846 return;
847 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700848
849 Method* m = frame.GetMethod();
850 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700851 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700852 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
853
854 os << " at " << PrettyMethod(m, false);
855 if (m->IsNative()) {
856 os << "(Native method)";
857 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700858 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700859 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
860 }
861 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700862
863 if (frame_count++ == 0) {
864 Monitor::DescribeWait(os, thread);
865 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700866 }
867
868 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700869 const Thread* thread;
870 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700871};
872
Elliott Hughesd92bec42011-09-02 17:04:36 -0700873void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700874 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700875 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700876}
877
Elliott Hughes8d768a92011-09-14 16:35:25 -0700878Thread::State Thread::SetState(Thread::State new_state) {
879 Thread::State old_state = state_;
880 if (old_state == new_state) {
881 return old_state;
882 }
883
884 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
885 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
886
887 if (new_state == Thread::kRunnable) {
888 /*
889 * Change our status to Thread::kRunnable. The transition requires
890 * that we check for pending suspension, because the VM considers
891 * us to be "asleep" in all other states, and another thread could
892 * be performing a GC now.
893 *
894 * The order of operations is very significant here. One way to
895 * do this wrong is:
896 *
897 * GCing thread Our thread (in kNative)
898 * ------------ ----------------------
899 * check suspend count (== 0)
900 * SuspendAllThreads()
901 * grab suspend-count lock
902 * increment all suspend counts
903 * release suspend-count lock
904 * check thread state (== kNative)
905 * all are suspended, begin GC
906 * set state to kRunnable
907 * (continue executing)
908 *
909 * We can correct this by grabbing the suspend-count lock and
910 * performing both of our operations (check suspend count, set
911 * state) while holding it, now we need to grab a mutex on every
912 * transition to kRunnable.
913 *
914 * What we do instead is change the order of operations so that
915 * the transition to kRunnable happens first. If we then detect
916 * that the suspend count is nonzero, we switch to kSuspended.
917 *
918 * Appropriate compiler and memory barriers are required to ensure
919 * that the operations are observed in the expected order.
920 *
921 * This does create a small window of opportunity where a GC in
922 * progress could observe what appears to be a running thread (if
923 * it happens to look between when we set to kRunnable and when we
924 * switch to kSuspended). At worst this only affects assertions
925 * and thread logging. (We could work around it with some sort
926 * of intermediate "pre-running" state that is generally treated
927 * as equivalent to running, but that doesn't seem worthwhile.)
928 *
929 * We can also solve this by combining the "status" and "suspend
930 * count" fields into a single 32-bit value. This trades the
931 * store/load barrier on transition to kRunnable for an atomic RMW
932 * op on all transitions and all suspend count updates (also, all
933 * accesses to status or the thread count require bit-fiddling).
934 * It also eliminates the brief transition through kRunnable when
935 * the thread is supposed to be suspended. This is possibly faster
936 * on SMP and slightly more correct, but less convenient.
937 */
938 android_atomic_acquire_store(new_state, addr);
939 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
940 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
941 }
942 } else {
943 /*
944 * Not changing to Thread::kRunnable. No additional work required.
945 *
946 * We use a releasing store to ensure that, if we were runnable,
947 * any updates we previously made to objects on the managed heap
948 * will be observed before the state change.
949 */
950 android_atomic_release_store(new_state, addr);
951 }
952
953 return old_state;
954}
955
956void Thread::WaitUntilSuspended() {
957 // TODO: dalvik dropped the waiting thread's priority after a while.
958 // TODO: dalvik timed out and aborted.
959 useconds_t delay = 0;
960 while (GetState() == Thread::kRunnable) {
961 useconds_t new_delay = delay * 2;
962 CHECK_GE(new_delay, delay);
963 delay = new_delay;
964 if (delay == 0) {
965 sched_yield();
966 delay = 10000;
967 } else {
968 usleep(delay);
969 }
970 }
971}
972
Elliott Hughesbe759c62011-09-08 19:38:21 -0700973void Thread::ThreadExitCallback(void* arg) {
974 Thread* self = reinterpret_cast<Thread*>(arg);
975 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700976}
977
Elliott Hughesbe759c62011-09-08 19:38:21 -0700978void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700979 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700980 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700981
982 // Double-check the TLS slot allocation.
983 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700984 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700985 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700986}
Carl Shapirob5573532011-07-12 18:22:59 -0700987
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700988// TODO: make more accessible?
989Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
990 Class* c = class_linker->FindPrimitiveClass(descriptor);
991 CHECK(c != NULL) << descriptor;
992 return c;
993}
994
995// TODO: make more accessible?
996Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
997 Class* c = class_linker->FindSystemClass(descriptor);
998 CHECK(c != NULL) << descriptor;
999 return c;
1000}
1001
1002// TODO: make more accessible?
1003Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
1004 Field* f = c->FindDeclaredInstanceField(name, type);
1005 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
1006 return f;
1007}
1008
1009// TODO: make more accessible?
1010Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
1011 Method* m = c->FindVirtualMethod(name, signature);
1012 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
1013 return m;
1014}
1015
Elliott Hughes038a8062011-09-18 14:12:41 -07001016void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -07001017 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
1018 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001019
1020 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
1021 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
1022 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
1023 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
1024 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
1025 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
1026 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
1027 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
1028
1029 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
1030 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
1031 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
1032 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
1033 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
1034 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
1035 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
1036 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
1037 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
1038
1039 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
1040 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
1041 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
1042 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -07001043
1044 // Finish attaching the main thread.
1045 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -07001046}
1047
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001048void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -07001049 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001050}
1051
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001052uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
1053 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
1054 return ThreadList::kInvalidId;
1055 }
1056 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
1057 if (managed_thread == NULL) {
1058 return ThreadList::kInvalidId;
1059 }
1060 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
1061 Thread* thread = reinterpret_cast<Thread*>(vmData);
1062 if (thread == NULL) {
1063 return ThreadList::kInvalidId;
1064 }
1065 return thread->GetThinLockId();
1066}
1067
Elliott Hughesdcc24742011-09-07 14:02:44 -07001068Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -07001069 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001070 top_of_managed_stack_(),
1071 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001072 wait_mutex_(new Mutex("Thread wait mutex")),
1073 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001074 wait_monitor_(NULL),
1075 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001076 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001077 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001078 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001079 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001080 native_to_managed_record_(NULL),
1081 top_sirt_(NULL),
1082 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001083 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001084 self_(NULL),
1085 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001086 exception_(NULL),
1087 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001088 class_loader_override_(NULL),
1089 long_jump_context_(NULL) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001090 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001091}
1092
Elliott Hughes02b48d12011-09-07 17:15:51 -07001093void MonitorExitVisitor(const Object* object, void*) {
1094 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -07001095 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001096}
1097
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001098Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -07001099 SetState(Thread::kRunnable);
1100
Elliott Hughes02b48d12011-09-07 17:15:51 -07001101 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -07001102 if (jni_env_ != NULL) {
1103 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
1104 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001105
Elliott Hughes93e74e82011-09-13 11:07:03 -07001106 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001107 Object* group = gThread_group->GetObject(peer_);
1108
1109 // Handle any pending exception.
1110 if (IsExceptionPending()) {
1111 // Get and clear the exception.
1112 Object* exception = GetException();
1113 ClearException();
1114
1115 // If the thread has its own handler, use that.
1116 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1117 if (handler == NULL) {
1118 // Otherwise use the thread group's default handler.
1119 handler = group;
1120 }
1121
1122 // Call the handler.
1123 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
1124 Object* args[2];
1125 args[0] = peer_;
1126 args[1] = exception;
1127 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
1128
1129 // If the handler threw, clear that exception too.
1130 ClearException();
1131 }
1132
1133 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -07001134 // group can be null if we're in the compiler or a test.
1135 if (group != NULL) {
1136 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
1137 Object* args = peer_;
1138 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
1139 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001140
1141 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -07001142 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001143
Elliott Hughes29f27422011-09-18 16:02:18 -07001144 // TODO: say "bye" to the debugger.
1145 //if (gDvm.debuggerConnected) {
1146 // dvmDbgPostThreadDeath(self);
1147 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001148
Elliott Hughes29f27422011-09-18 16:02:18 -07001149 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1150 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -07001151 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -07001152 Object* lock = gThread_lock->GetObject(peer_);
1153 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -07001154 if (lock != NULL) {
1155 lock->MonitorEnter(self);
1156 lock->NotifyAll();
1157 lock->MonitorExit(self);
1158 }
1159 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001160
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001161 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001162 jni_env_ = NULL;
1163
1164 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001165
1166 delete wait_cond_;
1167 delete wait_mutex_;
1168
1169 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001170}
1171
Ian Rogers408f79a2011-08-23 18:22:33 -07001172size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001173 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001174 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001175 count += cur->NumberOfReferences();
1176 }
1177 return count;
1178}
1179
Ian Rogers408f79a2011-08-23 18:22:33 -07001180bool Thread::SirtContains(jobject obj) {
1181 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1182 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001183 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001184 // A SIRT should always have a jobject/jclass as a native method is passed
1185 // in a this pointer or a class
1186 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001187 if ((&cur->References()[0] <= sirt_entry) &&
1188 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001189 return true;
1190 }
1191 }
1192 return false;
1193}
1194
Ian Rogers67375ac2011-09-14 00:55:44 -07001195void Thread::PopSirt() {
1196 CHECK(top_sirt_ != NULL);
1197 top_sirt_ = top_sirt_->Link();
1198}
1199
Ian Rogers408f79a2011-08-23 18:22:33 -07001200Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001201 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001202 if (obj == NULL) {
1203 return NULL;
1204 }
1205 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1206 IndirectRefKind kind = GetIndirectRefKind(ref);
1207 Object* result;
1208 switch (kind) {
1209 case kLocal:
1210 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001211 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001212 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001213 break;
1214 }
1215 case kGlobal:
1216 {
1217 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1218 IndirectReferenceTable& globals = vm->globals;
1219 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001220 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001221 break;
1222 }
1223 case kWeakGlobal:
1224 {
1225 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1226 IndirectReferenceTable& weak_globals = vm->weak_globals;
1227 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001228 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001229 if (result == kClearedJniWeakGlobal) {
1230 // This is a special case where it's okay to return NULL.
1231 return NULL;
1232 }
1233 break;
1234 }
1235 case kSirtOrInvalid:
1236 default:
1237 // TODO: make stack indirect reference table lookup more efficient
1238 // Check if this is a local reference in the SIRT
1239 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001240 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001241 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001242 // Assume an invalid local reference is actually a direct pointer.
1243 result = reinterpret_cast<Object*>(obj);
1244 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001245 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001246 }
1247 }
1248
1249 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001250 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1251 JniAbort(NULL);
1252 } else {
1253 if (result != kInvalidIndirectRefObject) {
1254 Heap::VerifyObject(result);
1255 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001256 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001257 return result;
1258}
1259
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001260class CountStackDepthVisitor : public Thread::StackVisitor {
1261 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001262 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001263
Elliott Hughes29f27422011-09-18 16:02:18 -07001264 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1265 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001266 // Note we also skip the frame if it doesn't have a method (namely the callee
1267 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001268 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001269 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001270 skipping_ = false;
1271 }
1272 if (!skipping_) {
1273 ++depth_;
1274 } else {
1275 ++skip_depth_;
1276 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001277 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001278
1279 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001280 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001281 }
1282
Elliott Hughes29f27422011-09-18 16:02:18 -07001283 int GetSkipDepth() const {
1284 return skip_depth_;
1285 }
1286
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001287 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001288 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001289 uint32_t skip_depth_;
1290 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001291};
1292
Ian Rogersaaa20802011-09-11 21:47:37 -07001293class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001294 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001295 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1296 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001297 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001298 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001299 // Register a local reference as IntArray::Alloc may trigger GC
1300 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1301 pc_trace_ = IntArray::Alloc(depth);
1302#ifdef MOVING_GARBAGE_COLLECTOR
1303 // Re-read after potential GC
1304 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1305#endif
1306 // Save PC trace in last element of method trace, also places it into the
1307 // object graph.
1308 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001309 }
1310
Ian Rogersaaa20802011-09-11 21:47:37 -07001311 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001312
Ian Rogersbdb03912011-09-14 00:55:44 -07001313 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001314 if (skip_depth_ > 0) {
1315 skip_depth_--;
1316 return;
1317 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001318 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001319 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001320 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001321 }
1322
Ian Rogersaaa20802011-09-11 21:47:37 -07001323 jobject GetInternalStackTrace() const {
1324 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001325 }
1326
1327 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001328 // How many more frames to skip.
1329 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001330 // Current position down stack trace
1331 uint32_t count_;
1332 // Array of return PC values
1333 IntArray* pc_trace_;
1334 // An array of the methods on the stack, the last entry is a reference to the
1335 // PC trace
1336 ObjectArray<Object>* method_trace_;
1337 // Local indirect reference table entry for method trace
1338 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001339};
1340
Ian Rogersaaa20802011-09-11 21:47:37 -07001341void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001342 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001343 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001344 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1345 // CHECK(native_to_managed_record_ != NULL);
1346 NativeToManagedRecord* record = native_to_managed_record_;
1347
Ian Rogersbdb03912011-09-14 00:55:44 -07001348 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001349 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001350 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1351 visitor->VisitFrame(frame, pc);
1352 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001353 }
1354 if (record == NULL) {
1355 break;
1356 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001357 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001358 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001359 pc = record->last_top_of_managed_stack_pc_;
1360 record = record->link_;
1361 }
1362}
1363
Ian Rogers67375ac2011-09-14 00:55:44 -07001364void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001365 Frame frame = GetTopOfStack();
1366 uintptr_t pc = top_of_managed_stack_pc_;
1367
1368 if (frame.GetSP() != 0) {
1369 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001370 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001371 visitor->VisitFrame(frame, pc);
1372 pc = frame.GetReturnPC();
1373 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001374 if (include_upcall) {
1375 visitor->VisitFrame(frame, pc);
1376 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001377 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001378}
1379
Elliott Hughes01158d72011-09-19 19:47:10 -07001380jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001381 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001382 CountStackDepthVisitor count_visitor;
1383 WalkStack(&count_visitor);
1384 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001385 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001386
Ian Rogersaaa20802011-09-11 21:47:37 -07001387 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001388 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001389
1390 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001391 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001392 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001393
Ian Rogersaaa20802011-09-11 21:47:37 -07001394 return build_trace_visitor.GetInternalStackTrace();
1395}
1396
Elliott Hughes01158d72011-09-19 19:47:10 -07001397jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1398 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001399 // Transition into runnable state to work on Object*/Array*
1400 ScopedJniThreadState ts(env);
1401
1402 // Decode the internal stack trace into the depth, method trace and PC trace
1403 ObjectArray<Object>* method_trace =
1404 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1405 int32_t depth = method_trace->GetLength()-1;
1406 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1407
1408 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1409
Elliott Hughes01158d72011-09-19 19:47:10 -07001410 jobjectArray result;
1411 ObjectArray<StackTraceElement>* java_traces;
1412 if (output_array != NULL) {
1413 // Reuse the array we were given.
1414 result = output_array;
1415 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1416 output_array));
1417 // ...adjusting the number of frames we'll write to not exceed the array length.
1418 depth = std::min(depth, java_traces->GetLength());
1419 } else {
1420 // Create java_trace array and place in local reference table
1421 java_traces = class_linker->AllocStackTraceElementArray(depth);
1422 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1423 }
1424
1425 if (stack_depth != NULL) {
1426 *stack_depth = depth;
1427 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001428
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001429 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001430 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1431 Method* method = down_cast<Method*>(method_trace->Get(i));
1432 uint32_t native_pc = pc_trace->Get(i);
1433 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001434 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001435 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001436
Ian Rogersaaa20802011-09-11 21:47:37 -07001437 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001438 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001439 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001440 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001441 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001442 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001443 method->ToDexPC(native_pc)));
1444#ifdef MOVING_GARBAGE_COLLECTOR
1445 // Re-read after potential GC
1446 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1447 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1448 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1449#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001450 java_traces->Set(i, obj);
1451 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001452 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001453}
1454
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001455void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001456 va_list args;
1457 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001458 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001459 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001460}
1461
1462void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1463 std::string msg;
1464 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001465
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001466 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001467 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001468 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001469 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001470 descriptor.erase(descriptor.length() - 1);
1471
1472 JNIEnv* env = GetJniEnv();
1473 jclass exception_class = env->FindClass(descriptor.c_str());
1474 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1475 int rc = env->ThrowNew(exception_class, msg.c_str());
1476 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001477 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001478}
1479
Elliott Hughes79082e32011-08-25 12:07:32 -07001480void Thread::ThrowOutOfMemoryError() {
1481 UNIMPLEMENTED(FATAL);
1482}
1483
Ian Rogersbdb03912011-09-14 00:55:44 -07001484class CatchBlockStackVisitor : public Thread::StackVisitor {
1485 public:
1486 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001487 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1488#ifndef NDEBUG
1489 handler_pc_ = 0xEBADC0DE;
1490 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1491#endif
1492 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001493
Ian Rogersbdb03912011-09-14 00:55:44 -07001494 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1495 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001496 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001497 if (method == NULL) {
1498 // This is the upcall, we remember the frame and last_pc so that we may
1499 // long jump to them
1500 handler_pc_ = pc;
1501 handler_frame_ = fr;
1502 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001503 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001504 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001505 if (method->IsPhony()) {
1506 // ignore callee save method
1507 } else if (method->IsNative()) {
1508 native_method_count_++;
1509 } else {
1510 // Move the PC back 2 bytes as a call will frequently terminate the
1511 // decoding of a particular instruction and we want to make sure we
1512 // get the Dex PC of the instruction with the call and not the
1513 // instruction following.
1514 pc -= 2;
1515 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001516 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001517 if (dex_pc != DexFile::kDexNoIndex) {
1518 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1519 if (found_dex_pc != DexFile::kDexNoIndex) {
1520 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001521 handler_pc_ = method->ToNativePC(found_dex_pc);
1522 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001523 }
1524 }
1525 if (!found_) {
1526 // Caller may be handler, fill in callee saves in context
1527 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001528 }
1529 }
1530 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001531
1532 // Did we find a catch block yet?
1533 bool found_;
1534 // The type of the exception catch block to find
1535 Class* to_find_;
1536 // Frame with found handler or last frame if no handler found
1537 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001538 // PC to branch to for the handler
1539 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001540 // Context that will be the target of the long jump
1541 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001542 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1543 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001544};
1545
Ian Rogersff1ed472011-09-20 13:46:24 -07001546void Thread::DeliverException() {
1547 Throwable *exception = GetException(); // Set exception on thread
1548 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001549
1550 Context* long_jump_context = GetLongJumpContext();
1551 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001552 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001553
Ian Rogers67375ac2011-09-14 00:55:44 -07001554 // Pop any SIRT
1555 if (catch_finder.native_method_count_ == 1) {
1556 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001557 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001558 // We only expect the stack crawl to have passed 1 native method as it's terminated
1559 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001560 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001561 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001562 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1563 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001564 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001565}
1566
Ian Rogersbdb03912011-09-14 00:55:44 -07001567Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001568 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001569 if (result == NULL) {
1570 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001571 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001572 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001573 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001574}
1575
Elliott Hughes5f791332011-09-15 17:45:30 -07001576bool Thread::HoldsLock(Object* object) {
1577 if (object == NULL) {
1578 return false;
1579 }
1580 return object->GetLockOwner() == thin_lock_id_;
1581}
1582
Elliott Hughes038a8062011-09-18 14:12:41 -07001583bool Thread::IsDaemon() {
1584 return gThread_daemon->GetBoolean(peer_);
1585}
1586
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001587// blx is 2-byte in Thumb2. Need to offset PC back to a call site.
1588static const int kThumb2InstSize = 2;
1589
Ian Rogersd6b1f612011-09-27 13:38:14 -07001590class ReferenceMapVisitor : public Thread::StackVisitor {
1591 public:
1592 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1593 context_(context), root_visitor_(root_visitor), arg_(arg) {
1594 }
1595
1596 void VisitFrame(const Frame& frame, uintptr_t pc) {
1597 Method* m = frame.GetMethod();
Ian Rogersd6b1f612011-09-27 13:38:14 -07001598
1599 // Process register map (which native and callee save methods don't have)
1600 if (!m->IsNative() && !m->IsPhony()) {
1601 UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
1602
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001603 const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(
1604 map.get(),
1605 m->ToDexPC(pc -kThumb2InstSize));
1606
1607 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
1608 << "@ PC: " << m->ToDexPC(pc - kThumb2InstSize);
1609
Ian Rogersd6b1f612011-09-27 13:38:14 -07001610 CHECK(reg_bitmap != NULL);
1611 ShortArray* vmap = m->GetVMapTable();
1612 // For all dex registers
1613 for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1614 // Does this register hold a reference?
1615 if (TestBitmap(reg, reg_bitmap)) {
1616 // Is the reference in the context or on the stack?
1617 bool in_context = false;
1618 int vmap_offset = -1;
1619 // TODO: take advantage of the registers being ordered
1620 for (int i = 0; i < vmap->GetLength(); i++) {
1621 if (vmap->Get(i) == reg) {
1622 in_context = true;
1623 vmap_offset = i;
1624 break;
1625 }
1626 }
1627 Object* ref;
1628 if (in_context) {
1629 // Compute the register we need to load from the context
1630 uint32_t spill_mask = m->GetCoreSpillMask();
1631 uint32_t reg = 0;
1632 for (int i = 0; i < vmap_offset; i++) {
1633 while ((spill_mask & 1) == 0) {
1634 CHECK_NE(spill_mask, 0u);
1635 spill_mask >>= 1;
1636 reg++;
1637 }
1638 }
1639 ref = reinterpret_cast<Object*>(context_->GetGPR(reg));
1640 } else {
1641 ref = reinterpret_cast<Object*>(frame.GetVReg(m ,reg));
1642 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001643 if (ref != NULL) {
1644 root_visitor_(ref, arg_);
1645 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001646 }
1647 }
1648 }
1649 context_->FillCalleeSaves(frame);
1650 }
1651
1652 private:
1653 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1654 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1655 }
1656
1657 // Context used to build up picture of callee saves
1658 Context* context_;
1659 // Call-back when we visit a root
1660 Heap::RootVisitor* root_visitor_;
1661 // Argument to call-back
1662 void* arg_;
1663};
1664
1665void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001666 if (exception_ != NULL) {
1667 visitor(exception_, arg);
1668 }
1669 if (peer_ != NULL) {
1670 visitor(peer_, arg);
1671 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001672 jni_env_->locals.VisitRoots(visitor, arg);
1673 jni_env_->monitors.VisitRoots(visitor, arg);
Ian Rogersd6b1f612011-09-27 13:38:14 -07001674 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1675 // delivery.
1676 Context* context = GetLongJumpContext();
1677 // Visit roots on this thread's stack
1678 ReferenceMapVisitor mapper(context, visitor, arg);
1679 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001680}
1681
Ian Rogersb033c752011-07-20 12:22:35 -07001682static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001683 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001684 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001685 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001686 "Blocked",
1687 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001688 "Initializing",
1689 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001690 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001691 "VmWait",
1692 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001693};
1694std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001695 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001696 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1697 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001698 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001699 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001700 }
1701 return os;
1702}
1703
Elliott Hughes330304d2011-08-12 14:28:05 -07001704std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1705 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001706 << ",pthread_t=" << thread.GetImpl()
1707 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001708 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001709 << ",state=" << thread.GetState()
1710 << ",peer=" << thread.GetPeer()
1711 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001712 return os;
1713}
1714
Elliott Hughes8daa0922011-09-11 13:46:25 -07001715} // namespace art