blob: 4e3e8d140513fd1c7f0f3452b747d9d76567ec0b [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
21#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070030#include "context.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070031#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070032#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "monitor.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070034#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070036#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070037#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070038#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070039#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070040
41namespace art {
42
43pthread_key_t Thread::pthread_key_self_;
44
Elliott Hughes8e4aac52011-09-26 17:03:36 -070045static Class* gThreadLock = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070046static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070047static Field* gThread_daemon = NULL;
48static Field* gThread_group = NULL;
49static Field* gThread_lock = NULL;
50static Field* gThread_name = NULL;
51static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070052static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070053static Field* gThread_vmData = NULL;
54static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070055static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070056static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070057static Method* gThreadGroup_removeThread = NULL;
58static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070059
buzbee4a3164f2011-09-03 11:25:10 -070060// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070061void DebugMe(Method* method, uint32_t info) {
Elliott Hughes01158d72011-09-19 19:47:10 -070062 LOG(INFO) << "DebugMe";
63 if (method != NULL) {
64 LOG(INFO) << PrettyMethod(method);
65 }
66 LOG(INFO) << "Info: " << info;
buzbee4a3164f2011-09-03 11:25:10 -070067}
68
Ian Rogersbdb03912011-09-14 00:55:44 -070069// Called by generated call to throw an exception
Ian Rogersff1ed472011-09-20 13:46:24 -070070extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070071 /*
72 * exception may be NULL, in which case this routine should
73 * throw NPE. NOTE: this is a convenience for generated code,
74 * which previously did the null check inline and constructed
75 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070076 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070077 */
Ian Rogers67375ac2011-09-14 00:55:44 -070078 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070079 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogersbdb03912011-09-14 00:55:44 -070080 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070081 if (exception == NULL) {
82 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
Ian Rogersff1ed472011-09-20 13:46:24 -070083 } else {
84 thread->SetException(exception);
Ian Rogers93dd9662011-09-17 23:21:22 -070085 }
Ian Rogersff1ed472011-09-20 13:46:24 -070086 thread->DeliverException();
87}
88
89// Deliver an exception that's pending on thread helping set up a callee save frame on the way
90extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
91 *sp = Runtime::Current()->GetCalleeSaveMethod();
92 thread->SetTopOfStack(sp, 0);
93 thread->DeliverException();
buzbee1b4c8592011-08-31 10:43:51 -070094}
95
Ian Rogers9651f422011-09-19 20:26:07 -070096// Called by generated call to throw a NPE exception
Ian Rogersff1ed472011-09-20 13:46:24 -070097extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -070098 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070099 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700100 thread->SetTopOfStack(sp, 0);
101 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
Ian Rogersff1ed472011-09-20 13:46:24 -0700102 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700103}
104
105// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700106extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700107 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700108 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700109 thread->SetTopOfStack(sp, 0);
110 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
Ian Rogersff1ed472011-09-20 13:46:24 -0700111 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700112}
113
114// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700115extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700116 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700117 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700118 thread->SetTopOfStack(sp, 0);
119 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
120 "length=%d; index=%d", limit, index);
Ian Rogersff1ed472011-09-20 13:46:24 -0700121 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700122}
123
Ian Rogersff1ed472011-09-20 13:46:24 -0700124// Called by the AbstractMethodError stub (not runtime support)
125void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
126 *sp = Runtime::Current()->GetCalleeSaveMethod();
127 thread->SetTopOfStack(sp, 0);
Ian Rogersa0841a82011-09-22 14:16:31 -0700128 thread->ThrowNewException("Ljava/lang/AbstractMethodError;",
Ian Rogersff1ed472011-09-20 13:46:24 -0700129 "abstract method \"%s\"",
130 PrettyMethod(method).c_str());
131 thread->DeliverException();
132}
133
Ian Rogers932746a2011-09-22 18:57:50 -0700134extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
135 // Place a special frame at the TOS that will save all callee saves
136 Runtime* runtime = Runtime::Current();
137 *sp = runtime->GetCalleeSaveMethod();
138 thread->SetTopOfStack(sp, 0);
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700139 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Ian Rogers932746a2011-09-22 18:57:50 -0700140 thread->ThrowNewException("Ljava/lang/StackOverflowError;",
141 "stack size %zdkb; default stack size: %zdkb",
142 thread->GetStackSize() / KB, runtime->GetDefaultStackSize() / KB);
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700143 thread->ResetDefaultStackEnd(); // Return to default stack size
Ian Rogers932746a2011-09-22 18:57:50 -0700144 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700145}
146
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700147extern "C" void artThrowVerificationErrorFromCode(int32_t src1, int32_t ref, Thread* thread, Method** sp) {
148 // Place a special frame at the TOS that will save all callee saves
149 Runtime* runtime = Runtime::Current();
150 *sp = runtime->GetCalleeSaveMethod();
151 thread->SetTopOfStack(sp, 0);
152 LOG(WARNING) << "TODO: verifcation error detail message. src1=" << src1 << " ref=" << ref;
153 thread->ThrowNewException("Ljava/lang/VerifyError;",
154 "TODO: verifcation error detail message. src1=%d; ref=%d", src1, ref);
155 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700156}
157
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700158extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
159 // Place a special frame at the TOS that will save all callee saves
160 Runtime* runtime = Runtime::Current();
161 *sp = runtime->GetCalleeSaveMethod();
162 thread->SetTopOfStack(sp, 0);
163 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
164 thread->ThrowNewException("Ljava/lang/InternalError;", "errnum=%d", errnum);
165 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700166}
167
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700168extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
169 // Place a special frame at the TOS that will save all callee saves
170 Runtime* runtime = Runtime::Current();
171 *sp = runtime->GetCalleeSaveMethod();
172 thread->SetTopOfStack(sp, 0);
173 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
174 thread->ThrowNewException("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
175 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700176}
177
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700178extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* thread, Method** sp) {
179 // Place a special frame at the TOS that will save all callee saves
180 Runtime* runtime = Runtime::Current();
181 *sp = runtime->GetCalleeSaveMethod();
182 thread->SetTopOfStack(sp, 0);
183 LOG(WARNING) << "TODO: no such method exception detail message. method_idx=" << method_idx;
184 thread->ThrowNewException("Ljava/lang/NoSuchMethodError;", "method_idx=%d", method_idx);
185 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700186}
187
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700188extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
189 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
190 // Place a special frame at the TOS that will save all callee saves
191 Runtime* runtime = Runtime::Current();
192 *sp = runtime->GetCalleeSaveMethod();
193 thread->SetTopOfStack(sp, 0);
194 thread->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d", size);
195 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700196}
Ian Rogersbdb03912011-09-14 00:55:44 -0700197
buzbee1b4c8592011-08-31 10:43:51 -0700198// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700199Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700200 /*
201 * Should initialize & fix up method->dex_cache_resolved_types_[].
202 * Returns initialized type. Does not return normally if an exception
203 * is thrown, but instead initiates the catch. Should be similar to
204 * ClassLinker::InitializeStaticStorageFromCode.
205 */
206 UNIMPLEMENTED(FATAL);
207 return NULL;
208}
209
buzbee561227c2011-09-02 15:28:19 -0700210// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700211void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700212 /*
213 * Slow-path handler on invoke virtual method path in which
214 * base method is unresolved at compile-time. Doesn't need to
215 * return anything - just either ensure that
216 * method->dex_cache_resolved_methods_(method_idx) != NULL or
217 * throw and unwind. The caller will restart call sequence
218 * from the beginning.
219 */
220}
221
Ian Rogers21d9e832011-09-23 17:05:09 -0700222// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
223// cannot be resolved, throw an error. If it can, use it to create an instance.
224extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method) {
225 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
226 if (klass == NULL) {
227 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
228 if (klass == NULL) {
229 DCHECK(Thread::Current()->IsExceptionPending());
230 return NULL; // Failure
231 }
232 }
233 return klass->AllocObject();
234}
235
Ian Rogersb886da82011-09-23 16:27:54 -0700236// Helper function to alloc array for OP_FILLED_NEW_ARRAY
237extern "C" Array* artCheckAndArrayAllocFromCode(uint32_t type_idx, Method* method,
238 int32_t component_count) {
239 if (component_count < 0) {
240 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
241 component_count);
242 return NULL; // Failure
243 }
244 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
245 if (klass == NULL) { // Not in dex cache so try to resolve
246 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
247 if (klass == NULL) { // Error
248 DCHECK(Thread::Current()->IsExceptionPending());
249 return NULL; // Failure
250 }
251 }
252 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
253 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
254 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
255 "Bad filled array request for type %s",
256 PrettyDescriptor(klass->GetDescriptor()).c_str());
257 } else {
258 Thread::Current()->ThrowNewException("Ljava/lang/InternalError;",
259 "Found type %s; filled-new-array not implemented for anything but \'int\'",
260 PrettyDescriptor(klass->GetDescriptor()).c_str());
261 }
262 return NULL; // Failure
263 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700264 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700265 return Array::Alloc(klass, component_count);
266 }
267}
268
269// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
270// it cannot be resolved, throw an error. If it can, use it to create an array.
271extern "C" Array* artArrayAllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
272 if (component_count < 0) {
273 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
274 component_count);
275 return NULL; // Failure
276 }
277 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
278 if (klass == NULL) { // Not in dex cache so try to resolve
279 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
280 if (klass == NULL) { // Error
281 DCHECK(Thread::Current()->IsExceptionPending());
282 return NULL; // Failure
283 }
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700284 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700285 }
286 return Array::Alloc(klass, component_count);
buzbee1da522d2011-09-04 11:22:20 -0700287}
288
Ian Rogerse51a5112011-09-23 14:16:35 -0700289// 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 -0700290extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700291 DCHECK(a->IsClass()) << PrettyClass(a);
292 DCHECK(b->IsClass()) << PrettyClass(b);
Brian Carlstromc2282522011-09-17 10:33:14 -0700293 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700294 return 0; // Success
295 } else {
296 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700297 "%s cannot be cast to %s",
298 PrettyDescriptor(a->GetDescriptor()).c_str(),
299 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700300 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700301 }
buzbee2a475e72011-09-07 17:19:17 -0700302}
303
Ian Rogerse51a5112011-09-23 14:16:35 -0700304// Tests whether 'element' can be assigned into an array of type 'array_class'.
305// Returns 0 on success and -1 if an exception is pending.
306extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
307 DCHECK(array_class != NULL);
308 // element can't be NULL as we catch this is screened in runtime_support
309 Class* element_class = element->GetClass();
310 Class* component_type = array_class->GetComponentType();
311 if (component_type->IsAssignableFrom(element_class)) {
312 return 0; // Success
313 } else {
314 Thread::Current()->ThrowNewException("Ljava/lang/ArrayStoreException;",
Ian Rogersb886da82011-09-23 16:27:54 -0700315 "Cannot store an object of type %s in to an array of type %s",
316 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
317 PrettyDescriptor(array_class->GetDescriptor()).c_str());
Ian Rogerse51a5112011-09-23 14:16:35 -0700318 return -1; // Failure
319 }
320}
321
Ian Rogersff1ed472011-09-20 13:46:24 -0700322extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
323 DCHECK(obj != NULL); // Assumed to have been checked before entry
324 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700325}
326
Elliott Hughesd369bb72011-09-12 14:41:14 -0700327void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700328 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700329 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700330 DCHECK(thread->HoldsLock(obj));
331 // Only possible exception is NPE and is handled before entry
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700332 DCHECK(!thread->IsExceptionPending());
buzbee2a475e72011-09-07 17:19:17 -0700333}
334
buzbeec1f45042011-09-21 16:03:19 -0700335extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700336 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700337}
338
buzbee5ade1d22011-09-09 14:44:52 -0700339/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700340 * Fill the array with predefined constant values, throwing exceptions if the array is null or
341 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700342 *
343 * NOTE: When dealing with a raw dex file, the data to be copied uses
344 * little-endian ordering. Require that oat2dex do any required swapping
345 * so this routine can get by with a memcpy().
346 *
347 * Format of the data:
348 * ushort ident = 0x0300 magic value
349 * ushort width width of each element in the table
350 * uint size number of elements in the table
351 * ubyte data[size*width] table of data values (may contain a single-byte
352 * padding at the end)
353 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700354extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
355 DCHECK_EQ(table[0], 0x0300);
356 if (array == NULL) {
357 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
358 "null array in fill array");
359 return -1; // Error
360 }
361 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
362 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
363 if (static_cast<int32_t>(size) > array->GetLength()) {
364 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
365 "failed array fill. length=%d; index=%d",
366 array->GetLength(), size);
367 return -1; // Error
368 }
369 uint16_t width = table[1];
370 uint32_t size_in_bytes = size * width;
371 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
372 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700373}
374
375// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700376extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
377 Object* this_object ,
378 Method* caller_method) {
379 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700380 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700381 thread->ThrowNewException("Ljava/lang/NullPointerException;",
382 "null receiver during interface dispatch");
383 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700384 }
385 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
386 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
387 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700388 // Could not resolve interface method. Throw error and unwind
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700389 CHECK(thread->IsExceptionPending());
Ian Rogersff1ed472011-09-20 13:46:24 -0700390 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700391 }
392 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700393 if (method == NULL) {
394 CHECK(thread->IsExceptionPending());
395 return 0;
396 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700397 const void* code = method->GetCode();
398
399 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
400 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
401 uint64_t result = ((code_uint << 32) | method_uint);
402 return result;
403}
404
buzbee5ade1d22011-09-09 14:44:52 -0700405// TODO: move to more appropriate location
406/*
407 * Float/double conversion requires clamping to min and max of integer form. If
408 * target doesn't support this normally, use these.
409 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700410int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700411 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
412 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
413 if (d >= kMaxLong)
414 return (int64_t)0x7fffffffffffffffULL;
415 else if (d <= kMinLong)
416 return (int64_t)0x8000000000000000ULL;
417 else if (d != d) // NaN case
418 return 0;
419 else
420 return (int64_t)d;
421}
422
Elliott Hughesd369bb72011-09-12 14:41:14 -0700423int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700424 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
425 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
426 if (f >= kMaxLong)
427 return (int64_t)0x7fffffffffffffffULL;
428 else if (f <= kMinLong)
429 return (int64_t)0x8000000000000000ULL;
430 else if (f != f) // NaN case
431 return 0;
432 else
433 return (int64_t)f;
434}
435
Brian Carlstrom16192862011-09-12 17:50:06 -0700436// Return value helper for jobject return types
437static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
438 return thread->DecodeJObject(obj);
439}
440
buzbee3ea4ec52011-08-22 17:37:19 -0700441void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700442#if defined(__arm__)
443 pShlLong = art_shl_long;
444 pShrLong = art_shr_long;
445 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700446 pIdiv = __aeabi_idiv;
447 pIdivmod = __aeabi_idivmod;
448 pI2f = __aeabi_i2f;
449 pF2iz = __aeabi_f2iz;
450 pD2f = __aeabi_d2f;
451 pF2d = __aeabi_f2d;
452 pD2iz = __aeabi_d2iz;
453 pL2f = __aeabi_l2f;
454 pL2d = __aeabi_l2d;
455 pFadd = __aeabi_fadd;
456 pFsub = __aeabi_fsub;
457 pFdiv = __aeabi_fdiv;
458 pFmul = __aeabi_fmul;
459 pFmodf = fmodf;
460 pDadd = __aeabi_dadd;
461 pDsub = __aeabi_dsub;
462 pDdiv = __aeabi_ddiv;
463 pDmul = __aeabi_dmul;
464 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700465 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700466 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700467 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700468 pArrayAllocFromCode = art_array_alloc_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700469 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700470 pCheckAndArrayAllocFromCode = art_check_and_array_alloc_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700471 pCheckCastFromCode = art_check_cast_from_code;
472 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700473 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700474 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700475 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700476 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
477 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700478 pThrowInternalErrorFromCode = art_throw_internal_error_from_code;
479 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
480 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700481 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700482 pThrowRuntimeExceptionFromCode = art_throw_runtime_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700483 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700484 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700485 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700486#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700487 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700488 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700489 pF2l = F2L;
490 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700491 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700492 pGet32Static = Field::Get32StaticFromCode;
493 pSet32Static = Field::Set32StaticFromCode;
494 pGet64Static = Field::Get64StaticFromCode;
495 pSet64Static = Field::Set64StaticFromCode;
496 pGetObjStatic = Field::GetObjStaticFromCode;
497 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700498 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700499 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700500 pInstanceofNonTrivialFromCode = Object::InstanceOf;
buzbee2a475e72011-09-07 17:19:17 -0700501 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700502 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700503 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700504 pFindNativeMethod = FindNativeMethod;
505 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700506 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700507}
508
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700509void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700510 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
511 DCHECK_NE(frame_size, 0u);
512 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700513 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514 sp_ = reinterpret_cast<Method**>(next_sp);
Elliott Hughes80609252011-09-23 17:24:51 -0700515 if (*sp_ != NULL) {
516 DCHECK((*sp_)->GetClass() == Method::GetMethodClass() ||
517 (*sp_)->GetClass() == Method::GetConstructorClass());
Ian Rogersff1ed472011-09-20 13:46:24 -0700518 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700519}
520
Ian Rogers90865722011-09-19 11:11:44 -0700521bool Frame::HasMethod() const {
522 return GetMethod() != NULL && (!GetMethod()->IsPhony());
523}
524
Ian Rogersbdb03912011-09-14 00:55:44 -0700525uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700526 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700527 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700528}
529
Ian Rogersbdb03912011-09-14 00:55:44 -0700530uintptr_t Frame::LoadCalleeSave(int num) const {
531 // Callee saves are held at the top of the frame
532 Method* method = GetMethod();
533 DCHECK(method != NULL);
534 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700535 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700536#if defined(__i386__)
537 save_addr -= kPointerSize; // account for return address
538#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700539 return *reinterpret_cast<uintptr_t*>(save_addr);
540}
541
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700543 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700544 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700546}
547
Brian Carlstrom78128a62011-09-15 17:21:19 -0700548void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700549 Thread* self = reinterpret_cast<Thread*>(arg);
550 Runtime* runtime = Runtime::Current();
551
552 self->Attach(runtime);
553
Elliott Hughes038a8062011-09-18 14:12:41 -0700554 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700555 if (thread_name != NULL) {
556 SetThreadName(thread_name->ToModifiedUtf8().c_str());
557 }
558
559 // Wait until it's safe to start running code. (There may have been a suspend-all
560 // in progress while we were starting up.)
561 runtime->GetThreadList()->WaitForGo();
562
563 // TODO: say "hi" to the debugger.
564 //if (gDvm.debuggerConnected) {
565 // dvmDbgPostThreadStart(self);
566 //}
567
568 // Invoke the 'run' method of our java.lang.Thread.
569 CHECK(self->peer_ != NULL);
570 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700571 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700572 m->Invoke(self, receiver, NULL, NULL);
573
574 // Detach.
575 runtime->GetThreadList()->Unregister();
576
Carl Shapirob5573532011-07-12 18:22:59 -0700577 return NULL;
578}
579
Elliott Hughes93e74e82011-09-13 11:07:03 -0700580void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700581 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700582}
583
Elliott Hughes01158d72011-09-19 19:47:10 -0700584Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
585 Object* thread = Decode<Object*>(env, java_thread);
586 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
587}
588
Elliott Hughesd369bb72011-09-12 14:41:14 -0700589void Thread::Create(Object* peer, size_t stack_size) {
590 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700591
Elliott Hughesd369bb72011-09-12 14:41:14 -0700592 if (stack_size == 0) {
593 stack_size = Runtime::Current()->GetDefaultStackSize();
594 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700595
Elliott Hughes93e74e82011-09-13 11:07:03 -0700596 Thread* native_thread = new Thread;
597 native_thread->peer_ = peer;
598
599 // Thread.start is synchronized, so we know that vmData is 0,
600 // and know that we're not racing to assign it.
601 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700602
603 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700604 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
605 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
606 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
607 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
608 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700609
610 // Let the child know when it's safe to start running.
611 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700612}
613
Elliott Hughes93e74e82011-09-13 11:07:03 -0700614void Thread::Attach(const Runtime* runtime) {
615 InitCpu();
616 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700617
Elliott Hughes93e74e82011-09-13 11:07:03 -0700618 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700619
Elliott Hughes93e74e82011-09-13 11:07:03 -0700620 tid_ = ::art::GetTid();
621 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700622
Elliott Hughes93e74e82011-09-13 11:07:03 -0700623 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700624
Elliott Hughes8d768a92011-09-14 16:35:25 -0700625 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700626
Elliott Hughes93e74e82011-09-13 11:07:03 -0700627 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700628
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700629 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700630}
631
632Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
633 Thread* self = new Thread;
634 self->Attach(runtime);
635
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700636 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700637
638 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700639
640 // If we're the main thread, ClassLinker won't be created until after we're attached,
641 // so that thread needs a two-stage attach. Regular threads don't need this hack.
642 if (self->thin_lock_id_ != ThreadList::kMainId) {
643 self->CreatePeer(name, as_daemon);
644 }
645
646 return self;
647}
648
Elliott Hughesd369bb72011-09-12 14:41:14 -0700649jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
650 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
651 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
652 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
653 // This will be null in the compiler (and tests), but never in a running system.
654 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
655 return thread_group;
656}
657
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700658void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700659 JNIEnv* env = jni_env_;
660
Elliott Hughesd369bb72011-09-12 14:41:14 -0700661 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
662 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700663 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700664 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700665 jboolean thread_is_daemon = as_daemon;
666
667 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700668 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700669
Elliott Hughes8daa0922011-09-11 13:46:25 -0700670 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700671 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700672 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700673
674 // Because we mostly run without code available (in the compiler, in tests), we
675 // manually assign the fields the constructor should have set.
676 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700677 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
678 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
679 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
680 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700681}
682
Elliott Hughesbe759c62011-09-08 19:38:21 -0700683void Thread::InitStackHwm() {
684 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700685 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700686
Ian Rogers932746a2011-09-22 18:57:50 -0700687 void* temp_stack_base;
688 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
689 __FUNCTION__);
690 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700691
Ian Rogers932746a2011-09-22 18:57:50 -0700692 if (stack_size_ <= kStackOverflowReservedBytes) {
693 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700694 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700695
Ian Rogers932746a2011-09-22 18:57:50 -0700696 // Set stack_end_ to the bottom of the stack saving space of stack overflows
697 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700698
699 // Sanity check.
700 int stack_variable;
701 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700702
Elliott Hughes8d768a92011-09-14 16:35:25 -0700703 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700704}
705
Elliott Hughesa0957642011-09-02 14:27:33 -0700706void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700707 DumpState(os);
708 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700709}
710
Elliott Hughesd92bec42011-09-02 17:04:36 -0700711std::string GetSchedulerGroup(pid_t tid) {
712 // /proc/<pid>/group looks like this:
713 // 2:devices:/
714 // 1:cpuacct,cpu:/
715 // We want the third field from the line whose second field contains the "cpu" token.
716 std::string cgroup_file;
717 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
718 return "";
719 }
720 std::vector<std::string> cgroup_lines;
721 Split(cgroup_file, '\n', cgroup_lines);
722 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
723 std::vector<std::string> cgroup_fields;
724 Split(cgroup_lines[i], ':', cgroup_fields);
725 std::vector<std::string> cgroups;
726 Split(cgroup_fields[1], ',', cgroups);
727 for (size_t i = 0; i < cgroups.size(); ++i) {
728 if (cgroups[i] == "cpu") {
729 return cgroup_fields[2].substr(1); // Skip the leading slash.
730 }
731 }
732 }
733 return "";
734}
735
736void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700737 std::string thread_name("<native thread without managed peer>");
738 std::string group_name;
739 int priority;
740 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700741
Elliott Hughesd369bb72011-09-12 14:41:14 -0700742 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700743 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700744 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700745 priority = gThread_priority->GetInt(peer_);
746 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700747
Elliott Hughes038a8062011-09-18 14:12:41 -0700748 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700749 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700750 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700751 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
752 }
753 } else {
754 // 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 -0700755 std::string stats;
756 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
757 size_t start = stats.find('(') + 1;
758 size_t end = stats.find(')') - start;
759 thread_name = stats.substr(start, end);
760 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700761 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700762 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700763
764 int policy;
765 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700766 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700767
768 std::string scheduler_group(GetSchedulerGroup(GetTid()));
769 if (scheduler_group.empty()) {
770 scheduler_group = "default";
771 }
772
Elliott Hughesd92bec42011-09-02 17:04:36 -0700773 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700774 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700775 os << " daemon";
776 }
777 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700778 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700779 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700780
Elliott Hughesd92bec42011-09-02 17:04:36 -0700781 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700782 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700783 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700784 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700785 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700786 << " self=" << reinterpret_cast<const void*>(this) << "\n";
787 os << " | sysTid=" << GetTid()
788 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
789 << " sched=" << policy << "/" << sp.sched_priority
790 << " cgrp=" << scheduler_group
791 << " handle=" << GetImpl() << "\n";
792
793 // Grab the scheduler stats for this thread.
794 std::string scheduler_stats;
795 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
796 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
797 } else {
798 scheduler_stats = "0 0 0";
799 }
800
801 int utime = 0;
802 int stime = 0;
803 int task_cpu = 0;
804 std::string stats;
805 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
806 // Skip the command, which may contain spaces.
807 stats = stats.substr(stats.find(')') + 2);
808 // Extract the three fields we care about.
809 std::vector<std::string> fields;
810 Split(stats, ' ', fields);
811 utime = strtoull(fields[11].c_str(), NULL, 10);
812 stime = strtoull(fields[12].c_str(), NULL, 10);
813 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
814 }
815
816 os << " | schedstat=( " << scheduler_stats << " )"
817 << " utm=" << utime
818 << " stm=" << stime
819 << " core=" << task_cpu
820 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
821}
822
Elliott Hughesd369bb72011-09-12 14:41:14 -0700823struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700824 StackDumpVisitor(std::ostream& os, const Thread* thread)
825 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700826 }
827
Ian Rogersbdb03912011-09-14 00:55:44 -0700828 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700829 }
830
Ian Rogersbdb03912011-09-14 00:55:44 -0700831 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700832 if (!frame.HasMethod()) {
833 return;
834 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700835
836 Method* m = frame.GetMethod();
837 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700838 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700839 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
840
841 os << " at " << PrettyMethod(m, false);
842 if (m->IsNative()) {
843 os << "(Native method)";
844 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700845 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700846 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
847 }
848 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700849
850 if (frame_count++ == 0) {
851 Monitor::DescribeWait(os, thread);
852 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700853 }
854
855 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700856 const Thread* thread;
857 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700858};
859
Elliott Hughesd92bec42011-09-02 17:04:36 -0700860void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700861 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700862 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700863}
864
Elliott Hughes8d768a92011-09-14 16:35:25 -0700865Thread::State Thread::SetState(Thread::State new_state) {
866 Thread::State old_state = state_;
867 if (old_state == new_state) {
868 return old_state;
869 }
870
871 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
872 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
873
874 if (new_state == Thread::kRunnable) {
875 /*
876 * Change our status to Thread::kRunnable. The transition requires
877 * that we check for pending suspension, because the VM considers
878 * us to be "asleep" in all other states, and another thread could
879 * be performing a GC now.
880 *
881 * The order of operations is very significant here. One way to
882 * do this wrong is:
883 *
884 * GCing thread Our thread (in kNative)
885 * ------------ ----------------------
886 * check suspend count (== 0)
887 * SuspendAllThreads()
888 * grab suspend-count lock
889 * increment all suspend counts
890 * release suspend-count lock
891 * check thread state (== kNative)
892 * all are suspended, begin GC
893 * set state to kRunnable
894 * (continue executing)
895 *
896 * We can correct this by grabbing the suspend-count lock and
897 * performing both of our operations (check suspend count, set
898 * state) while holding it, now we need to grab a mutex on every
899 * transition to kRunnable.
900 *
901 * What we do instead is change the order of operations so that
902 * the transition to kRunnable happens first. If we then detect
903 * that the suspend count is nonzero, we switch to kSuspended.
904 *
905 * Appropriate compiler and memory barriers are required to ensure
906 * that the operations are observed in the expected order.
907 *
908 * This does create a small window of opportunity where a GC in
909 * progress could observe what appears to be a running thread (if
910 * it happens to look between when we set to kRunnable and when we
911 * switch to kSuspended). At worst this only affects assertions
912 * and thread logging. (We could work around it with some sort
913 * of intermediate "pre-running" state that is generally treated
914 * as equivalent to running, but that doesn't seem worthwhile.)
915 *
916 * We can also solve this by combining the "status" and "suspend
917 * count" fields into a single 32-bit value. This trades the
918 * store/load barrier on transition to kRunnable for an atomic RMW
919 * op on all transitions and all suspend count updates (also, all
920 * accesses to status or the thread count require bit-fiddling).
921 * It also eliminates the brief transition through kRunnable when
922 * the thread is supposed to be suspended. This is possibly faster
923 * on SMP and slightly more correct, but less convenient.
924 */
925 android_atomic_acquire_store(new_state, addr);
926 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
927 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
928 }
929 } else {
930 /*
931 * Not changing to Thread::kRunnable. No additional work required.
932 *
933 * We use a releasing store to ensure that, if we were runnable,
934 * any updates we previously made to objects on the managed heap
935 * will be observed before the state change.
936 */
937 android_atomic_release_store(new_state, addr);
938 }
939
940 return old_state;
941}
942
943void Thread::WaitUntilSuspended() {
944 // TODO: dalvik dropped the waiting thread's priority after a while.
945 // TODO: dalvik timed out and aborted.
946 useconds_t delay = 0;
947 while (GetState() == Thread::kRunnable) {
948 useconds_t new_delay = delay * 2;
949 CHECK_GE(new_delay, delay);
950 delay = new_delay;
951 if (delay == 0) {
952 sched_yield();
953 delay = 10000;
954 } else {
955 usleep(delay);
956 }
957 }
958}
959
Elliott Hughesbe759c62011-09-08 19:38:21 -0700960void Thread::ThreadExitCallback(void* arg) {
961 Thread* self = reinterpret_cast<Thread*>(arg);
962 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700963}
964
Elliott Hughesbe759c62011-09-08 19:38:21 -0700965void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700966 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700967 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700968
969 // Double-check the TLS slot allocation.
970 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700971 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700972 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700973}
Carl Shapirob5573532011-07-12 18:22:59 -0700974
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700975// TODO: make more accessible?
976Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
977 Class* c = class_linker->FindPrimitiveClass(descriptor);
978 CHECK(c != NULL) << descriptor;
979 return c;
980}
981
982// TODO: make more accessible?
983Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
984 Class* c = class_linker->FindSystemClass(descriptor);
985 CHECK(c != NULL) << descriptor;
986 return c;
987}
988
989// TODO: make more accessible?
990Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
991 Field* f = c->FindDeclaredInstanceField(name, type);
992 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
993 return f;
994}
995
996// TODO: make more accessible?
997Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
998 Method* m = c->FindVirtualMethod(name, signature);
999 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
1000 return m;
1001}
1002
Elliott Hughes038a8062011-09-18 14:12:41 -07001003void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -07001004 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
1005 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001006
1007 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
1008 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
1009 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
1010 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
1011 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
1012 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
1013 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
1014 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
1015
1016 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
1017 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
1018 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
1019 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
1020 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
1021 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
1022 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
1023 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
1024 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
1025
1026 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
1027 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
1028 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
1029 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -07001030
1031 // Finish attaching the main thread.
1032 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -07001033}
1034
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001035void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -07001036 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001037}
1038
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001039uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
1040 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
1041 return ThreadList::kInvalidId;
1042 }
1043 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
1044 if (managed_thread == NULL) {
1045 return ThreadList::kInvalidId;
1046 }
1047 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
1048 Thread* thread = reinterpret_cast<Thread*>(vmData);
1049 if (thread == NULL) {
1050 return ThreadList::kInvalidId;
1051 }
1052 return thread->GetThinLockId();
1053}
1054
Elliott Hughesdcc24742011-09-07 14:02:44 -07001055Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -07001056 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001057 top_of_managed_stack_(),
1058 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001059 wait_mutex_(new Mutex("Thread wait mutex")),
1060 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001061 wait_monitor_(NULL),
1062 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001063 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001064 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001065 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001066 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001067 native_to_managed_record_(NULL),
1068 top_sirt_(NULL),
1069 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001070 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001071 self_(NULL),
1072 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001073 exception_(NULL),
1074 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001075 class_loader_override_(NULL),
1076 long_jump_context_(NULL) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001077 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001078}
1079
Elliott Hughes02b48d12011-09-07 17:15:51 -07001080void MonitorExitVisitor(const Object* object, void*) {
1081 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -07001082 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001083}
1084
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001085Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -07001086 SetState(Thread::kRunnable);
1087
Elliott Hughes02b48d12011-09-07 17:15:51 -07001088 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -07001089 if (jni_env_ != NULL) {
1090 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
1091 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001092
Elliott Hughes93e74e82011-09-13 11:07:03 -07001093 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001094 Object* group = gThread_group->GetObject(peer_);
1095
1096 // Handle any pending exception.
1097 if (IsExceptionPending()) {
1098 // Get and clear the exception.
1099 Object* exception = GetException();
1100 ClearException();
1101
1102 // If the thread has its own handler, use that.
1103 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1104 if (handler == NULL) {
1105 // Otherwise use the thread group's default handler.
1106 handler = group;
1107 }
1108
1109 // Call the handler.
1110 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
1111 Object* args[2];
1112 args[0] = peer_;
1113 args[1] = exception;
1114 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
1115
1116 // If the handler threw, clear that exception too.
1117 ClearException();
1118 }
1119
1120 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -07001121 // group can be null if we're in the compiler or a test.
1122 if (group != NULL) {
1123 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
1124 Object* args = peer_;
1125 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
1126 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001127
1128 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -07001129 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001130
Elliott Hughes29f27422011-09-18 16:02:18 -07001131 // TODO: say "bye" to the debugger.
1132 //if (gDvm.debuggerConnected) {
1133 // dvmDbgPostThreadDeath(self);
1134 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001135
Elliott Hughes29f27422011-09-18 16:02:18 -07001136 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1137 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -07001138 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -07001139 Object* lock = gThread_lock->GetObject(peer_);
1140 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -07001141 if (lock != NULL) {
1142 lock->MonitorEnter(self);
1143 lock->NotifyAll();
1144 lock->MonitorExit(self);
1145 }
1146 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001147
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001148 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001149 jni_env_ = NULL;
1150
1151 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001152
1153 delete wait_cond_;
1154 delete wait_mutex_;
1155
1156 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001157}
1158
Ian Rogers408f79a2011-08-23 18:22:33 -07001159size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001160 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001161 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001162 count += cur->NumberOfReferences();
1163 }
1164 return count;
1165}
1166
Ian Rogers408f79a2011-08-23 18:22:33 -07001167bool Thread::SirtContains(jobject obj) {
1168 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1169 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001170 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001171 // A SIRT should always have a jobject/jclass as a native method is passed
1172 // in a this pointer or a class
1173 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001174 if ((&cur->References()[0] <= sirt_entry) &&
1175 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001176 return true;
1177 }
1178 }
1179 return false;
1180}
1181
Ian Rogers67375ac2011-09-14 00:55:44 -07001182void Thread::PopSirt() {
1183 CHECK(top_sirt_ != NULL);
1184 top_sirt_ = top_sirt_->Link();
1185}
1186
Ian Rogers408f79a2011-08-23 18:22:33 -07001187Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001188 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001189 if (obj == NULL) {
1190 return NULL;
1191 }
1192 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1193 IndirectRefKind kind = GetIndirectRefKind(ref);
1194 Object* result;
1195 switch (kind) {
1196 case kLocal:
1197 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001198 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001199 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001200 break;
1201 }
1202 case kGlobal:
1203 {
1204 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1205 IndirectReferenceTable& globals = vm->globals;
1206 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001207 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001208 break;
1209 }
1210 case kWeakGlobal:
1211 {
1212 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1213 IndirectReferenceTable& weak_globals = vm->weak_globals;
1214 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001215 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001216 if (result == kClearedJniWeakGlobal) {
1217 // This is a special case where it's okay to return NULL.
1218 return NULL;
1219 }
1220 break;
1221 }
1222 case kSirtOrInvalid:
1223 default:
1224 // TODO: make stack indirect reference table lookup more efficient
1225 // Check if this is a local reference in the SIRT
1226 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001227 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001228 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001229 // Assume an invalid local reference is actually a direct pointer.
1230 result = reinterpret_cast<Object*>(obj);
1231 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001232 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001233 }
1234 }
1235
1236 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001237 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1238 JniAbort(NULL);
1239 } else {
1240 if (result != kInvalidIndirectRefObject) {
1241 Heap::VerifyObject(result);
1242 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001243 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001244 return result;
1245}
1246
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001247class CountStackDepthVisitor : public Thread::StackVisitor {
1248 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001249 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001250
Elliott Hughes29f27422011-09-18 16:02:18 -07001251 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1252 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001253 // Note we also skip the frame if it doesn't have a method (namely the callee
1254 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001255 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001256 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001257 skipping_ = false;
1258 }
1259 if (!skipping_) {
1260 ++depth_;
1261 } else {
1262 ++skip_depth_;
1263 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001264 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001265
1266 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001267 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001268 }
1269
Elliott Hughes29f27422011-09-18 16:02:18 -07001270 int GetSkipDepth() const {
1271 return skip_depth_;
1272 }
1273
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001274 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001275 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001276 uint32_t skip_depth_;
1277 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001278};
1279
Ian Rogersaaa20802011-09-11 21:47:37 -07001280class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001281 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001282 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1283 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001284 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001285 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001286 // Register a local reference as IntArray::Alloc may trigger GC
1287 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1288 pc_trace_ = IntArray::Alloc(depth);
1289#ifdef MOVING_GARBAGE_COLLECTOR
1290 // Re-read after potential GC
1291 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1292#endif
1293 // Save PC trace in last element of method trace, also places it into the
1294 // object graph.
1295 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001296 }
1297
Ian Rogersaaa20802011-09-11 21:47:37 -07001298 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001299
Ian Rogersbdb03912011-09-14 00:55:44 -07001300 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001301 if (skip_depth_ > 0) {
1302 skip_depth_--;
1303 return;
1304 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001305 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001306 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001307 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001308 }
1309
Ian Rogersaaa20802011-09-11 21:47:37 -07001310 jobject GetInternalStackTrace() const {
1311 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001312 }
1313
1314 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001315 // How many more frames to skip.
1316 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001317 // Current position down stack trace
1318 uint32_t count_;
1319 // Array of return PC values
1320 IntArray* pc_trace_;
1321 // An array of the methods on the stack, the last entry is a reference to the
1322 // PC trace
1323 ObjectArray<Object>* method_trace_;
1324 // Local indirect reference table entry for method trace
1325 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001326};
1327
Ian Rogersaaa20802011-09-11 21:47:37 -07001328void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001329 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001330 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001331 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1332 // CHECK(native_to_managed_record_ != NULL);
1333 NativeToManagedRecord* record = native_to_managed_record_;
1334
Ian Rogersbdb03912011-09-14 00:55:44 -07001335 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001336 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001337 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1338 visitor->VisitFrame(frame, pc);
1339 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001340 }
1341 if (record == NULL) {
1342 break;
1343 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001344 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001345 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001346 pc = record->last_top_of_managed_stack_pc_;
1347 record = record->link_;
1348 }
1349}
1350
Ian Rogers67375ac2011-09-14 00:55:44 -07001351void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001352 Frame frame = GetTopOfStack();
1353 uintptr_t pc = top_of_managed_stack_pc_;
1354
1355 if (frame.GetSP() != 0) {
1356 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001357 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001358 visitor->VisitFrame(frame, pc);
1359 pc = frame.GetReturnPC();
1360 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001361 if (include_upcall) {
1362 visitor->VisitFrame(frame, pc);
1363 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001364 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001365}
1366
Elliott Hughes01158d72011-09-19 19:47:10 -07001367jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001368 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001369 CountStackDepthVisitor count_visitor;
1370 WalkStack(&count_visitor);
1371 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001372 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001373
Ian Rogersaaa20802011-09-11 21:47:37 -07001374 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001375 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001376
1377 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001378 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001379 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001380
Ian Rogersaaa20802011-09-11 21:47:37 -07001381 return build_trace_visitor.GetInternalStackTrace();
1382}
1383
Elliott Hughes01158d72011-09-19 19:47:10 -07001384jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1385 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001386 // Transition into runnable state to work on Object*/Array*
1387 ScopedJniThreadState ts(env);
1388
1389 // Decode the internal stack trace into the depth, method trace and PC trace
1390 ObjectArray<Object>* method_trace =
1391 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1392 int32_t depth = method_trace->GetLength()-1;
1393 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1394
1395 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1396
Elliott Hughes01158d72011-09-19 19:47:10 -07001397 jobjectArray result;
1398 ObjectArray<StackTraceElement>* java_traces;
1399 if (output_array != NULL) {
1400 // Reuse the array we were given.
1401 result = output_array;
1402 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1403 output_array));
1404 // ...adjusting the number of frames we'll write to not exceed the array length.
1405 depth = std::min(depth, java_traces->GetLength());
1406 } else {
1407 // Create java_trace array and place in local reference table
1408 java_traces = class_linker->AllocStackTraceElementArray(depth);
1409 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1410 }
1411
1412 if (stack_depth != NULL) {
1413 *stack_depth = depth;
1414 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001415
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001416 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001417 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1418 Method* method = down_cast<Method*>(method_trace->Get(i));
1419 uint32_t native_pc = pc_trace->Get(i);
1420 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001421 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001422 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001423
Ian Rogersaaa20802011-09-11 21:47:37 -07001424 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001425 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001426 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001427 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001428 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001429 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001430 method->ToDexPC(native_pc)));
1431#ifdef MOVING_GARBAGE_COLLECTOR
1432 // Re-read after potential GC
1433 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1434 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1435 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1436#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001437 java_traces->Set(i, obj);
1438 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001439 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001440}
1441
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001442void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001443 va_list args;
1444 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001445 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001446 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001447}
1448
1449void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1450 std::string msg;
1451 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001452
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001453 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001454 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001455 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001456 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001457 descriptor.erase(descriptor.length() - 1);
1458
1459 JNIEnv* env = GetJniEnv();
1460 jclass exception_class = env->FindClass(descriptor.c_str());
1461 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1462 int rc = env->ThrowNew(exception_class, msg.c_str());
1463 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001464 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001465}
1466
Elliott Hughes79082e32011-08-25 12:07:32 -07001467void Thread::ThrowOutOfMemoryError() {
1468 UNIMPLEMENTED(FATAL);
1469}
1470
Ian Rogersbdb03912011-09-14 00:55:44 -07001471class CatchBlockStackVisitor : public Thread::StackVisitor {
1472 public:
1473 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001474 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1475#ifndef NDEBUG
1476 handler_pc_ = 0xEBADC0DE;
1477 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1478#endif
1479 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001480
Ian Rogersbdb03912011-09-14 00:55:44 -07001481 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1482 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001483 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001484 if (method == NULL) {
1485 // This is the upcall, we remember the frame and last_pc so that we may
1486 // long jump to them
1487 handler_pc_ = pc;
1488 handler_frame_ = fr;
1489 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001490 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001491 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001492 if (method->IsPhony()) {
1493 // ignore callee save method
1494 } else if (method->IsNative()) {
1495 native_method_count_++;
1496 } else {
1497 // Move the PC back 2 bytes as a call will frequently terminate the
1498 // decoding of a particular instruction and we want to make sure we
1499 // get the Dex PC of the instruction with the call and not the
1500 // instruction following.
1501 pc -= 2;
1502 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001503 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001504 if (dex_pc != DexFile::kDexNoIndex) {
1505 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1506 if (found_dex_pc != DexFile::kDexNoIndex) {
1507 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001508 handler_pc_ = method->ToNativePC(found_dex_pc);
1509 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001510 }
1511 }
1512 if (!found_) {
1513 // Caller may be handler, fill in callee saves in context
1514 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001515 }
1516 }
1517 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001518
1519 // Did we find a catch block yet?
1520 bool found_;
1521 // The type of the exception catch block to find
1522 Class* to_find_;
1523 // Frame with found handler or last frame if no handler found
1524 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001525 // PC to branch to for the handler
1526 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001527 // Context that will be the target of the long jump
1528 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001529 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1530 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001531};
1532
Ian Rogersff1ed472011-09-20 13:46:24 -07001533void Thread::DeliverException() {
1534 Throwable *exception = GetException(); // Set exception on thread
1535 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001536
1537 Context* long_jump_context = GetLongJumpContext();
1538 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001539 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001540
Ian Rogers67375ac2011-09-14 00:55:44 -07001541 // Pop any SIRT
1542 if (catch_finder.native_method_count_ == 1) {
1543 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001544 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001545 // We only expect the stack crawl to have passed 1 native method as it's terminated
1546 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001547 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001548 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001549 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1550 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001551 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001552}
1553
Ian Rogersbdb03912011-09-14 00:55:44 -07001554Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001555 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001556 if (result == NULL) {
1557 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001558 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001559 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001560 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001561}
1562
Elliott Hughes5f791332011-09-15 17:45:30 -07001563bool Thread::HoldsLock(Object* object) {
1564 if (object == NULL) {
1565 return false;
1566 }
1567 return object->GetLockOwner() == thin_lock_id_;
1568}
1569
Elliott Hughes038a8062011-09-18 14:12:41 -07001570bool Thread::IsDaemon() {
1571 return gThread_daemon->GetBoolean(peer_);
1572}
1573
Elliott Hughes410c0c82011-09-01 17:58:25 -07001574void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001575 if (exception_ != NULL) {
1576 visitor(exception_, arg);
1577 }
1578 if (peer_ != NULL) {
1579 visitor(peer_, arg);
1580 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001581 jni_env_->locals.VisitRoots(visitor, arg);
1582 jni_env_->monitors.VisitRoots(visitor, arg);
1583 // visitThreadStack(visitor, thread, arg);
1584 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1585}
1586
Ian Rogersb033c752011-07-20 12:22:35 -07001587static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001588 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001589 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001590 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001591 "Blocked",
1592 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001593 "Initializing",
1594 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001595 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001596 "VmWait",
1597 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001598};
1599std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001600 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001601 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1602 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001603 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001604 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001605 }
1606 return os;
1607}
1608
Elliott Hughes330304d2011-08-12 14:28:05 -07001609std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1610 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001611 << ",pthread_t=" << thread.GetImpl()
1612 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001613 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001614 << ",state=" << thread.GetState()
1615 << ",peer=" << thread.GetPeer()
1616 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001617 return os;
1618}
1619
Elliott Hughes8daa0922011-09-11 13:46:25 -07001620} // namespace art