blob: 22495be9c2c4d1416e2777c698afc055dc0e778a [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
21#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070030#include "context.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070031#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070032#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070033#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070035#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070036#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070037#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070038#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070039
40namespace art {
41
42pthread_key_t Thread::pthread_key_self_;
43
Elliott Hughes29f27422011-09-18 16:02:18 -070044static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070045static Field* gThread_daemon = NULL;
46static Field* gThread_group = NULL;
47static Field* gThread_lock = NULL;
48static Field* gThread_name = NULL;
49static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070050static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070051static Field* gThread_vmData = NULL;
52static Field* gThreadGroup_name = NULL;
53static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070054static Method* gThreadGroup_removeThread = NULL;
55static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070056
buzbee4a3164f2011-09-03 11:25:10 -070057// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070058void DebugMe(Method* method, uint32_t info) {
Elliott Hughes01158d72011-09-19 19:47:10 -070059 LOG(INFO) << "DebugMe";
60 if (method != NULL) {
61 LOG(INFO) << PrettyMethod(method);
62 }
63 LOG(INFO) << "Info: " << info;
buzbee4a3164f2011-09-03 11:25:10 -070064}
65
Ian Rogersbdb03912011-09-14 00:55:44 -070066// Called by generated call to throw an exception
Ian Rogersff1ed472011-09-20 13:46:24 -070067extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070068 /*
69 * exception may be NULL, in which case this routine should
70 * throw NPE. NOTE: this is a convenience for generated code,
71 * which previously did the null check inline and constructed
72 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070073 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070074 */
Ian Rogers67375ac2011-09-14 00:55:44 -070075 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070076 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogersbdb03912011-09-14 00:55:44 -070077 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070078 if (exception == NULL) {
79 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
Ian Rogersff1ed472011-09-20 13:46:24 -070080 } else {
81 thread->SetException(exception);
Ian Rogers93dd9662011-09-17 23:21:22 -070082 }
Ian Rogersff1ed472011-09-20 13:46:24 -070083 thread->DeliverException();
84}
85
86// Deliver an exception that's pending on thread helping set up a callee save frame on the way
87extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
88 *sp = Runtime::Current()->GetCalleeSaveMethod();
89 thread->SetTopOfStack(sp, 0);
90 thread->DeliverException();
buzbee1b4c8592011-08-31 10:43:51 -070091}
92
Ian Rogers9651f422011-09-19 20:26:07 -070093// Called by generated call to throw a NPE exception
Ian Rogersff1ed472011-09-20 13:46:24 -070094extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -070095 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070096 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -070097 thread->SetTopOfStack(sp, 0);
98 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
Ian Rogersff1ed472011-09-20 13:46:24 -070099 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700100}
101
102// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700103extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700104 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700105 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700106 thread->SetTopOfStack(sp, 0);
107 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
Ian Rogersff1ed472011-09-20 13:46:24 -0700108 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700109}
110
111// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700112extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700113 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700114 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700115 thread->SetTopOfStack(sp, 0);
116 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
117 "length=%d; index=%d", limit, index);
Ian Rogersff1ed472011-09-20 13:46:24 -0700118 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700119}
120
Ian Rogersff1ed472011-09-20 13:46:24 -0700121// Called by the AbstractMethodError stub (not runtime support)
122void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
123 *sp = Runtime::Current()->GetCalleeSaveMethod();
124 thread->SetTopOfStack(sp, 0);
Ian Rogersa0841a82011-09-22 14:16:31 -0700125 thread->ThrowNewException("Ljava/lang/AbstractMethodError;",
Ian Rogersff1ed472011-09-20 13:46:24 -0700126 "abstract method \"%s\"",
127 PrettyMethod(method).c_str());
128 thread->DeliverException();
129}
130
Ian Rogers932746a2011-09-22 18:57:50 -0700131extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
132 // Place a special frame at the TOS that will save all callee saves
133 Runtime* runtime = Runtime::Current();
134 *sp = runtime->GetCalleeSaveMethod();
135 thread->SetTopOfStack(sp, 0);
136 thread->SetStackEndForStackOverflow();
137 thread->ThrowNewException("Ljava/lang/StackOverflowError;",
138 "stack size %zdkb; default stack size: %zdkb",
139 thread->GetStackSize() / KB, runtime->GetDefaultStackSize() / KB);
140 thread->ResetDefaultStackEnd();
141 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700142}
143
144// TODO: placeholder
145void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
146 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
147 " ref: " << ref;
148}
149
150// TODO: placeholder
151void ThrowNegArraySizeFromCode(int32_t index) {
152 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
153}
154
155// TODO: placeholder
156void ThrowInternalErrorFromCode(int32_t errnum) {
157 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
158}
159
160// TODO: placeholder
161void ThrowRuntimeExceptionFromCode(int32_t errnum) {
162 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
163}
164
165// TODO: placeholder
166void ThrowNoSuchMethodFromCode(int32_t method_idx) {
167 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
168}
Ian Rogersbdb03912011-09-14 00:55:44 -0700169
buzbee1b4c8592011-08-31 10:43:51 -0700170// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700171Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700172 /*
173 * Should initialize & fix up method->dex_cache_resolved_types_[].
174 * Returns initialized type. Does not return normally if an exception
175 * is thrown, but instead initiates the catch. Should be similar to
176 * ClassLinker::InitializeStaticStorageFromCode.
177 */
178 UNIMPLEMENTED(FATAL);
179 return NULL;
180}
181
buzbee561227c2011-09-02 15:28:19 -0700182// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700183void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700184 /*
185 * Slow-path handler on invoke virtual method path in which
186 * base method is unresolved at compile-time. Doesn't need to
187 * return anything - just either ensure that
188 * method->dex_cache_resolved_methods_(method_idx) != NULL or
189 * throw and unwind. The caller will restart call sequence
190 * from the beginning.
191 */
192}
193
Ian Rogers21d9e832011-09-23 17:05:09 -0700194// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
195// cannot be resolved, throw an error. If it can, use it to create an instance.
196extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method) {
197 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
198 if (klass == NULL) {
199 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
200 if (klass == NULL) {
201 DCHECK(Thread::Current()->IsExceptionPending());
202 return NULL; // Failure
203 }
204 }
205 return klass->AllocObject();
206}
207
Ian Rogersb886da82011-09-23 16:27:54 -0700208// Helper function to alloc array for OP_FILLED_NEW_ARRAY
209extern "C" Array* artCheckAndArrayAllocFromCode(uint32_t type_idx, Method* method,
210 int32_t component_count) {
211 if (component_count < 0) {
212 Thread::Current()->ThrowNewException("Ljava/lang/NegativeArraySizeException;", "%d",
213 component_count);
214 return NULL; // Failure
215 }
216 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
217 if (klass == NULL) { // Not in dex cache so try to resolve
218 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
219 if (klass == NULL) { // Error
220 DCHECK(Thread::Current()->IsExceptionPending());
221 return NULL; // Failure
222 }
223 }
224 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
225 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
226 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
227 "Bad filled array request for type %s",
228 PrettyDescriptor(klass->GetDescriptor()).c_str());
229 } else {
230 Thread::Current()->ThrowNewException("Ljava/lang/InternalError;",
231 "Found type %s; filled-new-array not implemented for anything but \'int\'",
232 PrettyDescriptor(klass->GetDescriptor()).c_str());
233 }
234 return NULL; // Failure
235 } else {
236 CHECK(klass->IsArrayClass());
237 return Array::Alloc(klass, component_count);
238 }
239}
240
241// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
242// it cannot be resolved, throw an error. If it can, use it to create an array.
243extern "C" Array* artArrayAllocFromCode(uint32_t type_idx, Method* method, 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 CHECK(klass->IsArrayClass());
257 }
258 return Array::Alloc(klass, component_count);
buzbee1da522d2011-09-04 11:22:20 -0700259}
260
Ian Rogerse51a5112011-09-23 14:16:35 -0700261// 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 -0700262extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700263 DCHECK(a->IsClass());
264 DCHECK(b->IsClass());
265 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700266 return 0; // Success
267 } else {
268 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700269 "%s cannot be cast to %s",
270 PrettyDescriptor(a->GetDescriptor()).c_str(),
271 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700272 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700273 }
buzbee2a475e72011-09-07 17:19:17 -0700274}
275
Ian Rogerse51a5112011-09-23 14:16:35 -0700276// Tests whether 'element' can be assigned into an array of type 'array_class'.
277// Returns 0 on success and -1 if an exception is pending.
278extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
279 DCHECK(array_class != NULL);
280 // element can't be NULL as we catch this is screened in runtime_support
281 Class* element_class = element->GetClass();
282 Class* component_type = array_class->GetComponentType();
283 if (component_type->IsAssignableFrom(element_class)) {
284 return 0; // Success
285 } else {
286 Thread::Current()->ThrowNewException("Ljava/lang/ArrayStoreException;",
Ian Rogersb886da82011-09-23 16:27:54 -0700287 "Cannot store an object of type %s in to an array of type %s",
288 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
289 PrettyDescriptor(array_class->GetDescriptor()).c_str());
Ian Rogerse51a5112011-09-23 14:16:35 -0700290 return -1; // Failure
291 }
292}
293
Ian Rogersff1ed472011-09-20 13:46:24 -0700294extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
295 DCHECK(obj != NULL); // Assumed to have been checked before entry
296 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700297}
298
Elliott Hughesd369bb72011-09-12 14:41:14 -0700299void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700300 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700301 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700302 DCHECK(thread->HoldsLock(obj));
303 // Only possible exception is NPE and is handled before entry
304 DCHECK(thread->GetException() == NULL);
buzbee2a475e72011-09-07 17:19:17 -0700305}
306
buzbeec1f45042011-09-21 16:03:19 -0700307extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700308 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700309}
310
buzbee5ade1d22011-09-09 14:44:52 -0700311/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700312 * Fill the array with predefined constant values, throwing exceptions if the array is null or
313 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700314 *
315 * NOTE: When dealing with a raw dex file, the data to be copied uses
316 * little-endian ordering. Require that oat2dex do any required swapping
317 * so this routine can get by with a memcpy().
318 *
319 * Format of the data:
320 * ushort ident = 0x0300 magic value
321 * ushort width width of each element in the table
322 * uint size number of elements in the table
323 * ubyte data[size*width] table of data values (may contain a single-byte
324 * padding at the end)
325 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700326extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
327 DCHECK_EQ(table[0], 0x0300);
328 if (array == NULL) {
329 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
330 "null array in fill array");
331 return -1; // Error
332 }
333 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
334 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
335 if (static_cast<int32_t>(size) > array->GetLength()) {
336 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
337 "failed array fill. length=%d; index=%d",
338 array->GetLength(), size);
339 return -1; // Error
340 }
341 uint16_t width = table[1];
342 uint32_t size_in_bytes = size * width;
343 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
344 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700345}
346
347// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700348extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
349 Object* this_object ,
350 Method* caller_method) {
351 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700352 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700353 thread->ThrowNewException("Ljava/lang/NullPointerException;",
354 "null receiver during interface dispatch");
355 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700356 }
357 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
358 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
359 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700360 // Could not resolve interface method. Throw error and unwind
361 CHECK(thread->GetException() != NULL);
362 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700363 }
364 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
365 const void* code = method->GetCode();
366
367 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
368 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
369 uint64_t result = ((code_uint << 32) | method_uint);
370 return result;
371}
372
buzbee5ade1d22011-09-09 14:44:52 -0700373// TODO: move to more appropriate location
374/*
375 * Float/double conversion requires clamping to min and max of integer form. If
376 * target doesn't support this normally, use these.
377 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700378int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700379 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
380 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
381 if (d >= kMaxLong)
382 return (int64_t)0x7fffffffffffffffULL;
383 else if (d <= kMinLong)
384 return (int64_t)0x8000000000000000ULL;
385 else if (d != d) // NaN case
386 return 0;
387 else
388 return (int64_t)d;
389}
390
Elliott Hughesd369bb72011-09-12 14:41:14 -0700391int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700392 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
393 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
394 if (f >= kMaxLong)
395 return (int64_t)0x7fffffffffffffffULL;
396 else if (f <= kMinLong)
397 return (int64_t)0x8000000000000000ULL;
398 else if (f != f) // NaN case
399 return 0;
400 else
401 return (int64_t)f;
402}
403
Brian Carlstrom16192862011-09-12 17:50:06 -0700404// Return value helper for jobject return types
405static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
406 return thread->DecodeJObject(obj);
407}
408
buzbee3ea4ec52011-08-22 17:37:19 -0700409void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700410#if defined(__arm__)
411 pShlLong = art_shl_long;
412 pShrLong = art_shr_long;
413 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700414 pIdiv = __aeabi_idiv;
415 pIdivmod = __aeabi_idivmod;
416 pI2f = __aeabi_i2f;
417 pF2iz = __aeabi_f2iz;
418 pD2f = __aeabi_d2f;
419 pF2d = __aeabi_f2d;
420 pD2iz = __aeabi_d2iz;
421 pL2f = __aeabi_l2f;
422 pL2d = __aeabi_l2d;
423 pFadd = __aeabi_fadd;
424 pFsub = __aeabi_fsub;
425 pFdiv = __aeabi_fdiv;
426 pFmul = __aeabi_fmul;
427 pFmodf = fmodf;
428 pDadd = __aeabi_dadd;
429 pDsub = __aeabi_dsub;
430 pDdiv = __aeabi_ddiv;
431 pDmul = __aeabi_dmul;
432 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700433 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700434 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700435 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700436 pArrayAllocFromCode = art_array_alloc_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700437 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Ian Rogersb886da82011-09-23 16:27:54 -0700438 pCheckAndArrayAllocFromCode = art_check_and_array_alloc_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700439 pCheckCastFromCode = art_check_cast_from_code;
440 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700441 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700442 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700443 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700444 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
445 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
446 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700447 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700448 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700449#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700450 pDeliverException = art_deliver_exception_from_code;
buzbeec396efc2011-09-11 09:36:41 -0700451 pF2l = F2L;
452 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700453 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700454 pGet32Static = Field::Get32StaticFromCode;
455 pSet32Static = Field::Set32StaticFromCode;
456 pGet64Static = Field::Get64StaticFromCode;
457 pSet64Static = Field::Set64StaticFromCode;
458 pGetObjStatic = Field::GetObjStaticFromCode;
459 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700460 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700461 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700462 pInstanceofNonTrivialFromCode = Object::InstanceOf;
buzbee2a475e72011-09-07 17:19:17 -0700463 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700464 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700465 pCheckSuspendFromCode = artCheckSuspendFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700466 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
467 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
468 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
469 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
470 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700471 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700472 pFindNativeMethod = FindNativeMethod;
473 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700474 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700475}
476
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700477void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700478 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
479 DCHECK_NE(frame_size, 0u);
480 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700481 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700482 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogersff1ed472011-09-20 13:46:24 -0700483 if(*sp_ != NULL) {
484 DCHECK_EQ((*sp_)->GetClass(), Method::GetMethodClass());
485 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700486}
487
Ian Rogers90865722011-09-19 11:11:44 -0700488bool Frame::HasMethod() const {
489 return GetMethod() != NULL && (!GetMethod()->IsPhony());
490}
491
Ian Rogersbdb03912011-09-14 00:55:44 -0700492uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700493 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700494 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700495}
496
Ian Rogersbdb03912011-09-14 00:55:44 -0700497uintptr_t Frame::LoadCalleeSave(int num) const {
498 // Callee saves are held at the top of the frame
499 Method* method = GetMethod();
500 DCHECK(method != NULL);
501 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700502 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700503#if defined(__i386__)
504 save_addr -= kPointerSize; // account for return address
505#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700506 return *reinterpret_cast<uintptr_t*>(save_addr);
507}
508
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700510 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700511 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700513}
514
Brian Carlstrom78128a62011-09-15 17:21:19 -0700515void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700516 Thread* self = reinterpret_cast<Thread*>(arg);
517 Runtime* runtime = Runtime::Current();
518
519 self->Attach(runtime);
520
Elliott Hughes038a8062011-09-18 14:12:41 -0700521 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700522 if (thread_name != NULL) {
523 SetThreadName(thread_name->ToModifiedUtf8().c_str());
524 }
525
526 // Wait until it's safe to start running code. (There may have been a suspend-all
527 // in progress while we were starting up.)
528 runtime->GetThreadList()->WaitForGo();
529
530 // TODO: say "hi" to the debugger.
531 //if (gDvm.debuggerConnected) {
532 // dvmDbgPostThreadStart(self);
533 //}
534
535 // Invoke the 'run' method of our java.lang.Thread.
536 CHECK(self->peer_ != NULL);
537 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700538 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700539 m->Invoke(self, receiver, NULL, NULL);
540
541 // Detach.
542 runtime->GetThreadList()->Unregister();
543
Carl Shapirob5573532011-07-12 18:22:59 -0700544 return NULL;
545}
546
Elliott Hughes93e74e82011-09-13 11:07:03 -0700547void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700548 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700549}
550
Elliott Hughes01158d72011-09-19 19:47:10 -0700551Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
552 Object* thread = Decode<Object*>(env, java_thread);
553 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
554}
555
Elliott Hughesd369bb72011-09-12 14:41:14 -0700556void Thread::Create(Object* peer, size_t stack_size) {
557 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700558
Elliott Hughesd369bb72011-09-12 14:41:14 -0700559 if (stack_size == 0) {
560 stack_size = Runtime::Current()->GetDefaultStackSize();
561 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700562
Elliott Hughes93e74e82011-09-13 11:07:03 -0700563 Thread* native_thread = new Thread;
564 native_thread->peer_ = peer;
565
566 // Thread.start is synchronized, so we know that vmData is 0,
567 // and know that we're not racing to assign it.
568 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700569
570 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700571 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
572 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
573 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
574 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
575 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700576
577 // Let the child know when it's safe to start running.
578 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700579}
580
Elliott Hughes93e74e82011-09-13 11:07:03 -0700581void Thread::Attach(const Runtime* runtime) {
582 InitCpu();
583 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700584
Elliott Hughes93e74e82011-09-13 11:07:03 -0700585 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700586
Elliott Hughes93e74e82011-09-13 11:07:03 -0700587 tid_ = ::art::GetTid();
588 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700589
Elliott Hughes93e74e82011-09-13 11:07:03 -0700590 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700591
Elliott Hughes8d768a92011-09-14 16:35:25 -0700592 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700593
Elliott Hughes93e74e82011-09-13 11:07:03 -0700594 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700595
Elliott Hughes93e74e82011-09-13 11:07:03 -0700596 runtime->GetThreadList()->Register(this);
597}
598
599Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
600 Thread* self = new Thread;
601 self->Attach(runtime);
602
603 self->SetState(Thread::kRunnable);
604
605 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700606
607 // If we're the main thread, ClassLinker won't be created until after we're attached,
608 // so that thread needs a two-stage attach. Regular threads don't need this hack.
609 if (self->thin_lock_id_ != ThreadList::kMainId) {
610 self->CreatePeer(name, as_daemon);
611 }
612
613 return self;
614}
615
Elliott Hughesd369bb72011-09-12 14:41:14 -0700616jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
617 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
618 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
619 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
620 // This will be null in the compiler (and tests), but never in a running system.
621 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
622 return thread_group;
623}
624
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700625void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes01158d72011-09-19 19:47:10 -0700626 Thread* self = Thread::Current();
627 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700628
629 JNIEnv* env = jni_env_;
630
Elliott Hughesd369bb72011-09-12 14:41:14 -0700631 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
632 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700633 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700634 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700635 jboolean thread_is_daemon = as_daemon;
636
637 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700638 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700639
Elliott Hughes8daa0922011-09-11 13:46:25 -0700640 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700641 peer_ = DecodeJObject(peer);
642 SetVmData(peer_, self);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700643
644 // Because we mostly run without code available (in the compiler, in tests), we
645 // manually assign the fields the constructor should have set.
646 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700647 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
648 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
649 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
650 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700651}
652
Elliott Hughesbe759c62011-09-08 19:38:21 -0700653void Thread::InitStackHwm() {
654 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700655 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700656
Ian Rogers932746a2011-09-22 18:57:50 -0700657 void* temp_stack_base;
658 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
659 __FUNCTION__);
660 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700661
Ian Rogers932746a2011-09-22 18:57:50 -0700662 if (stack_size_ <= kStackOverflowReservedBytes) {
663 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700664 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700665
Ian Rogers932746a2011-09-22 18:57:50 -0700666 // Set stack_end_ to the bottom of the stack saving space of stack overflows
667 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700668
669 // Sanity check.
670 int stack_variable;
671 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700672
Elliott Hughes8d768a92011-09-14 16:35:25 -0700673 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700674}
675
Elliott Hughesa0957642011-09-02 14:27:33 -0700676void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700677 DumpState(os);
678 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700679}
680
Elliott Hughesd92bec42011-09-02 17:04:36 -0700681std::string GetSchedulerGroup(pid_t tid) {
682 // /proc/<pid>/group looks like this:
683 // 2:devices:/
684 // 1:cpuacct,cpu:/
685 // We want the third field from the line whose second field contains the "cpu" token.
686 std::string cgroup_file;
687 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
688 return "";
689 }
690 std::vector<std::string> cgroup_lines;
691 Split(cgroup_file, '\n', cgroup_lines);
692 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
693 std::vector<std::string> cgroup_fields;
694 Split(cgroup_lines[i], ':', cgroup_fields);
695 std::vector<std::string> cgroups;
696 Split(cgroup_fields[1], ',', cgroups);
697 for (size_t i = 0; i < cgroups.size(); ++i) {
698 if (cgroups[i] == "cpu") {
699 return cgroup_fields[2].substr(1); // Skip the leading slash.
700 }
701 }
702 }
703 return "";
704}
705
706void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700707 std::string thread_name("<native thread without managed peer>");
708 std::string group_name;
709 int priority;
710 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700711
Elliott Hughesd369bb72011-09-12 14:41:14 -0700712 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700713 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700714 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700715 priority = gThread_priority->GetInt(peer_);
716 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700717
Elliott Hughes038a8062011-09-18 14:12:41 -0700718 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700719 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700720 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700721 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
722 }
723 } else {
724 // 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 -0700725 std::string stats;
726 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
727 size_t start = stats.find('(') + 1;
728 size_t end = stats.find(')') - start;
729 thread_name = stats.substr(start, end);
730 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700731 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700732 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700733
734 int policy;
735 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700736 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700737
738 std::string scheduler_group(GetSchedulerGroup(GetTid()));
739 if (scheduler_group.empty()) {
740 scheduler_group = "default";
741 }
742
Elliott Hughesd92bec42011-09-02 17:04:36 -0700743 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700744 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700745 os << " daemon";
746 }
747 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700748 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700749 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700750
Elliott Hughesd92bec42011-09-02 17:04:36 -0700751 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700752 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700753 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700754 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700755 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700756 << " self=" << reinterpret_cast<const void*>(this) << "\n";
757 os << " | sysTid=" << GetTid()
758 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
759 << " sched=" << policy << "/" << sp.sched_priority
760 << " cgrp=" << scheduler_group
761 << " handle=" << GetImpl() << "\n";
762
763 // Grab the scheduler stats for this thread.
764 std::string scheduler_stats;
765 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
766 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
767 } else {
768 scheduler_stats = "0 0 0";
769 }
770
771 int utime = 0;
772 int stime = 0;
773 int task_cpu = 0;
774 std::string stats;
775 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
776 // Skip the command, which may contain spaces.
777 stats = stats.substr(stats.find(')') + 2);
778 // Extract the three fields we care about.
779 std::vector<std::string> fields;
780 Split(stats, ' ', fields);
781 utime = strtoull(fields[11].c_str(), NULL, 10);
782 stime = strtoull(fields[12].c_str(), NULL, 10);
783 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
784 }
785
786 os << " | schedstat=( " << scheduler_stats << " )"
787 << " utm=" << utime
788 << " stm=" << stime
789 << " core=" << task_cpu
790 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
791}
792
Elliott Hughesd369bb72011-09-12 14:41:14 -0700793struct StackDumpVisitor : public Thread::StackVisitor {
794 StackDumpVisitor(std::ostream& os) : os(os) {
795 }
796
Ian Rogersbdb03912011-09-14 00:55:44 -0700797 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700798 }
799
Ian Rogersbdb03912011-09-14 00:55:44 -0700800 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700801 if (!frame.HasMethod()) {
802 return;
803 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700804 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
805
806 Method* m = frame.GetMethod();
807 Class* c = m->GetDeclaringClass();
808 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
809
810 os << " at " << PrettyMethod(m, false);
811 if (m->IsNative()) {
812 os << "(Native method)";
813 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700814 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700815 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
816 }
817 os << "\n";
818 }
819
820 std::ostream& os;
821};
822
Elliott Hughesd92bec42011-09-02 17:04:36 -0700823void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700824 StackDumpVisitor dumper(os);
825 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700826}
827
Elliott Hughes8d768a92011-09-14 16:35:25 -0700828Thread::State Thread::SetState(Thread::State new_state) {
829 Thread::State old_state = state_;
830 if (old_state == new_state) {
831 return old_state;
832 }
833
834 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
835 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
836
837 if (new_state == Thread::kRunnable) {
838 /*
839 * Change our status to Thread::kRunnable. The transition requires
840 * that we check for pending suspension, because the VM considers
841 * us to be "asleep" in all other states, and another thread could
842 * be performing a GC now.
843 *
844 * The order of operations is very significant here. One way to
845 * do this wrong is:
846 *
847 * GCing thread Our thread (in kNative)
848 * ------------ ----------------------
849 * check suspend count (== 0)
850 * SuspendAllThreads()
851 * grab suspend-count lock
852 * increment all suspend counts
853 * release suspend-count lock
854 * check thread state (== kNative)
855 * all are suspended, begin GC
856 * set state to kRunnable
857 * (continue executing)
858 *
859 * We can correct this by grabbing the suspend-count lock and
860 * performing both of our operations (check suspend count, set
861 * state) while holding it, now we need to grab a mutex on every
862 * transition to kRunnable.
863 *
864 * What we do instead is change the order of operations so that
865 * the transition to kRunnable happens first. If we then detect
866 * that the suspend count is nonzero, we switch to kSuspended.
867 *
868 * Appropriate compiler and memory barriers are required to ensure
869 * that the operations are observed in the expected order.
870 *
871 * This does create a small window of opportunity where a GC in
872 * progress could observe what appears to be a running thread (if
873 * it happens to look between when we set to kRunnable and when we
874 * switch to kSuspended). At worst this only affects assertions
875 * and thread logging. (We could work around it with some sort
876 * of intermediate "pre-running" state that is generally treated
877 * as equivalent to running, but that doesn't seem worthwhile.)
878 *
879 * We can also solve this by combining the "status" and "suspend
880 * count" fields into a single 32-bit value. This trades the
881 * store/load barrier on transition to kRunnable for an atomic RMW
882 * op on all transitions and all suspend count updates (also, all
883 * accesses to status or the thread count require bit-fiddling).
884 * It also eliminates the brief transition through kRunnable when
885 * the thread is supposed to be suspended. This is possibly faster
886 * on SMP and slightly more correct, but less convenient.
887 */
888 android_atomic_acquire_store(new_state, addr);
889 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
890 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
891 }
892 } else {
893 /*
894 * Not changing to Thread::kRunnable. No additional work required.
895 *
896 * We use a releasing store to ensure that, if we were runnable,
897 * any updates we previously made to objects on the managed heap
898 * will be observed before the state change.
899 */
900 android_atomic_release_store(new_state, addr);
901 }
902
903 return old_state;
904}
905
906void Thread::WaitUntilSuspended() {
907 // TODO: dalvik dropped the waiting thread's priority after a while.
908 // TODO: dalvik timed out and aborted.
909 useconds_t delay = 0;
910 while (GetState() == Thread::kRunnable) {
911 useconds_t new_delay = delay * 2;
912 CHECK_GE(new_delay, delay);
913 delay = new_delay;
914 if (delay == 0) {
915 sched_yield();
916 delay = 10000;
917 } else {
918 usleep(delay);
919 }
920 }
921}
922
Elliott Hughesbe759c62011-09-08 19:38:21 -0700923void Thread::ThreadExitCallback(void* arg) {
924 Thread* self = reinterpret_cast<Thread*>(arg);
925 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700926}
927
Elliott Hughesbe759c62011-09-08 19:38:21 -0700928void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700929 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700930 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700931
932 // Double-check the TLS slot allocation.
933 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700934 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700935 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700936}
Carl Shapirob5573532011-07-12 18:22:59 -0700937
Elliott Hughes038a8062011-09-18 14:12:41 -0700938void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700939 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
940 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
941 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
942 Class* int_class = class_linker->FindPrimitiveClass('I');
943 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
944 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
945 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
946 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
Elliott Hughes29f27422011-09-18 16:02:18 -0700947 Class* UncaughtExceptionHandler_class = class_linker->FindSystemClass("Ljava/lang/Thread$UncaughtExceptionHandler;");
948 gThrowable = class_linker->FindSystemClass("Ljava/lang/Throwable;");
Elliott Hughes038a8062011-09-18 14:12:41 -0700949 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
950 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
951 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
952 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
953 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
954 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
Elliott Hughes29f27422011-09-18 16:02:18 -0700955 gThread_uncaughtHandler = Thread_class->FindDeclaredInstanceField("uncaughtHandler", UncaughtExceptionHandler_class);
Elliott Hughes038a8062011-09-18 14:12:41 -0700956 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
957 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Elliott Hughes29f27422011-09-18 16:02:18 -0700958 gThreadGroup_removeThread = ThreadGroup_class->FindVirtualMethod("removeThread", "(Ljava/lang/Thread;)V");
959 gUncaughtExceptionHandler_uncaughtException =
960 UncaughtExceptionHandler_class->FindVirtualMethod("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700961
962 // Finish attaching the main thread.
963 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700964}
965
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700966void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700967 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700968}
969
Elliott Hughesdcc24742011-09-07 14:02:44 -0700970Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700971 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700972 wait_mutex_(new Mutex("Thread wait mutex")),
973 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700974 wait_monitor_(NULL),
975 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700976 wait_next_(NULL),
977 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700978 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700979 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700980 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700981 native_to_managed_record_(NULL),
982 top_sirt_(NULL),
983 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700984 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700985 self_(NULL),
986 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700987 exception_(NULL),
988 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700989 class_loader_override_(NULL),
990 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700991}
992
Elliott Hughes02b48d12011-09-07 17:15:51 -0700993void MonitorExitVisitor(const Object* object, void*) {
994 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700995 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700996}
997
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700998Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700999 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -07001000 if (jni_env_ != NULL) {
1001 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
1002 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001003
Elliott Hughes93e74e82011-09-13 11:07:03 -07001004 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001005 Object* group = gThread_group->GetObject(peer_);
1006
1007 // Handle any pending exception.
1008 if (IsExceptionPending()) {
1009 // Get and clear the exception.
1010 Object* exception = GetException();
1011 ClearException();
1012
1013 // If the thread has its own handler, use that.
1014 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1015 if (handler == NULL) {
1016 // Otherwise use the thread group's default handler.
1017 handler = group;
1018 }
1019
1020 // Call the handler.
1021 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
1022 Object* args[2];
1023 args[0] = peer_;
1024 args[1] = exception;
1025 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
1026
1027 // If the handler threw, clear that exception too.
1028 ClearException();
1029 }
1030
1031 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -07001032 // group can be null if we're in the compiler or a test.
1033 if (group != NULL) {
1034 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
1035 Object* args = peer_;
1036 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
1037 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001038
1039 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -07001040 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001041
Elliott Hughes29f27422011-09-18 16:02:18 -07001042 // TODO: say "bye" to the debugger.
1043 //if (gDvm.debuggerConnected) {
1044 // dvmDbgPostThreadDeath(self);
1045 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001046
Elliott Hughes29f27422011-09-18 16:02:18 -07001047 // Thread.join() is implemented as an Object.wait() on the Thread.lock
1048 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -07001049 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -07001050 Object* lock = gThread_lock->GetObject(peer_);
1051 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -07001052 if (lock != NULL) {
1053 lock->MonitorEnter(self);
1054 lock->NotifyAll();
1055 lock->MonitorExit(self);
1056 }
1057 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001058
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001059 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001060 jni_env_ = NULL;
1061
1062 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001063
1064 delete wait_cond_;
1065 delete wait_mutex_;
1066
1067 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001068}
1069
Ian Rogers408f79a2011-08-23 18:22:33 -07001070size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001071 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -07001072 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001073 count += cur->NumberOfReferences();
1074 }
1075 return count;
1076}
1077
Ian Rogers408f79a2011-08-23 18:22:33 -07001078bool Thread::SirtContains(jobject obj) {
1079 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1080 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001081 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001082 // A SIRT should always have a jobject/jclass as a native method is passed
1083 // in a this pointer or a class
1084 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001085 if ((&cur->References()[0] <= sirt_entry) &&
1086 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001087 return true;
1088 }
1089 }
1090 return false;
1091}
1092
Ian Rogers67375ac2011-09-14 00:55:44 -07001093void Thread::PopSirt() {
1094 CHECK(top_sirt_ != NULL);
1095 top_sirt_ = top_sirt_->Link();
1096}
1097
Ian Rogers408f79a2011-08-23 18:22:33 -07001098Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001099 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001100 if (obj == NULL) {
1101 return NULL;
1102 }
1103 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1104 IndirectRefKind kind = GetIndirectRefKind(ref);
1105 Object* result;
1106 switch (kind) {
1107 case kLocal:
1108 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001109 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001110 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001111 break;
1112 }
1113 case kGlobal:
1114 {
1115 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1116 IndirectReferenceTable& globals = vm->globals;
1117 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001118 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001119 break;
1120 }
1121 case kWeakGlobal:
1122 {
1123 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1124 IndirectReferenceTable& weak_globals = vm->weak_globals;
1125 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001126 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001127 if (result == kClearedJniWeakGlobal) {
1128 // This is a special case where it's okay to return NULL.
1129 return NULL;
1130 }
1131 break;
1132 }
1133 case kSirtOrInvalid:
1134 default:
1135 // TODO: make stack indirect reference table lookup more efficient
1136 // Check if this is a local reference in the SIRT
1137 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001138 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001139 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001140 // Assume an invalid local reference is actually a direct pointer.
1141 result = reinterpret_cast<Object*>(obj);
1142 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001143 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001144 }
1145 }
1146
1147 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001148 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1149 JniAbort(NULL);
1150 } else {
1151 if (result != kInvalidIndirectRefObject) {
1152 Heap::VerifyObject(result);
1153 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001154 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001155 return result;
1156}
1157
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001158class CountStackDepthVisitor : public Thread::StackVisitor {
1159 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001160 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001161
Elliott Hughes29f27422011-09-18 16:02:18 -07001162 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1163 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001164 // Note we also skip the frame if it doesn't have a method (namely the callee
1165 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001166 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001167 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001168 skipping_ = false;
1169 }
1170 if (!skipping_) {
1171 ++depth_;
1172 } else {
1173 ++skip_depth_;
1174 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001175 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001176
1177 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001178 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001179 }
1180
Elliott Hughes29f27422011-09-18 16:02:18 -07001181 int GetSkipDepth() const {
1182 return skip_depth_;
1183 }
1184
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001185 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001186 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001187 uint32_t skip_depth_;
1188 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001189};
1190
Ian Rogersaaa20802011-09-11 21:47:37 -07001191class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001192 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001193 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1194 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001195 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001196 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001197 // Register a local reference as IntArray::Alloc may trigger GC
1198 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1199 pc_trace_ = IntArray::Alloc(depth);
1200#ifdef MOVING_GARBAGE_COLLECTOR
1201 // Re-read after potential GC
1202 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1203#endif
1204 // Save PC trace in last element of method trace, also places it into the
1205 // object graph.
1206 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001207 }
1208
Ian Rogersaaa20802011-09-11 21:47:37 -07001209 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001210
Ian Rogersbdb03912011-09-14 00:55:44 -07001211 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001212 if (skip_depth_ > 0) {
1213 skip_depth_--;
1214 return;
1215 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001216 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001217 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001218 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001219 }
1220
Ian Rogersaaa20802011-09-11 21:47:37 -07001221 jobject GetInternalStackTrace() const {
1222 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001223 }
1224
1225 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001226 // How many more frames to skip.
1227 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001228 // Current position down stack trace
1229 uint32_t count_;
1230 // Array of return PC values
1231 IntArray* pc_trace_;
1232 // An array of the methods on the stack, the last entry is a reference to the
1233 // PC trace
1234 ObjectArray<Object>* method_trace_;
1235 // Local indirect reference table entry for method trace
1236 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001237};
1238
Ian Rogersaaa20802011-09-11 21:47:37 -07001239void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001240 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001241 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001242 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1243 // CHECK(native_to_managed_record_ != NULL);
1244 NativeToManagedRecord* record = native_to_managed_record_;
1245
Ian Rogersbdb03912011-09-14 00:55:44 -07001246 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001247 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001248 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1249 visitor->VisitFrame(frame, pc);
1250 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001251 }
1252 if (record == NULL) {
1253 break;
1254 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001255 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001256 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001257 pc = record->last_top_of_managed_stack_pc_;
1258 record = record->link_;
1259 }
1260}
1261
Ian Rogers67375ac2011-09-14 00:55:44 -07001262void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001263 Frame frame = GetTopOfStack();
1264 uintptr_t pc = top_of_managed_stack_pc_;
1265
1266 if (frame.GetSP() != 0) {
1267 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001268 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001269 visitor->VisitFrame(frame, pc);
1270 pc = frame.GetReturnPC();
1271 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001272 if (include_upcall) {
1273 visitor->VisitFrame(frame, pc);
1274 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001275 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001276}
1277
Elliott Hughes01158d72011-09-19 19:47:10 -07001278jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001279 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001280 CountStackDepthVisitor count_visitor;
1281 WalkStack(&count_visitor);
1282 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001283 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001284
Ian Rogersaaa20802011-09-11 21:47:37 -07001285 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001286 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001287
1288 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001289 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001290 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001291
Ian Rogersaaa20802011-09-11 21:47:37 -07001292 return build_trace_visitor.GetInternalStackTrace();
1293}
1294
Elliott Hughes01158d72011-09-19 19:47:10 -07001295jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1296 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001297 // Transition into runnable state to work on Object*/Array*
1298 ScopedJniThreadState ts(env);
1299
1300 // Decode the internal stack trace into the depth, method trace and PC trace
1301 ObjectArray<Object>* method_trace =
1302 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1303 int32_t depth = method_trace->GetLength()-1;
1304 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1305
1306 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1307
Elliott Hughes01158d72011-09-19 19:47:10 -07001308 jobjectArray result;
1309 ObjectArray<StackTraceElement>* java_traces;
1310 if (output_array != NULL) {
1311 // Reuse the array we were given.
1312 result = output_array;
1313 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1314 output_array));
1315 // ...adjusting the number of frames we'll write to not exceed the array length.
1316 depth = std::min(depth, java_traces->GetLength());
1317 } else {
1318 // Create java_trace array and place in local reference table
1319 java_traces = class_linker->AllocStackTraceElementArray(depth);
1320 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1321 }
1322
1323 if (stack_depth != NULL) {
1324 *stack_depth = depth;
1325 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001326
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001327 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001328 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1329 Method* method = down_cast<Method*>(method_trace->Get(i));
1330 uint32_t native_pc = pc_trace->Get(i);
1331 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001332 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001333 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001334
Ian Rogersaaa20802011-09-11 21:47:37 -07001335 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001336 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001337 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001338 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001339 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001340 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001341 method->ToDexPC(native_pc)));
1342#ifdef MOVING_GARBAGE_COLLECTOR
1343 // Re-read after potential GC
1344 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1345 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1346 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1347#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001348 java_traces->Set(i, obj);
1349 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001350 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001351}
1352
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001353void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001354 va_list args;
1355 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001356 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001357 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001358}
1359
1360void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1361 std::string msg;
1362 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001363
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001364 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001365 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001366 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001367 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001368 descriptor.erase(descriptor.length() - 1);
1369
1370 JNIEnv* env = GetJniEnv();
1371 jclass exception_class = env->FindClass(descriptor.c_str());
1372 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1373 int rc = env->ThrowNew(exception_class, msg.c_str());
1374 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001375}
1376
Elliott Hughes79082e32011-08-25 12:07:32 -07001377void Thread::ThrowOutOfMemoryError() {
1378 UNIMPLEMENTED(FATAL);
1379}
1380
Ian Rogersbdb03912011-09-14 00:55:44 -07001381class CatchBlockStackVisitor : public Thread::StackVisitor {
1382 public:
1383 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001384 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1385#ifndef NDEBUG
1386 handler_pc_ = 0xEBADC0DE;
1387 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1388#endif
1389 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001390
Ian Rogersbdb03912011-09-14 00:55:44 -07001391 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1392 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001393 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001394 if (method == NULL) {
1395 // This is the upcall, we remember the frame and last_pc so that we may
1396 // long jump to them
1397 handler_pc_ = pc;
1398 handler_frame_ = fr;
1399 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001400 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001401 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001402 if (method->IsPhony()) {
1403 // ignore callee save method
1404 } else if (method->IsNative()) {
1405 native_method_count_++;
1406 } else {
1407 // Move the PC back 2 bytes as a call will frequently terminate the
1408 // decoding of a particular instruction and we want to make sure we
1409 // get the Dex PC of the instruction with the call and not the
1410 // instruction following.
1411 pc -= 2;
1412 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001413 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001414 if (dex_pc != DexFile::kDexNoIndex) {
1415 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1416 if (found_dex_pc != DexFile::kDexNoIndex) {
1417 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001418 handler_pc_ = method->ToNativePC(found_dex_pc);
1419 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001420 }
1421 }
1422 if (!found_) {
1423 // Caller may be handler, fill in callee saves in context
1424 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001425 }
1426 }
1427 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001428
1429 // Did we find a catch block yet?
1430 bool found_;
1431 // The type of the exception catch block to find
1432 Class* to_find_;
1433 // Frame with found handler or last frame if no handler found
1434 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001435 // PC to branch to for the handler
1436 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001437 // Context that will be the target of the long jump
1438 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001439 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1440 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001441};
1442
Ian Rogersff1ed472011-09-20 13:46:24 -07001443void Thread::DeliverException() {
1444 Throwable *exception = GetException(); // Set exception on thread
1445 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001446
1447 Context* long_jump_context = GetLongJumpContext();
1448 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001449 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001450
Ian Rogers67375ac2011-09-14 00:55:44 -07001451 // Pop any SIRT
1452 if (catch_finder.native_method_count_ == 1) {
1453 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001454 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001455 // We only expect the stack crawl to have passed 1 native method as it's terminated
1456 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001457 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001458 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001459 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1460 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001461 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001462}
1463
Ian Rogersbdb03912011-09-14 00:55:44 -07001464Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001465 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001466 if (result == NULL) {
1467 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001468 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001469 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001470 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001471}
1472
Elliott Hughes5f791332011-09-15 17:45:30 -07001473bool Thread::HoldsLock(Object* object) {
1474 if (object == NULL) {
1475 return false;
1476 }
1477 return object->GetLockOwner() == thin_lock_id_;
1478}
1479
Elliott Hughes038a8062011-09-18 14:12:41 -07001480bool Thread::IsDaemon() {
1481 return gThread_daemon->GetBoolean(peer_);
1482}
1483
Elliott Hughes410c0c82011-09-01 17:58:25 -07001484void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001485 if (exception_ != NULL) {
1486 visitor(exception_, arg);
1487 }
1488 if (peer_ != NULL) {
1489 visitor(peer_, arg);
1490 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001491 jni_env_->locals.VisitRoots(visitor, arg);
1492 jni_env_->monitors.VisitRoots(visitor, arg);
1493 // visitThreadStack(visitor, thread, arg);
1494 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1495}
1496
Ian Rogersb033c752011-07-20 12:22:35 -07001497static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001498 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001499 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001500 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001501 "Blocked",
1502 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001503 "Initializing",
1504 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001505 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001506 "VmWait",
1507 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001508};
1509std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001510 int int_state = static_cast<int>(state);
1511 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1512 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001513 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001514 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001515 }
1516 return os;
1517}
1518
Elliott Hughes330304d2011-08-12 14:28:05 -07001519std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1520 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001521 << ",pthread_t=" << thread.GetImpl()
1522 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001523 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001524 << ",state=" << thread.GetState()
1525 << ",peer=" << thread.GetPeer()
1526 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001527 return os;
1528}
1529
Elliott Hughes8daa0922011-09-11 13:46:25 -07001530} // namespace art