blob: d79e1c567be1f35e282f73a4bec9a0f6c5b457b2 [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 }
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700233 if (!klass->IsInitialized()
234 && !Runtime::Current()->GetClassLinker()->EnsureInitialized(klass, true)) {
235 DCHECK(Thread::Current()->IsExceptionPending());
236 return NULL; // Failure
237 }
Ian Rogers21d9e832011-09-23 17:05:09 -0700238 return klass->AllocObject();
239}
240
Ian Rogersb886da82011-09-23 16:27:54 -0700241// Helper function to alloc array for OP_FILLED_NEW_ARRAY
242extern "C" Array* artCheckAndArrayAllocFromCode(uint32_t type_idx, Method* method,
243 int32_t component_count) {
244 if (component_count < 0) {
245 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
246 component_count);
247 return NULL; // Failure
248 }
249 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
250 if (klass == NULL) { // Not in dex cache so try to resolve
251 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
252 if (klass == NULL) { // Error
253 DCHECK(Thread::Current()->IsExceptionPending());
254 return NULL; // Failure
255 }
256 }
257 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
258 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
259 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
260 "Bad filled array request for type %s",
261 PrettyDescriptor(klass->GetDescriptor()).c_str());
262 } else {
263 Thread::Current()->ThrowNewException("Ljava/lang/InternalError;",
264 "Found type %s; filled-new-array not implemented for anything but \'int\'",
265 PrettyDescriptor(klass->GetDescriptor()).c_str());
266 }
267 return NULL; // Failure
268 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700269 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700270 return Array::Alloc(klass, component_count);
271 }
272}
273
274// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
275// it cannot be resolved, throw an error. If it can, use it to create an array.
276extern "C" Array* artArrayAllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
277 if (component_count < 0) {
278 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
279 component_count);
280 return NULL; // Failure
281 }
282 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
283 if (klass == NULL) { // Not in dex cache so try to resolve
284 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
285 if (klass == NULL) { // Error
286 DCHECK(Thread::Current()->IsExceptionPending());
287 return NULL; // Failure
288 }
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700289 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
Ian Rogersb886da82011-09-23 16:27:54 -0700290 }
291 return Array::Alloc(klass, component_count);
buzbee1da522d2011-09-04 11:22:20 -0700292}
293
Ian Rogerse51a5112011-09-23 14:16:35 -0700294// 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 -0700295extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700296 DCHECK(a->IsClass()) << PrettyClass(a);
297 DCHECK(b->IsClass()) << PrettyClass(b);
Brian Carlstromc2282522011-09-17 10:33:14 -0700298 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700299 return 0; // Success
300 } else {
301 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700302 "%s cannot be cast to %s",
303 PrettyDescriptor(a->GetDescriptor()).c_str(),
304 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700305 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700306 }
buzbee2a475e72011-09-07 17:19:17 -0700307}
308
Ian Rogerse51a5112011-09-23 14:16:35 -0700309// Tests whether 'element' can be assigned into an array of type 'array_class'.
310// Returns 0 on success and -1 if an exception is pending.
311extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
312 DCHECK(array_class != NULL);
313 // element can't be NULL as we catch this is screened in runtime_support
314 Class* element_class = element->GetClass();
315 Class* component_type = array_class->GetComponentType();
316 if (component_type->IsAssignableFrom(element_class)) {
317 return 0; // Success
318 } else {
319 Thread::Current()->ThrowNewException("Ljava/lang/ArrayStoreException;",
Ian Rogersb886da82011-09-23 16:27:54 -0700320 "Cannot store an object of type %s in to an array of type %s",
321 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
322 PrettyDescriptor(array_class->GetDescriptor()).c_str());
Ian Rogerse51a5112011-09-23 14:16:35 -0700323 return -1; // Failure
324 }
325}
326
Ian Rogersff1ed472011-09-20 13:46:24 -0700327extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
328 DCHECK(obj != NULL); // Assumed to have been checked before entry
329 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700330}
331
Elliott Hughesd369bb72011-09-12 14:41:14 -0700332void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700333 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700334 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700335 DCHECK(thread->HoldsLock(obj));
336 // Only possible exception is NPE and is handled before entry
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700337 DCHECK(!thread->IsExceptionPending());
buzbee2a475e72011-09-07 17:19:17 -0700338}
339
buzbeec1f45042011-09-21 16:03:19 -0700340extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700341 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700342}
343
buzbee5ade1d22011-09-09 14:44:52 -0700344/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700345 * Fill the array with predefined constant values, throwing exceptions if the array is null or
346 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700347 *
348 * NOTE: When dealing with a raw dex file, the data to be copied uses
349 * little-endian ordering. Require that oat2dex do any required swapping
350 * so this routine can get by with a memcpy().
351 *
352 * Format of the data:
353 * ushort ident = 0x0300 magic value
354 * ushort width width of each element in the table
355 * uint size number of elements in the table
356 * ubyte data[size*width] table of data values (may contain a single-byte
357 * padding at the end)
358 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700359extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
360 DCHECK_EQ(table[0], 0x0300);
361 if (array == NULL) {
362 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
363 "null array in fill array");
364 return -1; // Error
365 }
366 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
367 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
368 if (static_cast<int32_t>(size) > array->GetLength()) {
369 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
370 "failed array fill. length=%d; index=%d",
371 array->GetLength(), size);
372 return -1; // Error
373 }
374 uint16_t width = table[1];
375 uint32_t size_in_bytes = size * width;
376 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
377 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700378}
379
380// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700381extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
382 Object* this_object ,
383 Method* caller_method) {
384 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700385 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700386 thread->ThrowNewException("Ljava/lang/NullPointerException;",
387 "null receiver during interface dispatch");
388 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700389 }
390 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
391 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
392 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700393 // Could not resolve interface method. Throw error and unwind
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700394 CHECK(thread->IsExceptionPending());
Ian Rogersff1ed472011-09-20 13:46:24 -0700395 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700396 }
397 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700398 if (method == NULL) {
399 CHECK(thread->IsExceptionPending());
400 return 0;
401 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700402 const void* code = method->GetCode();
403
404 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
405 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
406 uint64_t result = ((code_uint << 32) | method_uint);
407 return result;
408}
409
buzbee5ade1d22011-09-09 14:44:52 -0700410// TODO: move to more appropriate location
411/*
412 * Float/double conversion requires clamping to min and max of integer form. If
413 * target doesn't support this normally, use these.
414 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700415int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700416 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
417 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
418 if (d >= kMaxLong)
419 return (int64_t)0x7fffffffffffffffULL;
420 else if (d <= kMinLong)
421 return (int64_t)0x8000000000000000ULL;
422 else if (d != d) // NaN case
423 return 0;
424 else
425 return (int64_t)d;
426}
427
Elliott Hughesd369bb72011-09-12 14:41:14 -0700428int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700429 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
430 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
431 if (f >= kMaxLong)
432 return (int64_t)0x7fffffffffffffffULL;
433 else if (f <= kMinLong)
434 return (int64_t)0x8000000000000000ULL;
435 else if (f != f) // NaN case
436 return 0;
437 else
438 return (int64_t)f;
439}
440
Brian Carlstrom16192862011-09-12 17:50:06 -0700441// Return value helper for jobject return types
442static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
443 return thread->DecodeJObject(obj);
444}
445
buzbee3ea4ec52011-08-22 17:37:19 -0700446void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700447#if defined(__arm__)
448 pShlLong = art_shl_long;
449 pShrLong = art_shr_long;
450 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700451 pIdiv = __aeabi_idiv;
452 pIdivmod = __aeabi_idivmod;
453 pI2f = __aeabi_i2f;
454 pF2iz = __aeabi_f2iz;
455 pD2f = __aeabi_d2f;
456 pF2d = __aeabi_f2d;
457 pD2iz = __aeabi_d2iz;
458 pL2f = __aeabi_l2f;
459 pL2d = __aeabi_l2d;
460 pFadd = __aeabi_fadd;
461 pFsub = __aeabi_fsub;
462 pFdiv = __aeabi_fdiv;
463 pFmul = __aeabi_fmul;
464 pFmodf = fmodf;
465 pDadd = __aeabi_dadd;
466 pDsub = __aeabi_dsub;
467 pDdiv = __aeabi_ddiv;
468 pDmul = __aeabi_dmul;
469 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700470 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700471 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700472 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700473 pArrayAllocFromCode = art_array_alloc_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700474 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700475 pCheckAndArrayAllocFromCode = art_check_and_array_alloc_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700476 pCheckCastFromCode = art_check_cast_from_code;
477 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700478 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700479 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700480 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700481 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
482 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700483 pThrowInternalErrorFromCode = art_throw_internal_error_from_code;
484 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
485 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700486 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700487 pThrowRuntimeExceptionFromCode = art_throw_runtime_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700488 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700489 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700490 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700491#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700492 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700493 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700494 pF2l = F2L;
495 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700496 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700497 pGet32Static = Field::Get32StaticFromCode;
498 pSet32Static = Field::Set32StaticFromCode;
499 pGet64Static = Field::Get64StaticFromCode;
500 pSet64Static = Field::Set64StaticFromCode;
501 pGetObjStatic = Field::GetObjStaticFromCode;
502 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700503 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700504 pResolveMethodFromCode = ResolveMethodFromCode;
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700505 pInstanceofNonTrivialFromCode = Object::InstanceOfFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700506 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700507 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700508 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700509 pFindNativeMethod = FindNativeMethod;
510 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700511 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700512}
513
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700514void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700515 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
516 DCHECK_NE(frame_size, 0u);
517 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700518 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519 sp_ = reinterpret_cast<Method**>(next_sp);
Elliott Hughes80609252011-09-23 17:24:51 -0700520 if (*sp_ != NULL) {
521 DCHECK((*sp_)->GetClass() == Method::GetMethodClass() ||
522 (*sp_)->GetClass() == Method::GetConstructorClass());
Ian Rogersff1ed472011-09-20 13:46:24 -0700523 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700524}
525
Ian Rogers90865722011-09-19 11:11:44 -0700526bool Frame::HasMethod() const {
527 return GetMethod() != NULL && (!GetMethod()->IsPhony());
528}
529
Ian Rogersbdb03912011-09-14 00:55:44 -0700530uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700531 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700532 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700533}
534
Ian Rogersbdb03912011-09-14 00:55:44 -0700535uintptr_t Frame::LoadCalleeSave(int num) const {
536 // Callee saves are held at the top of the frame
537 Method* method = GetMethod();
538 DCHECK(method != NULL);
539 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700540 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700541#if defined(__i386__)
542 save_addr -= kPointerSize; // account for return address
543#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700544 return *reinterpret_cast<uintptr_t*>(save_addr);
545}
546
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700548 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700549 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700551}
552
Brian Carlstrom78128a62011-09-15 17:21:19 -0700553void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700554 Thread* self = reinterpret_cast<Thread*>(arg);
555 Runtime* runtime = Runtime::Current();
556
557 self->Attach(runtime);
558
Elliott Hughes038a8062011-09-18 14:12:41 -0700559 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700560 if (thread_name != NULL) {
561 SetThreadName(thread_name->ToModifiedUtf8().c_str());
562 }
563
564 // Wait until it's safe to start running code. (There may have been a suspend-all
565 // in progress while we were starting up.)
566 runtime->GetThreadList()->WaitForGo();
567
568 // TODO: say "hi" to the debugger.
569 //if (gDvm.debuggerConnected) {
570 // dvmDbgPostThreadStart(self);
571 //}
572
573 // Invoke the 'run' method of our java.lang.Thread.
574 CHECK(self->peer_ != NULL);
575 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700576 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700577 m->Invoke(self, receiver, NULL, NULL);
578
579 // Detach.
580 runtime->GetThreadList()->Unregister();
581
Carl Shapirob5573532011-07-12 18:22:59 -0700582 return NULL;
583}
584
Elliott Hughes93e74e82011-09-13 11:07:03 -0700585void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700586 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700587}
588
Elliott Hughes01158d72011-09-19 19:47:10 -0700589Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
590 Object* thread = Decode<Object*>(env, java_thread);
591 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
592}
593
Elliott Hughesd369bb72011-09-12 14:41:14 -0700594void Thread::Create(Object* peer, size_t stack_size) {
595 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700596
Elliott Hughesd369bb72011-09-12 14:41:14 -0700597 if (stack_size == 0) {
598 stack_size = Runtime::Current()->GetDefaultStackSize();
599 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700600
Elliott Hughes93e74e82011-09-13 11:07:03 -0700601 Thread* native_thread = new Thread;
602 native_thread->peer_ = peer;
603
604 // Thread.start is synchronized, so we know that vmData is 0,
605 // and know that we're not racing to assign it.
606 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700607
608 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700609 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
610 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
611 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
612 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
613 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700614
615 // Let the child know when it's safe to start running.
616 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700617}
618
Elliott Hughes93e74e82011-09-13 11:07:03 -0700619void Thread::Attach(const Runtime* runtime) {
620 InitCpu();
621 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700622
Elliott Hughes93e74e82011-09-13 11:07:03 -0700623 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700624
Elliott Hughes93e74e82011-09-13 11:07:03 -0700625 tid_ = ::art::GetTid();
626 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700627
Elliott Hughes93e74e82011-09-13 11:07:03 -0700628 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700629
Elliott Hughes8d768a92011-09-14 16:35:25 -0700630 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700631
Elliott Hughes93e74e82011-09-13 11:07:03 -0700632 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700633
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700634 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700635}
636
637Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
638 Thread* self = new Thread;
639 self->Attach(runtime);
640
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700641 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700642
643 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700644
645 // If we're the main thread, ClassLinker won't be created until after we're attached,
646 // so that thread needs a two-stage attach. Regular threads don't need this hack.
647 if (self->thin_lock_id_ != ThreadList::kMainId) {
648 self->CreatePeer(name, as_daemon);
649 }
650
651 return self;
652}
653
Elliott Hughesd369bb72011-09-12 14:41:14 -0700654jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
655 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
656 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
657 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
658 // This will be null in the compiler (and tests), but never in a running system.
659 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
660 return thread_group;
661}
662
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700663void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700664 JNIEnv* env = jni_env_;
665
Elliott Hughesd369bb72011-09-12 14:41:14 -0700666 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
667 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700668 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700669 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700670 jboolean thread_is_daemon = as_daemon;
671
672 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700673 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700674
Elliott Hughes8daa0922011-09-11 13:46:25 -0700675 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700676 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700677 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700678
679 // Because we mostly run without code available (in the compiler, in tests), we
680 // manually assign the fields the constructor should have set.
681 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700682 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
683 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
684 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
685 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700686}
687
Elliott Hughesbe759c62011-09-08 19:38:21 -0700688void Thread::InitStackHwm() {
689 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700690 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700691
Ian Rogers932746a2011-09-22 18:57:50 -0700692 void* temp_stack_base;
693 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
694 __FUNCTION__);
695 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700696
Ian Rogers932746a2011-09-22 18:57:50 -0700697 if (stack_size_ <= kStackOverflowReservedBytes) {
698 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700699 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700700
Ian Rogers932746a2011-09-22 18:57:50 -0700701 // Set stack_end_ to the bottom of the stack saving space of stack overflows
702 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700703
704 // Sanity check.
705 int stack_variable;
706 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700707
Elliott Hughes8d768a92011-09-14 16:35:25 -0700708 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700709}
710
Elliott Hughesa0957642011-09-02 14:27:33 -0700711void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700712 DumpState(os);
713 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700714}
715
Elliott Hughesd92bec42011-09-02 17:04:36 -0700716std::string GetSchedulerGroup(pid_t tid) {
717 // /proc/<pid>/group looks like this:
718 // 2:devices:/
719 // 1:cpuacct,cpu:/
720 // We want the third field from the line whose second field contains the "cpu" token.
721 std::string cgroup_file;
722 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
723 return "";
724 }
725 std::vector<std::string> cgroup_lines;
726 Split(cgroup_file, '\n', cgroup_lines);
727 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
728 std::vector<std::string> cgroup_fields;
729 Split(cgroup_lines[i], ':', cgroup_fields);
730 std::vector<std::string> cgroups;
731 Split(cgroup_fields[1], ',', cgroups);
732 for (size_t i = 0; i < cgroups.size(); ++i) {
733 if (cgroups[i] == "cpu") {
734 return cgroup_fields[2].substr(1); // Skip the leading slash.
735 }
736 }
737 }
738 return "";
739}
740
741void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700742 std::string thread_name("<native thread without managed peer>");
743 std::string group_name;
744 int priority;
745 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700746
Elliott Hughesd369bb72011-09-12 14:41:14 -0700747 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700748 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700749 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700750 priority = gThread_priority->GetInt(peer_);
751 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700752
Elliott Hughes038a8062011-09-18 14:12:41 -0700753 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700754 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700755 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700756 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
757 }
758 } else {
759 // 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 -0700760 std::string stats;
761 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
762 size_t start = stats.find('(') + 1;
763 size_t end = stats.find(')') - start;
764 thread_name = stats.substr(start, end);
765 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700766 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700767 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700768
769 int policy;
770 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700771 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700772
773 std::string scheduler_group(GetSchedulerGroup(GetTid()));
774 if (scheduler_group.empty()) {
775 scheduler_group = "default";
776 }
777
Elliott Hughesd92bec42011-09-02 17:04:36 -0700778 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700779 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700780 os << " daemon";
781 }
782 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700783 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700784 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700785
Elliott Hughesd92bec42011-09-02 17:04:36 -0700786 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700787 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700788 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700789 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700790 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700791 << " self=" << reinterpret_cast<const void*>(this) << "\n";
792 os << " | sysTid=" << GetTid()
793 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
794 << " sched=" << policy << "/" << sp.sched_priority
795 << " cgrp=" << scheduler_group
796 << " handle=" << GetImpl() << "\n";
797
798 // Grab the scheduler stats for this thread.
799 std::string scheduler_stats;
800 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
801 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
802 } else {
803 scheduler_stats = "0 0 0";
804 }
805
806 int utime = 0;
807 int stime = 0;
808 int task_cpu = 0;
809 std::string stats;
810 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
811 // Skip the command, which may contain spaces.
812 stats = stats.substr(stats.find(')') + 2);
813 // Extract the three fields we care about.
814 std::vector<std::string> fields;
815 Split(stats, ' ', fields);
816 utime = strtoull(fields[11].c_str(), NULL, 10);
817 stime = strtoull(fields[12].c_str(), NULL, 10);
818 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
819 }
820
821 os << " | schedstat=( " << scheduler_stats << " )"
822 << " utm=" << utime
823 << " stm=" << stime
824 << " core=" << task_cpu
825 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
826}
827
Elliott Hughesd369bb72011-09-12 14:41:14 -0700828struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700829 StackDumpVisitor(std::ostream& os, const Thread* thread)
830 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700831 }
832
Ian Rogersbdb03912011-09-14 00:55:44 -0700833 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700834 }
835
Ian Rogersbdb03912011-09-14 00:55:44 -0700836 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700837 if (!frame.HasMethod()) {
838 return;
839 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700840
841 Method* m = frame.GetMethod();
842 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700843 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700844 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
845
846 os << " at " << PrettyMethod(m, false);
847 if (m->IsNative()) {
848 os << "(Native method)";
849 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700850 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700851 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
852 }
853 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700854
855 if (frame_count++ == 0) {
856 Monitor::DescribeWait(os, thread);
857 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700858 }
859
860 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700861 const Thread* thread;
862 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700863};
864
Elliott Hughesd92bec42011-09-02 17:04:36 -0700865void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700866 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700867 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700868}
869
Elliott Hughes8d768a92011-09-14 16:35:25 -0700870Thread::State Thread::SetState(Thread::State new_state) {
871 Thread::State old_state = state_;
872 if (old_state == new_state) {
873 return old_state;
874 }
875
876 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
877 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
878
879 if (new_state == Thread::kRunnable) {
880 /*
881 * Change our status to Thread::kRunnable. The transition requires
882 * that we check for pending suspension, because the VM considers
883 * us to be "asleep" in all other states, and another thread could
884 * be performing a GC now.
885 *
886 * The order of operations is very significant here. One way to
887 * do this wrong is:
888 *
889 * GCing thread Our thread (in kNative)
890 * ------------ ----------------------
891 * check suspend count (== 0)
892 * SuspendAllThreads()
893 * grab suspend-count lock
894 * increment all suspend counts
895 * release suspend-count lock
896 * check thread state (== kNative)
897 * all are suspended, begin GC
898 * set state to kRunnable
899 * (continue executing)
900 *
901 * We can correct this by grabbing the suspend-count lock and
902 * performing both of our operations (check suspend count, set
903 * state) while holding it, now we need to grab a mutex on every
904 * transition to kRunnable.
905 *
906 * What we do instead is change the order of operations so that
907 * the transition to kRunnable happens first. If we then detect
908 * that the suspend count is nonzero, we switch to kSuspended.
909 *
910 * Appropriate compiler and memory barriers are required to ensure
911 * that the operations are observed in the expected order.
912 *
913 * This does create a small window of opportunity where a GC in
914 * progress could observe what appears to be a running thread (if
915 * it happens to look between when we set to kRunnable and when we
916 * switch to kSuspended). At worst this only affects assertions
917 * and thread logging. (We could work around it with some sort
918 * of intermediate "pre-running" state that is generally treated
919 * as equivalent to running, but that doesn't seem worthwhile.)
920 *
921 * We can also solve this by combining the "status" and "suspend
922 * count" fields into a single 32-bit value. This trades the
923 * store/load barrier on transition to kRunnable for an atomic RMW
924 * op on all transitions and all suspend count updates (also, all
925 * accesses to status or the thread count require bit-fiddling).
926 * It also eliminates the brief transition through kRunnable when
927 * the thread is supposed to be suspended. This is possibly faster
928 * on SMP and slightly more correct, but less convenient.
929 */
930 android_atomic_acquire_store(new_state, addr);
931 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
932 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
933 }
934 } else {
935 /*
936 * Not changing to Thread::kRunnable. No additional work required.
937 *
938 * We use a releasing store to ensure that, if we were runnable,
939 * any updates we previously made to objects on the managed heap
940 * will be observed before the state change.
941 */
942 android_atomic_release_store(new_state, addr);
943 }
944
945 return old_state;
946}
947
948void Thread::WaitUntilSuspended() {
949 // TODO: dalvik dropped the waiting thread's priority after a while.
950 // TODO: dalvik timed out and aborted.
951 useconds_t delay = 0;
952 while (GetState() == Thread::kRunnable) {
953 useconds_t new_delay = delay * 2;
954 CHECK_GE(new_delay, delay);
955 delay = new_delay;
956 if (delay == 0) {
957 sched_yield();
958 delay = 10000;
959 } else {
960 usleep(delay);
961 }
962 }
963}
964
Elliott Hughesbe759c62011-09-08 19:38:21 -0700965void Thread::ThreadExitCallback(void* arg) {
966 Thread* self = reinterpret_cast<Thread*>(arg);
967 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700968}
969
Elliott Hughesbe759c62011-09-08 19:38:21 -0700970void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700971 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700972 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700973
974 // Double-check the TLS slot allocation.
975 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700976 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700977 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700978}
Carl Shapirob5573532011-07-12 18:22:59 -0700979
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700980// TODO: make more accessible?
981Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
982 Class* c = class_linker->FindPrimitiveClass(descriptor);
983 CHECK(c != NULL) << descriptor;
984 return c;
985}
986
987// TODO: make more accessible?
988Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
989 Class* c = class_linker->FindSystemClass(descriptor);
990 CHECK(c != NULL) << descriptor;
991 return c;
992}
993
994// TODO: make more accessible?
995Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
996 Field* f = c->FindDeclaredInstanceField(name, type);
997 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
998 return f;
999}
1000
1001// TODO: make more accessible?
1002Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
1003 Method* m = c->FindVirtualMethod(name, signature);
1004 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
1005 return m;
1006}
1007
Elliott Hughes038a8062011-09-18 14:12:41 -07001008void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -07001009 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
1010 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001011
1012 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
1013 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
1014 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
1015 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
1016 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
1017 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
1018 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
1019 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
1020
1021 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
1022 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
1023 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
1024 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
1025 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
1026 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
1027 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
1028 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
1029 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
1030
1031 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
1032 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
1033 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
1034 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -07001035
1036 // Finish attaching the main thread.
1037 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -07001038}
1039
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001040void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -07001041 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001042}
1043
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001044uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
1045 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
1046 return ThreadList::kInvalidId;
1047 }
1048 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
1049 if (managed_thread == NULL) {
1050 return ThreadList::kInvalidId;
1051 }
1052 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
1053 Thread* thread = reinterpret_cast<Thread*>(vmData);
1054 if (thread == NULL) {
1055 return ThreadList::kInvalidId;
1056 }
1057 return thread->GetThinLockId();
1058}
1059
Elliott Hughesdcc24742011-09-07 14:02:44 -07001060Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -07001061 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001062 top_of_managed_stack_(),
1063 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001064 wait_mutex_(new Mutex("Thread wait mutex")),
1065 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001066 wait_monitor_(NULL),
1067 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001068 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001069 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001070 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001071 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001072 native_to_managed_record_(NULL),
1073 top_sirt_(NULL),
1074 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001075 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -07001076 self_(NULL),
1077 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -07001078 exception_(NULL),
1079 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -07001080 class_loader_override_(NULL),
1081 long_jump_context_(NULL) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001082 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001083}
1084
Elliott Hughes02b48d12011-09-07 17:15:51 -07001085void MonitorExitVisitor(const Object* object, void*) {
1086 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -07001087 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001088}
1089
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001090Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -07001091 SetState(Thread::kRunnable);
1092
Elliott Hughes02b48d12011-09-07 17:15:51 -07001093 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -07001094 if (jni_env_ != NULL) {
1095 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
1096 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001097
Elliott Hughes93e74e82011-09-13 11:07:03 -07001098 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001099 Object* group = gThread_group->GetObject(peer_);
1100
1101 // Handle any pending exception.
1102 if (IsExceptionPending()) {
1103 // Get and clear the exception.
1104 Object* exception = GetException();
1105 ClearException();
1106
1107 // If the thread has its own handler, use that.
1108 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1109 if (handler == NULL) {
1110 // Otherwise use the thread group's default handler.
1111 handler = group;
1112 }
1113
1114 // Call the handler.
1115 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
1116 Object* args[2];
1117 args[0] = peer_;
1118 args[1] = exception;
1119 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
1120
1121 // If the handler threw, clear that exception too.
1122 ClearException();
1123 }
1124
1125 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -07001126 // group can be null if we're in the compiler or a test.
1127 if (group != NULL) {
1128 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
1129 Object* args = peer_;
1130 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
1131 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001132
1133 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -07001134 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001135
Elliott Hughes29f27422011-09-18 16:02:18 -07001136 // TODO: say "bye" to the debugger.
1137 //if (gDvm.debuggerConnected) {
1138 // dvmDbgPostThreadDeath(self);
1139 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001140
Elliott Hughes29f27422011-09-18 16:02:18 -07001141 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1142 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -07001143 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -07001144 Object* lock = gThread_lock->GetObject(peer_);
1145 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -07001146 if (lock != NULL) {
1147 lock->MonitorEnter(self);
1148 lock->NotifyAll();
1149 lock->MonitorExit(self);
1150 }
1151 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001152
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001153 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001154 jni_env_ = NULL;
1155
1156 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001157
1158 delete wait_cond_;
1159 delete wait_mutex_;
1160
1161 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001162}
1163
Ian Rogers408f79a2011-08-23 18:22:33 -07001164size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001165 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001166 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001167 count += cur->NumberOfReferences();
1168 }
1169 return count;
1170}
1171
Ian Rogers408f79a2011-08-23 18:22:33 -07001172bool Thread::SirtContains(jobject obj) {
1173 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1174 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001175 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001176 // A SIRT should always have a jobject/jclass as a native method is passed
1177 // in a this pointer or a class
1178 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001179 if ((&cur->References()[0] <= sirt_entry) &&
1180 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001181 return true;
1182 }
1183 }
1184 return false;
1185}
1186
Ian Rogers67375ac2011-09-14 00:55:44 -07001187void Thread::PopSirt() {
1188 CHECK(top_sirt_ != NULL);
1189 top_sirt_ = top_sirt_->Link();
1190}
1191
Ian Rogers408f79a2011-08-23 18:22:33 -07001192Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001193 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001194 if (obj == NULL) {
1195 return NULL;
1196 }
1197 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1198 IndirectRefKind kind = GetIndirectRefKind(ref);
1199 Object* result;
1200 switch (kind) {
1201 case kLocal:
1202 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001203 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001204 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001205 break;
1206 }
1207 case kGlobal:
1208 {
1209 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1210 IndirectReferenceTable& globals = vm->globals;
1211 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001212 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001213 break;
1214 }
1215 case kWeakGlobal:
1216 {
1217 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1218 IndirectReferenceTable& weak_globals = vm->weak_globals;
1219 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001220 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001221 if (result == kClearedJniWeakGlobal) {
1222 // This is a special case where it's okay to return NULL.
1223 return NULL;
1224 }
1225 break;
1226 }
1227 case kSirtOrInvalid:
1228 default:
1229 // TODO: make stack indirect reference table lookup more efficient
1230 // Check if this is a local reference in the SIRT
1231 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001232 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001233 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001234 // Assume an invalid local reference is actually a direct pointer.
1235 result = reinterpret_cast<Object*>(obj);
1236 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001237 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001238 }
1239 }
1240
1241 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001242 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1243 JniAbort(NULL);
1244 } else {
1245 if (result != kInvalidIndirectRefObject) {
1246 Heap::VerifyObject(result);
1247 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001248 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001249 return result;
1250}
1251
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001252class CountStackDepthVisitor : public Thread::StackVisitor {
1253 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001254 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001255
Elliott Hughes29f27422011-09-18 16:02:18 -07001256 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1257 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001258 // Note we also skip the frame if it doesn't have a method (namely the callee
1259 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001260 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001261 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001262 skipping_ = false;
1263 }
1264 if (!skipping_) {
1265 ++depth_;
1266 } else {
1267 ++skip_depth_;
1268 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001269 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001270
1271 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001272 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001273 }
1274
Elliott Hughes29f27422011-09-18 16:02:18 -07001275 int GetSkipDepth() const {
1276 return skip_depth_;
1277 }
1278
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001279 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001280 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001281 uint32_t skip_depth_;
1282 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001283};
1284
Ian Rogersaaa20802011-09-11 21:47:37 -07001285class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001286 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001287 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1288 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001289 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001290 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001291 // Register a local reference as IntArray::Alloc may trigger GC
1292 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1293 pc_trace_ = IntArray::Alloc(depth);
1294#ifdef MOVING_GARBAGE_COLLECTOR
1295 // Re-read after potential GC
1296 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1297#endif
1298 // Save PC trace in last element of method trace, also places it into the
1299 // object graph.
1300 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001301 }
1302
Ian Rogersaaa20802011-09-11 21:47:37 -07001303 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001304
Ian Rogersbdb03912011-09-14 00:55:44 -07001305 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001306 if (skip_depth_ > 0) {
1307 skip_depth_--;
1308 return;
1309 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001310 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001311 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001312 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001313 }
1314
Ian Rogersaaa20802011-09-11 21:47:37 -07001315 jobject GetInternalStackTrace() const {
1316 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001317 }
1318
1319 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001320 // How many more frames to skip.
1321 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001322 // Current position down stack trace
1323 uint32_t count_;
1324 // Array of return PC values
1325 IntArray* pc_trace_;
1326 // An array of the methods on the stack, the last entry is a reference to the
1327 // PC trace
1328 ObjectArray<Object>* method_trace_;
1329 // Local indirect reference table entry for method trace
1330 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001331};
1332
Ian Rogersaaa20802011-09-11 21:47:37 -07001333void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001334 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001335 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001336 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1337 // CHECK(native_to_managed_record_ != NULL);
1338 NativeToManagedRecord* record = native_to_managed_record_;
1339
Ian Rogersbdb03912011-09-14 00:55:44 -07001340 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001341 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001342 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1343 visitor->VisitFrame(frame, pc);
1344 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001345 }
1346 if (record == NULL) {
1347 break;
1348 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001349 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001350 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001351 pc = record->last_top_of_managed_stack_pc_;
1352 record = record->link_;
1353 }
1354}
1355
Ian Rogers67375ac2011-09-14 00:55:44 -07001356void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001357 Frame frame = GetTopOfStack();
1358 uintptr_t pc = top_of_managed_stack_pc_;
1359
1360 if (frame.GetSP() != 0) {
1361 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001362 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001363 visitor->VisitFrame(frame, pc);
1364 pc = frame.GetReturnPC();
1365 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001366 if (include_upcall) {
1367 visitor->VisitFrame(frame, pc);
1368 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001369 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001370}
1371
Elliott Hughes01158d72011-09-19 19:47:10 -07001372jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001373 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001374 CountStackDepthVisitor count_visitor;
1375 WalkStack(&count_visitor);
1376 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001377 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001378
Ian Rogersaaa20802011-09-11 21:47:37 -07001379 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001380 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001381
1382 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001383 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001384 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001385
Ian Rogersaaa20802011-09-11 21:47:37 -07001386 return build_trace_visitor.GetInternalStackTrace();
1387}
1388
Elliott Hughes01158d72011-09-19 19:47:10 -07001389jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1390 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001391 // Transition into runnable state to work on Object*/Array*
1392 ScopedJniThreadState ts(env);
1393
1394 // Decode the internal stack trace into the depth, method trace and PC trace
1395 ObjectArray<Object>* method_trace =
1396 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1397 int32_t depth = method_trace->GetLength()-1;
1398 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1399
1400 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1401
Elliott Hughes01158d72011-09-19 19:47:10 -07001402 jobjectArray result;
1403 ObjectArray<StackTraceElement>* java_traces;
1404 if (output_array != NULL) {
1405 // Reuse the array we were given.
1406 result = output_array;
1407 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1408 output_array));
1409 // ...adjusting the number of frames we'll write to not exceed the array length.
1410 depth = std::min(depth, java_traces->GetLength());
1411 } else {
1412 // Create java_trace array and place in local reference table
1413 java_traces = class_linker->AllocStackTraceElementArray(depth);
1414 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1415 }
1416
1417 if (stack_depth != NULL) {
1418 *stack_depth = depth;
1419 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001420
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001421 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001422 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1423 Method* method = down_cast<Method*>(method_trace->Get(i));
1424 uint32_t native_pc = pc_trace->Get(i);
1425 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001426 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001427 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001428
Ian Rogersaaa20802011-09-11 21:47:37 -07001429 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001430 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001431 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001432 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001433 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001434 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001435 method->ToDexPC(native_pc)));
1436#ifdef MOVING_GARBAGE_COLLECTOR
1437 // Re-read after potential GC
1438 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1439 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1440 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1441#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001442 java_traces->Set(i, obj);
1443 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001444 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001445}
1446
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001447void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001448 va_list args;
1449 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001450 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001451 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001452}
1453
1454void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1455 std::string msg;
1456 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001457
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001458 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001459 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001460 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001461 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001462 descriptor.erase(descriptor.length() - 1);
1463
1464 JNIEnv* env = GetJniEnv();
1465 jclass exception_class = env->FindClass(descriptor.c_str());
1466 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1467 int rc = env->ThrowNew(exception_class, msg.c_str());
1468 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001469 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001470}
1471
Elliott Hughes79082e32011-08-25 12:07:32 -07001472void Thread::ThrowOutOfMemoryError() {
1473 UNIMPLEMENTED(FATAL);
1474}
1475
Ian Rogersbdb03912011-09-14 00:55:44 -07001476class CatchBlockStackVisitor : public Thread::StackVisitor {
1477 public:
1478 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001479 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1480#ifndef NDEBUG
1481 handler_pc_ = 0xEBADC0DE;
1482 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1483#endif
1484 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001485
Ian Rogersbdb03912011-09-14 00:55:44 -07001486 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1487 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001488 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001489 if (method == NULL) {
1490 // This is the upcall, we remember the frame and last_pc so that we may
1491 // long jump to them
1492 handler_pc_ = pc;
1493 handler_frame_ = fr;
1494 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001495 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001496 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001497 if (method->IsPhony()) {
1498 // ignore callee save method
1499 } else if (method->IsNative()) {
1500 native_method_count_++;
1501 } else {
1502 // Move the PC back 2 bytes as a call will frequently terminate the
1503 // decoding of a particular instruction and we want to make sure we
1504 // get the Dex PC of the instruction with the call and not the
1505 // instruction following.
1506 pc -= 2;
1507 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001508 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001509 if (dex_pc != DexFile::kDexNoIndex) {
1510 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1511 if (found_dex_pc != DexFile::kDexNoIndex) {
1512 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001513 handler_pc_ = method->ToNativePC(found_dex_pc);
1514 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001515 }
1516 }
1517 if (!found_) {
1518 // Caller may be handler, fill in callee saves in context
1519 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001520 }
1521 }
1522 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001523
1524 // Did we find a catch block yet?
1525 bool found_;
1526 // The type of the exception catch block to find
1527 Class* to_find_;
1528 // Frame with found handler or last frame if no handler found
1529 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001530 // PC to branch to for the handler
1531 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001532 // Context that will be the target of the long jump
1533 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001534 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1535 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001536};
1537
Ian Rogersff1ed472011-09-20 13:46:24 -07001538void Thread::DeliverException() {
1539 Throwable *exception = GetException(); // Set exception on thread
1540 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001541
1542 Context* long_jump_context = GetLongJumpContext();
1543 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001544 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001545
Ian Rogers67375ac2011-09-14 00:55:44 -07001546 // Pop any SIRT
1547 if (catch_finder.native_method_count_ == 1) {
1548 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001549 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001550 // We only expect the stack crawl to have passed 1 native method as it's terminated
1551 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001552 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001553 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001554 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1555 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001556 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001557}
1558
Ian Rogersbdb03912011-09-14 00:55:44 -07001559Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001560 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001561 if (result == NULL) {
1562 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001563 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001564 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001565 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001566}
1567
Elliott Hughes5f791332011-09-15 17:45:30 -07001568bool Thread::HoldsLock(Object* object) {
1569 if (object == NULL) {
1570 return false;
1571 }
1572 return object->GetLockOwner() == thin_lock_id_;
1573}
1574
Elliott Hughes038a8062011-09-18 14:12:41 -07001575bool Thread::IsDaemon() {
1576 return gThread_daemon->GetBoolean(peer_);
1577}
1578
Elliott Hughes410c0c82011-09-01 17:58:25 -07001579void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001580 if (exception_ != NULL) {
1581 visitor(exception_, arg);
1582 }
1583 if (peer_ != NULL) {
1584 visitor(peer_, arg);
1585 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001586 jni_env_->locals.VisitRoots(visitor, arg);
1587 jni_env_->monitors.VisitRoots(visitor, arg);
1588 // visitThreadStack(visitor, thread, arg);
1589 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1590}
1591
Ian Rogersb033c752011-07-20 12:22:35 -07001592static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001593 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001594 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001595 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001596 "Blocked",
1597 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001598 "Initializing",
1599 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001600 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001601 "VmWait",
1602 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001603};
1604std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001605 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001606 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1607 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001608 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001609 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001610 }
1611 return os;
1612}
1613
Elliott Hughes330304d2011-08-12 14:28:05 -07001614std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1615 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001616 << ",pthread_t=" << thread.GetImpl()
1617 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001618 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001619 << ",state=" << thread.GetState()
1620 << ",peer=" << thread.GetPeer()
1621 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001622 return os;
1623}
1624
Elliott Hughes8daa0922011-09-11 13:46:25 -07001625} // namespace art