blob: 7adddfa932c2747cbb6145f9123bd2a32f67a09f [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 Carlstrom5d40f182011-09-26 22:29:18 -0700235 if (!klass->IsInitialized()
236 && !Runtime::Current()->GetClassLinker()->EnsureInitialized(klass, true)) {
237 DCHECK(Thread::Current()->IsExceptionPending());
238 return NULL; // Failure
239 }
Ian Rogers21d9e832011-09-23 17:05:09 -0700240 return klass->AllocObject();
241}
242
Ian Rogersb886da82011-09-23 16:27:54 -0700243// Helper function to alloc array for OP_FILLED_NEW_ARRAY
244extern "C" Array* artCheckAndArrayAllocFromCode(uint32_t type_idx, Method* method,
245 int32_t component_count) {
246 if (component_count < 0) {
247 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
248 component_count);
249 return NULL; // Failure
250 }
251 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
252 if (klass == NULL) { // Not in dex cache so try to resolve
253 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
254 if (klass == NULL) { // Error
255 DCHECK(Thread::Current()->IsExceptionPending());
256 return NULL; // Failure
257 }
258 }
259 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
260 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
261 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
262 "Bad filled array request for type %s",
263 PrettyDescriptor(klass->GetDescriptor()).c_str());
264 } else {
265 Thread::Current()->ThrowNewException("Ljava/lang/InternalError;",
266 "Found type %s; filled-new-array not implemented for anything but \'int\'",
267 PrettyDescriptor(klass->GetDescriptor()).c_str());
268 }
269 return NULL; // Failure
270 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700271 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700272 return Array::Alloc(klass, component_count);
273 }
274}
275
276// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
277// it cannot be resolved, throw an error. If it can, use it to create an array.
278extern "C" Array* artArrayAllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
279 if (component_count < 0) {
280 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
281 component_count);
282 return NULL; // Failure
283 }
284 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
285 if (klass == NULL) { // Not in dex cache so try to resolve
286 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
287 if (klass == NULL) { // Error
288 DCHECK(Thread::Current()->IsExceptionPending());
289 return NULL; // Failure
290 }
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700291 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700292 }
293 return Array::Alloc(klass, component_count);
buzbee1da522d2011-09-04 11:22:20 -0700294}
295
Ian Rogerse51a5112011-09-23 14:16:35 -0700296// 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 -0700297extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700298 DCHECK(a->IsClass()) << PrettyClass(a);
299 DCHECK(b->IsClass()) << PrettyClass(b);
Brian Carlstromc2282522011-09-17 10:33:14 -0700300 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700301 return 0; // Success
302 } else {
303 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700304 "%s cannot be cast to %s",
305 PrettyDescriptor(a->GetDescriptor()).c_str(),
306 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700307 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700308 }
buzbee2a475e72011-09-07 17:19:17 -0700309}
310
Ian Rogerse51a5112011-09-23 14:16:35 -0700311// Tests whether 'element' can be assigned into an array of type 'array_class'.
312// Returns 0 on success and -1 if an exception is pending.
313extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
314 DCHECK(array_class != NULL);
315 // element can't be NULL as we catch this is screened in runtime_support
316 Class* element_class = element->GetClass();
317 Class* component_type = array_class->GetComponentType();
318 if (component_type->IsAssignableFrom(element_class)) {
319 return 0; // Success
320 } else {
321 Thread::Current()->ThrowNewException("Ljava/lang/ArrayStoreException;",
Ian Rogersb886da82011-09-23 16:27:54 -0700322 "Cannot store an object of type %s in to an array of type %s",
323 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
324 PrettyDescriptor(array_class->GetDescriptor()).c_str());
Ian Rogerse51a5112011-09-23 14:16:35 -0700325 return -1; // Failure
326 }
327}
328
Ian Rogersff1ed472011-09-20 13:46:24 -0700329extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
330 DCHECK(obj != NULL); // Assumed to have been checked before entry
331 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700332}
333
Elliott Hughesd369bb72011-09-12 14:41:14 -0700334void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700335 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700336 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700337 DCHECK(thread->HoldsLock(obj));
338 // Only possible exception is NPE and is handled before entry
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700339 DCHECK(!thread->IsExceptionPending());
buzbee2a475e72011-09-07 17:19:17 -0700340}
341
buzbeec1f45042011-09-21 16:03:19 -0700342extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700343 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700344}
345
buzbee5ade1d22011-09-09 14:44:52 -0700346/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700347 * Fill the array with predefined constant values, throwing exceptions if the array is null or
348 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700349 *
350 * NOTE: When dealing with a raw dex file, the data to be copied uses
351 * little-endian ordering. Require that oat2dex do any required swapping
352 * so this routine can get by with a memcpy().
353 *
354 * Format of the data:
355 * ushort ident = 0x0300 magic value
356 * ushort width width of each element in the table
357 * uint size number of elements in the table
358 * ubyte data[size*width] table of data values (may contain a single-byte
359 * padding at the end)
360 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700361extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
362 DCHECK_EQ(table[0], 0x0300);
363 if (array == NULL) {
364 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
365 "null array in fill array");
366 return -1; // Error
367 }
368 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
369 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
370 if (static_cast<int32_t>(size) > array->GetLength()) {
371 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
372 "failed array fill. length=%d; index=%d",
373 array->GetLength(), size);
374 return -1; // Error
375 }
376 uint16_t width = table[1];
377 uint32_t size_in_bytes = size * width;
378 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
379 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700380}
381
382// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700383extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
384 Object* this_object ,
385 Method* caller_method) {
386 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700387 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700388 thread->ThrowNewException("Ljava/lang/NullPointerException;",
389 "null receiver during interface dispatch");
390 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700391 }
392 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
393 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
394 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700395 // Could not resolve interface method. Throw error and unwind
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700396 CHECK(thread->IsExceptionPending());
Ian Rogersff1ed472011-09-20 13:46:24 -0700397 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700398 }
399 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700400 if (method == NULL) {
401 CHECK(thread->IsExceptionPending());
402 return 0;
403 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700404 const void* code = method->GetCode();
405
406 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
407 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
408 uint64_t result = ((code_uint << 32) | method_uint);
409 return result;
410}
411
buzbee5ade1d22011-09-09 14:44:52 -0700412// TODO: move to more appropriate location
413/*
414 * Float/double conversion requires clamping to min and max of integer form. If
415 * target doesn't support this normally, use these.
416 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700417int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700418 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
419 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
420 if (d >= kMaxLong)
421 return (int64_t)0x7fffffffffffffffULL;
422 else if (d <= kMinLong)
423 return (int64_t)0x8000000000000000ULL;
424 else if (d != d) // NaN case
425 return 0;
426 else
427 return (int64_t)d;
428}
429
Elliott Hughesd369bb72011-09-12 14:41:14 -0700430int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700431 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
432 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
433 if (f >= kMaxLong)
434 return (int64_t)0x7fffffffffffffffULL;
435 else if (f <= kMinLong)
436 return (int64_t)0x8000000000000000ULL;
437 else if (f != f) // NaN case
438 return 0;
439 else
440 return (int64_t)f;
441}
442
Brian Carlstrom16192862011-09-12 17:50:06 -0700443// Return value helper for jobject return types
444static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
445 return thread->DecodeJObject(obj);
446}
447
buzbee3ea4ec52011-08-22 17:37:19 -0700448void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700449#if defined(__arm__)
450 pShlLong = art_shl_long;
451 pShrLong = art_shr_long;
452 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700453 pIdiv = __aeabi_idiv;
454 pIdivmod = __aeabi_idivmod;
455 pI2f = __aeabi_i2f;
456 pF2iz = __aeabi_f2iz;
457 pD2f = __aeabi_d2f;
458 pF2d = __aeabi_f2d;
459 pD2iz = __aeabi_d2iz;
460 pL2f = __aeabi_l2f;
461 pL2d = __aeabi_l2d;
462 pFadd = __aeabi_fadd;
463 pFsub = __aeabi_fsub;
464 pFdiv = __aeabi_fdiv;
465 pFmul = __aeabi_fmul;
466 pFmodf = fmodf;
467 pDadd = __aeabi_dadd;
468 pDsub = __aeabi_dsub;
469 pDdiv = __aeabi_ddiv;
470 pDmul = __aeabi_dmul;
471 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700472 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700473 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700474 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700475 pArrayAllocFromCode = art_array_alloc_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700476 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700477 pCheckAndArrayAllocFromCode = art_check_and_array_alloc_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700478 pCheckCastFromCode = art_check_cast_from_code;
479 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700480 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700481 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700482 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700483 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
484 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700485 pThrowInternalErrorFromCode = art_throw_internal_error_from_code;
486 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
487 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700488 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700489 pThrowRuntimeExceptionFromCode = art_throw_runtime_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700490 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700491 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700492 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700493#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700494 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700495 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700496 pF2l = F2L;
497 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700498 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700499 pGet32Static = Field::Get32StaticFromCode;
500 pSet32Static = Field::Set32StaticFromCode;
501 pGet64Static = Field::Get64StaticFromCode;
502 pSet64Static = Field::Set64StaticFromCode;
503 pGetObjStatic = Field::GetObjStaticFromCode;
504 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700505 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700506 pResolveMethodFromCode = ResolveMethodFromCode;
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700507 pInstanceofNonTrivialFromCode = Object::InstanceOfFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700508 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700509 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700510 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700511 pFindNativeMethod = FindNativeMethod;
512 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700513 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700514}
515
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700516void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700517 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
518 DCHECK_NE(frame_size, 0u);
519 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700520 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700521 sp_ = reinterpret_cast<Method**>(next_sp);
Elliott Hughes80609252011-09-23 17:24:51 -0700522 if (*sp_ != NULL) {
523 DCHECK((*sp_)->GetClass() == Method::GetMethodClass() ||
524 (*sp_)->GetClass() == Method::GetConstructorClass());
Ian Rogersff1ed472011-09-20 13:46:24 -0700525 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700526}
527
Ian Rogers90865722011-09-19 11:11:44 -0700528bool Frame::HasMethod() const {
529 return GetMethod() != NULL && (!GetMethod()->IsPhony());
530}
531
Ian Rogersbdb03912011-09-14 00:55:44 -0700532uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700533 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700534 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700535}
536
Ian Rogersd6b1f612011-09-27 13:38:14 -0700537uintptr_t Frame::GetVReg(Method* method, int vreg) const {
538 DCHECK(method == GetMethod());
539 int offset = oatVRegOffsetFromMethod(method, vreg);
540 byte* vreg_addr = reinterpret_cast<byte*>(sp_) + offset;
541 return *reinterpret_cast<uintptr_t*>(vreg_addr);
542}
543
Ian Rogersbdb03912011-09-14 00:55:44 -0700544uintptr_t Frame::LoadCalleeSave(int num) const {
545 // Callee saves are held at the top of the frame
546 Method* method = GetMethod();
547 DCHECK(method != NULL);
548 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700549 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700550#if defined(__i386__)
551 save_addr -= kPointerSize; // account for return address
552#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700553 return *reinterpret_cast<uintptr_t*>(save_addr);
554}
555
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700557 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700558 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700560}
561
Brian Carlstrom78128a62011-09-15 17:21:19 -0700562void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700563 Thread* self = reinterpret_cast<Thread*>(arg);
564 Runtime* runtime = Runtime::Current();
565
566 self->Attach(runtime);
567
Elliott Hughes038a8062011-09-18 14:12:41 -0700568 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700569 if (thread_name != NULL) {
570 SetThreadName(thread_name->ToModifiedUtf8().c_str());
571 }
572
573 // Wait until it's safe to start running code. (There may have been a suspend-all
574 // in progress while we were starting up.)
575 runtime->GetThreadList()->WaitForGo();
576
577 // TODO: say "hi" to the debugger.
578 //if (gDvm.debuggerConnected) {
579 // dvmDbgPostThreadStart(self);
580 //}
581
582 // Invoke the 'run' method of our java.lang.Thread.
583 CHECK(self->peer_ != NULL);
584 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700585 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700586 m->Invoke(self, receiver, NULL, NULL);
587
588 // Detach.
589 runtime->GetThreadList()->Unregister();
590
Carl Shapirob5573532011-07-12 18:22:59 -0700591 return NULL;
592}
593
Elliott Hughes93e74e82011-09-13 11:07:03 -0700594void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700595 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700596}
597
Elliott Hughes01158d72011-09-19 19:47:10 -0700598Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
599 Object* thread = Decode<Object*>(env, java_thread);
600 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
601}
602
Elliott Hughesd369bb72011-09-12 14:41:14 -0700603void Thread::Create(Object* peer, size_t stack_size) {
604 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700605
Elliott Hughesd369bb72011-09-12 14:41:14 -0700606 if (stack_size == 0) {
607 stack_size = Runtime::Current()->GetDefaultStackSize();
608 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700609
Elliott Hughes93e74e82011-09-13 11:07:03 -0700610 Thread* native_thread = new Thread;
611 native_thread->peer_ = peer;
612
613 // Thread.start is synchronized, so we know that vmData is 0,
614 // and know that we're not racing to assign it.
615 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700616
617 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700618 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
619 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
620 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
621 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
622 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700623
624 // Let the child know when it's safe to start running.
625 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700626}
627
Elliott Hughes93e74e82011-09-13 11:07:03 -0700628void Thread::Attach(const Runtime* runtime) {
629 InitCpu();
630 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700631
Elliott Hughes93e74e82011-09-13 11:07:03 -0700632 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700633
Elliott Hughes93e74e82011-09-13 11:07:03 -0700634 tid_ = ::art::GetTid();
635 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700636
Elliott Hughes93e74e82011-09-13 11:07:03 -0700637 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700638
Elliott Hughes8d768a92011-09-14 16:35:25 -0700639 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700640
Elliott Hughes93e74e82011-09-13 11:07:03 -0700641 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700642
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700643 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700644}
645
646Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
647 Thread* self = new Thread;
648 self->Attach(runtime);
649
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700650 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700651
652 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700653
654 // If we're the main thread, ClassLinker won't be created until after we're attached,
655 // so that thread needs a two-stage attach. Regular threads don't need this hack.
656 if (self->thin_lock_id_ != ThreadList::kMainId) {
657 self->CreatePeer(name, as_daemon);
658 }
659
660 return self;
661}
662
Elliott Hughesd369bb72011-09-12 14:41:14 -0700663jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
664 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
665 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
666 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
667 // This will be null in the compiler (and tests), but never in a running system.
668 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
669 return thread_group;
670}
671
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700672void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700673 JNIEnv* env = jni_env_;
674
Elliott Hughesd369bb72011-09-12 14:41:14 -0700675 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
676 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700677 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700678 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700679 jboolean thread_is_daemon = as_daemon;
680
681 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700682 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700683
Elliott Hughes8daa0922011-09-11 13:46:25 -0700684 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700685 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700686 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700687
688 // Because we mostly run without code available (in the compiler, in tests), we
689 // manually assign the fields the constructor should have set.
690 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700691 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
692 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
693 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
694 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700695}
696
Elliott Hughesbe759c62011-09-08 19:38:21 -0700697void Thread::InitStackHwm() {
698 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700699 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700700
Ian Rogers932746a2011-09-22 18:57:50 -0700701 void* temp_stack_base;
702 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
703 __FUNCTION__);
704 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700705
Ian Rogers932746a2011-09-22 18:57:50 -0700706 if (stack_size_ <= kStackOverflowReservedBytes) {
707 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700708 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700709
Ian Rogers932746a2011-09-22 18:57:50 -0700710 // Set stack_end_ to the bottom of the stack saving space of stack overflows
711 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700712
713 // Sanity check.
714 int stack_variable;
715 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700716
Elliott Hughes8d768a92011-09-14 16:35:25 -0700717 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700718}
719
Elliott Hughesa0957642011-09-02 14:27:33 -0700720void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700721 DumpState(os);
722 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700723}
724
Elliott Hughesd92bec42011-09-02 17:04:36 -0700725std::string GetSchedulerGroup(pid_t tid) {
726 // /proc/<pid>/group looks like this:
727 // 2:devices:/
728 // 1:cpuacct,cpu:/
729 // We want the third field from the line whose second field contains the "cpu" token.
730 std::string cgroup_file;
731 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
732 return "";
733 }
734 std::vector<std::string> cgroup_lines;
735 Split(cgroup_file, '\n', cgroup_lines);
736 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
737 std::vector<std::string> cgroup_fields;
738 Split(cgroup_lines[i], ':', cgroup_fields);
739 std::vector<std::string> cgroups;
740 Split(cgroup_fields[1], ',', cgroups);
741 for (size_t i = 0; i < cgroups.size(); ++i) {
742 if (cgroups[i] == "cpu") {
743 return cgroup_fields[2].substr(1); // Skip the leading slash.
744 }
745 }
746 }
747 return "";
748}
749
750void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700751 std::string thread_name("<native thread without managed peer>");
752 std::string group_name;
753 int priority;
754 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700755
Elliott Hughesd369bb72011-09-12 14:41:14 -0700756 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700757 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700758 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700759 priority = gThread_priority->GetInt(peer_);
760 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700761
Elliott Hughes038a8062011-09-18 14:12:41 -0700762 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700763 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700764 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700765 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
766 }
767 } else {
768 // 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 -0700769 std::string stats;
770 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
771 size_t start = stats.find('(') + 1;
772 size_t end = stats.find(')') - start;
773 thread_name = stats.substr(start, end);
774 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700775 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700776 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700777
778 int policy;
779 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700780 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700781
782 std::string scheduler_group(GetSchedulerGroup(GetTid()));
783 if (scheduler_group.empty()) {
784 scheduler_group = "default";
785 }
786
Elliott Hughesd92bec42011-09-02 17:04:36 -0700787 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700788 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700789 os << " daemon";
790 }
791 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700792 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700793 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700794
Elliott Hughesd92bec42011-09-02 17:04:36 -0700795 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700796 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700797 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700798 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700799 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700800 << " self=" << reinterpret_cast<const void*>(this) << "\n";
801 os << " | sysTid=" << GetTid()
802 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
803 << " sched=" << policy << "/" << sp.sched_priority
804 << " cgrp=" << scheduler_group
805 << " handle=" << GetImpl() << "\n";
806
807 // Grab the scheduler stats for this thread.
808 std::string scheduler_stats;
809 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
810 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
811 } else {
812 scheduler_stats = "0 0 0";
813 }
814
815 int utime = 0;
816 int stime = 0;
817 int task_cpu = 0;
818 std::string stats;
819 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
820 // Skip the command, which may contain spaces.
821 stats = stats.substr(stats.find(')') + 2);
822 // Extract the three fields we care about.
823 std::vector<std::string> fields;
824 Split(stats, ' ', fields);
825 utime = strtoull(fields[11].c_str(), NULL, 10);
826 stime = strtoull(fields[12].c_str(), NULL, 10);
827 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
828 }
829
830 os << " | schedstat=( " << scheduler_stats << " )"
831 << " utm=" << utime
832 << " stm=" << stime
833 << " core=" << task_cpu
834 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
835}
836
Elliott Hughesd369bb72011-09-12 14:41:14 -0700837struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700838 StackDumpVisitor(std::ostream& os, const Thread* thread)
839 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700840 }
841
Ian Rogersbdb03912011-09-14 00:55:44 -0700842 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700843 }
844
Ian Rogersbdb03912011-09-14 00:55:44 -0700845 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700846 if (!frame.HasMethod()) {
847 return;
848 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700849
850 Method* m = frame.GetMethod();
851 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700852 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700853 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
854
855 os << " at " << PrettyMethod(m, false);
856 if (m->IsNative()) {
857 os << "(Native method)";
858 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700859 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700860 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
861 }
862 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700863
864 if (frame_count++ == 0) {
865 Monitor::DescribeWait(os, thread);
866 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700867 }
868
869 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700870 const Thread* thread;
871 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700872};
873
Elliott Hughesd92bec42011-09-02 17:04:36 -0700874void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700875 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700876 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700877}
878
Elliott Hughes8d768a92011-09-14 16:35:25 -0700879Thread::State Thread::SetState(Thread::State new_state) {
880 Thread::State old_state = state_;
881 if (old_state == new_state) {
882 return old_state;
883 }
884
885 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
886 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
887
888 if (new_state == Thread::kRunnable) {
889 /*
890 * Change our status to Thread::kRunnable. The transition requires
891 * that we check for pending suspension, because the VM considers
892 * us to be "asleep" in all other states, and another thread could
893 * be performing a GC now.
894 *
895 * The order of operations is very significant here. One way to
896 * do this wrong is:
897 *
898 * GCing thread Our thread (in kNative)
899 * ------------ ----------------------
900 * check suspend count (== 0)
901 * SuspendAllThreads()
902 * grab suspend-count lock
903 * increment all suspend counts
904 * release suspend-count lock
905 * check thread state (== kNative)
906 * all are suspended, begin GC
907 * set state to kRunnable
908 * (continue executing)
909 *
910 * We can correct this by grabbing the suspend-count lock and
911 * performing both of our operations (check suspend count, set
912 * state) while holding it, now we need to grab a mutex on every
913 * transition to kRunnable.
914 *
915 * What we do instead is change the order of operations so that
916 * the transition to kRunnable happens first. If we then detect
917 * that the suspend count is nonzero, we switch to kSuspended.
918 *
919 * Appropriate compiler and memory barriers are required to ensure
920 * that the operations are observed in the expected order.
921 *
922 * This does create a small window of opportunity where a GC in
923 * progress could observe what appears to be a running thread (if
924 * it happens to look between when we set to kRunnable and when we
925 * switch to kSuspended). At worst this only affects assertions
926 * and thread logging. (We could work around it with some sort
927 * of intermediate "pre-running" state that is generally treated
928 * as equivalent to running, but that doesn't seem worthwhile.)
929 *
930 * We can also solve this by combining the "status" and "suspend
931 * count" fields into a single 32-bit value. This trades the
932 * store/load barrier on transition to kRunnable for an atomic RMW
933 * op on all transitions and all suspend count updates (also, all
934 * accesses to status or the thread count require bit-fiddling).
935 * It also eliminates the brief transition through kRunnable when
936 * the thread is supposed to be suspended. This is possibly faster
937 * on SMP and slightly more correct, but less convenient.
938 */
939 android_atomic_acquire_store(new_state, addr);
940 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
941 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
942 }
943 } else {
944 /*
945 * Not changing to Thread::kRunnable. No additional work required.
946 *
947 * We use a releasing store to ensure that, if we were runnable,
948 * any updates we previously made to objects on the managed heap
949 * will be observed before the state change.
950 */
951 android_atomic_release_store(new_state, addr);
952 }
953
954 return old_state;
955}
956
957void Thread::WaitUntilSuspended() {
958 // TODO: dalvik dropped the waiting thread's priority after a while.
959 // TODO: dalvik timed out and aborted.
960 useconds_t delay = 0;
961 while (GetState() == Thread::kRunnable) {
962 useconds_t new_delay = delay * 2;
963 CHECK_GE(new_delay, delay);
964 delay = new_delay;
965 if (delay == 0) {
966 sched_yield();
967 delay = 10000;
968 } else {
969 usleep(delay);
970 }
971 }
972}
973
Elliott Hughesbe759c62011-09-08 19:38:21 -0700974void Thread::ThreadExitCallback(void* arg) {
975 Thread* self = reinterpret_cast<Thread*>(arg);
976 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700977}
978
Elliott Hughesbe759c62011-09-08 19:38:21 -0700979void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700980 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700981 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700982
983 // Double-check the TLS slot allocation.
984 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700985 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700986 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700987}
Carl Shapirob5573532011-07-12 18:22:59 -0700988
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700989// TODO: make more accessible?
990Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
991 Class* c = class_linker->FindPrimitiveClass(descriptor);
992 CHECK(c != NULL) << descriptor;
993 return c;
994}
995
996// TODO: make more accessible?
997Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
998 Class* c = class_linker->FindSystemClass(descriptor);
999 CHECK(c != NULL) << descriptor;
1000 return c;
1001}
1002
1003// TODO: make more accessible?
1004Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
1005 Field* f = c->FindDeclaredInstanceField(name, type);
1006 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
1007 return f;
1008}
1009
1010// TODO: make more accessible?
1011Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
1012 Method* m = c->FindVirtualMethod(name, signature);
1013 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
1014 return m;
1015}
1016
Elliott Hughes038a8062011-09-18 14:12:41 -07001017void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -07001018 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
1019 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001020
1021 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
1022 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
1023 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
1024 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
1025 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
1026 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
1027 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
1028 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
1029
1030 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
1031 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
1032 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
1033 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
1034 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
1035 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
1036 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
1037 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
1038 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
1039
1040 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
1041 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
1042 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
1043 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -07001044
1045 // Finish attaching the main thread.
1046 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -07001047}
1048
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001049void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -07001050 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001051}
1052
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001053uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
1054 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
1055 return ThreadList::kInvalidId;
1056 }
1057 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
1058 if (managed_thread == NULL) {
1059 return ThreadList::kInvalidId;
1060 }
1061 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
1062 Thread* thread = reinterpret_cast<Thread*>(vmData);
1063 if (thread == NULL) {
1064 return ThreadList::kInvalidId;
1065 }
1066 return thread->GetThinLockId();
1067}
1068
Elliott Hughesdcc24742011-09-07 14:02:44 -07001069Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -07001070 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001071 top_of_managed_stack_(),
1072 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001073 wait_mutex_(new Mutex("Thread wait mutex")),
1074 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001075 wait_monitor_(NULL),
1076 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001077 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001078 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001079 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001080 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001081 native_to_managed_record_(NULL),
1082 top_sirt_(NULL),
1083 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001084 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001085 self_(NULL),
1086 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001087 exception_(NULL),
1088 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001089 class_loader_override_(NULL),
1090 long_jump_context_(NULL) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001091 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001092}
1093
Elliott Hughes02b48d12011-09-07 17:15:51 -07001094void MonitorExitVisitor(const Object* object, void*) {
1095 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -07001096 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001097}
1098
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001099Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -07001100 SetState(Thread::kRunnable);
1101
Elliott Hughes02b48d12011-09-07 17:15:51 -07001102 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -07001103 if (jni_env_ != NULL) {
1104 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
1105 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001106
Elliott Hughes93e74e82011-09-13 11:07:03 -07001107 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001108 Object* group = gThread_group->GetObject(peer_);
1109
1110 // Handle any pending exception.
1111 if (IsExceptionPending()) {
1112 // Get and clear the exception.
1113 Object* exception = GetException();
1114 ClearException();
1115
1116 // If the thread has its own handler, use that.
1117 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1118 if (handler == NULL) {
1119 // Otherwise use the thread group's default handler.
1120 handler = group;
1121 }
1122
1123 // Call the handler.
1124 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
1125 Object* args[2];
1126 args[0] = peer_;
1127 args[1] = exception;
1128 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
1129
1130 // If the handler threw, clear that exception too.
1131 ClearException();
1132 }
1133
1134 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -07001135 // group can be null if we're in the compiler or a test.
1136 if (group != NULL) {
1137 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
1138 Object* args = peer_;
1139 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
1140 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001141
1142 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -07001143 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001144
Elliott Hughes29f27422011-09-18 16:02:18 -07001145 // TODO: say "bye" to the debugger.
1146 //if (gDvm.debuggerConnected) {
1147 // dvmDbgPostThreadDeath(self);
1148 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001149
Elliott Hughes29f27422011-09-18 16:02:18 -07001150 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1151 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -07001152 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -07001153 Object* lock = gThread_lock->GetObject(peer_);
1154 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -07001155 if (lock != NULL) {
1156 lock->MonitorEnter(self);
1157 lock->NotifyAll();
1158 lock->MonitorExit(self);
1159 }
1160 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001161
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001162 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001163 jni_env_ = NULL;
1164
1165 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001166
1167 delete wait_cond_;
1168 delete wait_mutex_;
1169
1170 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001171}
1172
Ian Rogers408f79a2011-08-23 18:22:33 -07001173size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001174 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001175 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001176 count += cur->NumberOfReferences();
1177 }
1178 return count;
1179}
1180
Ian Rogers408f79a2011-08-23 18:22:33 -07001181bool Thread::SirtContains(jobject obj) {
1182 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1183 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001184 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001185 // A SIRT should always have a jobject/jclass as a native method is passed
1186 // in a this pointer or a class
1187 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001188 if ((&cur->References()[0] <= sirt_entry) &&
1189 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001190 return true;
1191 }
1192 }
1193 return false;
1194}
1195
Ian Rogers67375ac2011-09-14 00:55:44 -07001196void Thread::PopSirt() {
1197 CHECK(top_sirt_ != NULL);
1198 top_sirt_ = top_sirt_->Link();
1199}
1200
Ian Rogers408f79a2011-08-23 18:22:33 -07001201Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001202 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001203 if (obj == NULL) {
1204 return NULL;
1205 }
1206 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1207 IndirectRefKind kind = GetIndirectRefKind(ref);
1208 Object* result;
1209 switch (kind) {
1210 case kLocal:
1211 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001212 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001213 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001214 break;
1215 }
1216 case kGlobal:
1217 {
1218 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1219 IndirectReferenceTable& globals = vm->globals;
1220 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001221 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001222 break;
1223 }
1224 case kWeakGlobal:
1225 {
1226 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1227 IndirectReferenceTable& weak_globals = vm->weak_globals;
1228 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001229 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001230 if (result == kClearedJniWeakGlobal) {
1231 // This is a special case where it's okay to return NULL.
1232 return NULL;
1233 }
1234 break;
1235 }
1236 case kSirtOrInvalid:
1237 default:
1238 // TODO: make stack indirect reference table lookup more efficient
1239 // Check if this is a local reference in the SIRT
1240 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001241 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001242 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001243 // Assume an invalid local reference is actually a direct pointer.
1244 result = reinterpret_cast<Object*>(obj);
1245 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001246 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001247 }
1248 }
1249
1250 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001251 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1252 JniAbort(NULL);
1253 } else {
1254 if (result != kInvalidIndirectRefObject) {
1255 Heap::VerifyObject(result);
1256 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001257 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001258 return result;
1259}
1260
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001261class CountStackDepthVisitor : public Thread::StackVisitor {
1262 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001263 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001264
Elliott Hughes29f27422011-09-18 16:02:18 -07001265 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1266 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001267 // Note we also skip the frame if it doesn't have a method (namely the callee
1268 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001269 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001270 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001271 skipping_ = false;
1272 }
1273 if (!skipping_) {
1274 ++depth_;
1275 } else {
1276 ++skip_depth_;
1277 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001278 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001279
1280 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001281 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001282 }
1283
Elliott Hughes29f27422011-09-18 16:02:18 -07001284 int GetSkipDepth() const {
1285 return skip_depth_;
1286 }
1287
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001288 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001289 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001290 uint32_t skip_depth_;
1291 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001292};
1293
Ian Rogersaaa20802011-09-11 21:47:37 -07001294class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001295 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001296 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1297 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001298 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001299 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001300 // Register a local reference as IntArray::Alloc may trigger GC
1301 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1302 pc_trace_ = IntArray::Alloc(depth);
1303#ifdef MOVING_GARBAGE_COLLECTOR
1304 // Re-read after potential GC
1305 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1306#endif
1307 // Save PC trace in last element of method trace, also places it into the
1308 // object graph.
1309 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001310 }
1311
Ian Rogersaaa20802011-09-11 21:47:37 -07001312 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001313
Ian Rogersbdb03912011-09-14 00:55:44 -07001314 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001315 if (skip_depth_ > 0) {
1316 skip_depth_--;
1317 return;
1318 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001319 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001320 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001321 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001322 }
1323
Ian Rogersaaa20802011-09-11 21:47:37 -07001324 jobject GetInternalStackTrace() const {
1325 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001326 }
1327
1328 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001329 // How many more frames to skip.
1330 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001331 // Current position down stack trace
1332 uint32_t count_;
1333 // Array of return PC values
1334 IntArray* pc_trace_;
1335 // An array of the methods on the stack, the last entry is a reference to the
1336 // PC trace
1337 ObjectArray<Object>* method_trace_;
1338 // Local indirect reference table entry for method trace
1339 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001340};
1341
Ian Rogersaaa20802011-09-11 21:47:37 -07001342void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001343 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001344 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001345 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1346 // CHECK(native_to_managed_record_ != NULL);
1347 NativeToManagedRecord* record = native_to_managed_record_;
1348
Ian Rogersbdb03912011-09-14 00:55:44 -07001349 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001350 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001351 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1352 visitor->VisitFrame(frame, pc);
1353 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001354 }
1355 if (record == NULL) {
1356 break;
1357 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001358 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001359 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001360 pc = record->last_top_of_managed_stack_pc_;
1361 record = record->link_;
1362 }
1363}
1364
Ian Rogers67375ac2011-09-14 00:55:44 -07001365void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001366 Frame frame = GetTopOfStack();
1367 uintptr_t pc = top_of_managed_stack_pc_;
1368
1369 if (frame.GetSP() != 0) {
1370 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001371 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001372 visitor->VisitFrame(frame, pc);
1373 pc = frame.GetReturnPC();
1374 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001375 if (include_upcall) {
1376 visitor->VisitFrame(frame, pc);
1377 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001378 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001379}
1380
Elliott Hughes01158d72011-09-19 19:47:10 -07001381jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001382 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001383 CountStackDepthVisitor count_visitor;
1384 WalkStack(&count_visitor);
1385 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001386 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001387
Ian Rogersaaa20802011-09-11 21:47:37 -07001388 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001389 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001390
1391 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001392 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001393 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001394
Ian Rogersaaa20802011-09-11 21:47:37 -07001395 return build_trace_visitor.GetInternalStackTrace();
1396}
1397
Elliott Hughes01158d72011-09-19 19:47:10 -07001398jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1399 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001400 // Transition into runnable state to work on Object*/Array*
1401 ScopedJniThreadState ts(env);
1402
1403 // Decode the internal stack trace into the depth, method trace and PC trace
1404 ObjectArray<Object>* method_trace =
1405 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1406 int32_t depth = method_trace->GetLength()-1;
1407 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1408
1409 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1410
Elliott Hughes01158d72011-09-19 19:47:10 -07001411 jobjectArray result;
1412 ObjectArray<StackTraceElement>* java_traces;
1413 if (output_array != NULL) {
1414 // Reuse the array we were given.
1415 result = output_array;
1416 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1417 output_array));
1418 // ...adjusting the number of frames we'll write to not exceed the array length.
1419 depth = std::min(depth, java_traces->GetLength());
1420 } else {
1421 // Create java_trace array and place in local reference table
1422 java_traces = class_linker->AllocStackTraceElementArray(depth);
1423 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1424 }
1425
1426 if (stack_depth != NULL) {
1427 *stack_depth = depth;
1428 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001429
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001430 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001431 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1432 Method* method = down_cast<Method*>(method_trace->Get(i));
1433 uint32_t native_pc = pc_trace->Get(i);
1434 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001435 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001436 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001437
Ian Rogersaaa20802011-09-11 21:47:37 -07001438 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001439 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001440 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001441 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001442 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001443 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001444 method->ToDexPC(native_pc)));
1445#ifdef MOVING_GARBAGE_COLLECTOR
1446 // Re-read after potential GC
1447 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1448 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1449 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1450#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001451 java_traces->Set(i, obj);
1452 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001453 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001454}
1455
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001456void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001457 va_list args;
1458 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001459 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001460 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001461}
1462
1463void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1464 std::string msg;
1465 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001466
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001467 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001468 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001469 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001470 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001471 descriptor.erase(descriptor.length() - 1);
1472
1473 JNIEnv* env = GetJniEnv();
1474 jclass exception_class = env->FindClass(descriptor.c_str());
1475 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1476 int rc = env->ThrowNew(exception_class, msg.c_str());
1477 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001478 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001479}
1480
Elliott Hughes79082e32011-08-25 12:07:32 -07001481void Thread::ThrowOutOfMemoryError() {
1482 UNIMPLEMENTED(FATAL);
1483}
1484
Ian Rogersbdb03912011-09-14 00:55:44 -07001485class CatchBlockStackVisitor : public Thread::StackVisitor {
1486 public:
1487 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001488 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1489#ifndef NDEBUG
1490 handler_pc_ = 0xEBADC0DE;
1491 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1492#endif
1493 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001494
Ian Rogersbdb03912011-09-14 00:55:44 -07001495 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1496 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001497 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001498 if (method == NULL) {
1499 // This is the upcall, we remember the frame and last_pc so that we may
1500 // long jump to them
1501 handler_pc_ = pc;
1502 handler_frame_ = fr;
1503 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001504 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001505 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001506 if (method->IsPhony()) {
1507 // ignore callee save method
1508 } else if (method->IsNative()) {
1509 native_method_count_++;
1510 } else {
1511 // Move the PC back 2 bytes as a call will frequently terminate the
1512 // decoding of a particular instruction and we want to make sure we
1513 // get the Dex PC of the instruction with the call and not the
1514 // instruction following.
1515 pc -= 2;
1516 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001517 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001518 if (dex_pc != DexFile::kDexNoIndex) {
1519 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1520 if (found_dex_pc != DexFile::kDexNoIndex) {
1521 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001522 handler_pc_ = method->ToNativePC(found_dex_pc);
1523 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001524 }
1525 }
1526 if (!found_) {
1527 // Caller may be handler, fill in callee saves in context
1528 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001529 }
1530 }
1531 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001532
1533 // Did we find a catch block yet?
1534 bool found_;
1535 // The type of the exception catch block to find
1536 Class* to_find_;
1537 // Frame with found handler or last frame if no handler found
1538 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001539 // PC to branch to for the handler
1540 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001541 // Context that will be the target of the long jump
1542 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001543 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1544 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001545};
1546
Ian Rogersff1ed472011-09-20 13:46:24 -07001547void Thread::DeliverException() {
1548 Throwable *exception = GetException(); // Set exception on thread
1549 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001550
1551 Context* long_jump_context = GetLongJumpContext();
1552 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001553 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001554
Ian Rogers67375ac2011-09-14 00:55:44 -07001555 // Pop any SIRT
1556 if (catch_finder.native_method_count_ == 1) {
1557 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001558 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001559 // We only expect the stack crawl to have passed 1 native method as it's terminated
1560 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001561 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001562 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001563 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1564 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001565 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001566}
1567
Ian Rogersbdb03912011-09-14 00:55:44 -07001568Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001569 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001570 if (result == NULL) {
1571 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001572 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001573 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001574 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001575}
1576
Elliott Hughes5f791332011-09-15 17:45:30 -07001577bool Thread::HoldsLock(Object* object) {
1578 if (object == NULL) {
1579 return false;
1580 }
1581 return object->GetLockOwner() == thin_lock_id_;
1582}
1583
Elliott Hughes038a8062011-09-18 14:12:41 -07001584bool Thread::IsDaemon() {
1585 return gThread_daemon->GetBoolean(peer_);
1586}
1587
Ian Rogersd6b1f612011-09-27 13:38:14 -07001588class ReferenceMapVisitor : public Thread::StackVisitor {
1589 public:
1590 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1591 context_(context), root_visitor_(root_visitor), arg_(arg) {
1592 }
1593
1594 void VisitFrame(const Frame& frame, uintptr_t pc) {
1595 Method* m = frame.GetMethod();
1596 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false);
1597
1598 // Process register map (which native and callee save methods don't have)
1599 if (!m->IsNative() && !m->IsPhony()) {
1600 UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
1601
1602 const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(map.get(), m->ToDexPC(pc));
1603 CHECK(reg_bitmap != NULL);
1604 ShortArray* vmap = m->GetVMapTable();
1605 // For all dex registers
1606 for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1607 // Does this register hold a reference?
1608 if (TestBitmap(reg, reg_bitmap)) {
1609 // Is the reference in the context or on the stack?
1610 bool in_context = false;
1611 int vmap_offset = -1;
1612 // TODO: take advantage of the registers being ordered
1613 for (int i = 0; i < vmap->GetLength(); i++) {
1614 if (vmap->Get(i) == reg) {
1615 in_context = true;
1616 vmap_offset = i;
1617 break;
1618 }
1619 }
1620 Object* ref;
1621 if (in_context) {
1622 // Compute the register we need to load from the context
1623 uint32_t spill_mask = m->GetCoreSpillMask();
1624 uint32_t reg = 0;
1625 for (int i = 0; i < vmap_offset; i++) {
1626 while ((spill_mask & 1) == 0) {
1627 CHECK_NE(spill_mask, 0u);
1628 spill_mask >>= 1;
1629 reg++;
1630 }
1631 }
1632 ref = reinterpret_cast<Object*>(context_->GetGPR(reg));
1633 } else {
1634 ref = reinterpret_cast<Object*>(frame.GetVReg(m ,reg));
1635 }
1636 root_visitor_(ref, arg_);
1637 }
1638 }
1639 }
1640 context_->FillCalleeSaves(frame);
1641 }
1642
1643 private:
1644 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1645 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1646 }
1647
1648 // Context used to build up picture of callee saves
1649 Context* context_;
1650 // Call-back when we visit a root
1651 Heap::RootVisitor* root_visitor_;
1652 // Argument to call-back
1653 void* arg_;
1654};
1655
1656void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001657 if (exception_ != NULL) {
1658 visitor(exception_, arg);
1659 }
1660 if (peer_ != NULL) {
1661 visitor(peer_, arg);
1662 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001663 jni_env_->locals.VisitRoots(visitor, arg);
1664 jni_env_->monitors.VisitRoots(visitor, arg);
Ian Rogersd6b1f612011-09-27 13:38:14 -07001665 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1666 // delivery.
1667 Context* context = GetLongJumpContext();
1668 // Visit roots on this thread's stack
1669 ReferenceMapVisitor mapper(context, visitor, arg);
1670 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001671}
1672
Ian Rogersb033c752011-07-20 12:22:35 -07001673static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001674 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001675 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001676 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001677 "Blocked",
1678 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001679 "Initializing",
1680 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001681 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001682 "VmWait",
1683 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001684};
1685std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001686 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001687 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1688 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001689 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001690 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001691 }
1692 return os;
1693}
1694
Elliott Hughes330304d2011-08-12 14:28:05 -07001695std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1696 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001697 << ",pthread_t=" << thread.GetImpl()
1698 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001699 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001700 << ",state=" << thread.GetState()
1701 << ",peer=" << thread.GetPeer()
1702 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001703 return os;
1704}
1705
Elliott Hughes8daa0922011-09-11 13:46:25 -07001706} // namespace art