thread.cc revision 40381fb9dc4b4cf274f1e58b2cdf4396202c6189
1/*
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 */
16
17#include "thread.h"
18
19#include <dynamic_annotations.h>
20#include <pthread.h>
21#include <sys/mman.h>
22
23#include <algorithm>
24#include <bitset>
25#include <cerrno>
26#include <iostream>
27#include <list>
28
29#include "class_linker.h"
30#include "class_loader.h"
31#include "context.h"
32#include "dex_verifier.h"
33#include "heap.h"
34#include "jni_internal.h"
35#include "monitor.h"
36#include "object.h"
37#include "runtime.h"
38#include "runtime_support.h"
39#include "ScopedLocalRef.h"
40#include "scoped_jni_thread_state.h"
41#include "stack.h"
42#include "stack_indirect_reference_table.h"
43#include "thread_list.h"
44#include "utils.h"
45
46namespace art {
47
48pthread_key_t Thread::pthread_key_self_;
49
50static Class* gThreadLock = NULL;
51static Class* gThrowable = NULL;
52static Field* gThread_daemon = NULL;
53static Field* gThread_group = NULL;
54static Field* gThread_lock = NULL;
55static Field* gThread_name = NULL;
56static Field* gThread_priority = NULL;
57static Field* gThread_uncaughtHandler = NULL;
58static Field* gThread_vmData = NULL;
59static Field* gThreadGroup_name = NULL;
60static Field* gThreadLock_thread = NULL;
61static Method* gThread_run = NULL;
62static Method* gThreadGroup_removeThread = NULL;
63static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
64
65void Thread::InitFunctionPointers() {
66#if defined(__arm__)
67  pShlLong = art_shl_long;
68  pShrLong = art_shr_long;
69  pUshrLong = art_ushr_long;
70  pIdiv = __aeabi_idiv;
71  pIdivmod = __aeabi_idivmod;
72  pI2f = __aeabi_i2f;
73  pF2iz = __aeabi_f2iz;
74  pD2f = __aeabi_d2f;
75  pF2d = __aeabi_f2d;
76  pD2iz = __aeabi_d2iz;
77  pL2f = __aeabi_l2f;
78  pL2d = __aeabi_l2d;
79  pFadd = __aeabi_fadd;
80  pFsub = __aeabi_fsub;
81  pFdiv = __aeabi_fdiv;
82  pFmul = __aeabi_fmul;
83  pFmodf = fmodf;
84  pDadd = __aeabi_dadd;
85  pDsub = __aeabi_dsub;
86  pDdiv = __aeabi_ddiv;
87  pDmul = __aeabi_dmul;
88  pFmod = fmod;
89  pLdivmod = __aeabi_ldivmod;
90  pLmul = __aeabi_lmul;
91  pAllocArrayFromCode = art_alloc_array_from_code;
92  pAllocObjectFromCode = art_alloc_object_from_code;
93  pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
94  pCheckAndAllocArrayFromCode = art_check_and_alloc_array_from_code;
95  pCheckCastFromCode = art_check_cast_from_code;
96  pFindInstanceFieldFromCode = art_find_instance_field_from_code;
97  pGet32Static = art_get32_static_from_code;
98  pGet64Static = art_get64_static_from_code;
99  pGetObjStatic = art_get_obj_static_from_code;
100  pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
101  pInitializeStaticStorage = art_initialize_static_storage_from_code;
102  pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
103  pLockObjectFromCode = art_lock_object_from_code;
104  pObjectInit = art_object_init_from_code;
105  pResolveStringFromCode = art_resolve_string_from_code;
106  pSet32Static = art_set32_static_from_code;
107  pSet64Static = art_set64_static_from_code;
108  pSetObjStatic = art_set_obj_static_from_code;
109  pTestSuspendFromCode = art_test_suspend;
110  pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
111  pThrowDivZeroFromCode = art_throw_div_zero_from_code;
112  pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
113  pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
114  pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
115  pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
116  pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
117  pUnlockObjectFromCode = art_unlock_object_from_code;
118#endif
119  pF2l = F2L;
120  pD2l = D2L;
121  pMemcpy = memcpy;
122  pCheckSuspendFromCode = CheckSuspendFromCode;
123  pDebugMe = DebugMe;
124  pDecodeJObjectInThread = DecodeJObjectInThread;
125  pDeliverException = art_deliver_exception_from_code;
126  pFindNativeMethod = FindNativeMethod;
127  pInitializeTypeFromCode = InitializeTypeFromCode;
128  pInstanceofNonTrivialFromCode = IsAssignableFromCode;
129  pResolveMethodFromCode = ResolveMethodFromCode;
130  pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
131  pUnresolvedDirectMethodTrampolineFromCode = UnresolvedDirectMethodTrampolineFromCode;
132}
133
134void Thread::InitTid() {
135  tid_ = ::art::GetTid();
136}
137
138void Thread::InitAfterFork() {
139  InitTid();
140#if defined(__BIONIC__)
141  // Work around a bionic bug.
142  struct bionic_pthread_internal_t {
143    void*  next;
144    void** pref;
145    pthread_attr_t attr;
146    pid_t kernel_id;
147    // et cetera. we just need 'kernel_id' so we can stop here.
148  };
149  reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
150#endif
151}
152
153void* Thread::CreateCallback(void* arg) {
154  Thread* self = reinterpret_cast<Thread*>(arg);
155  Runtime* runtime = Runtime::Current();
156
157  self->Attach(runtime);
158
159  String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
160  if (thread_name != NULL) {
161    SetThreadName(thread_name->ToModifiedUtf8().c_str());
162  }
163
164  // Wait until it's safe to start running code. (There may have been a suspend-all
165  // in progress while we were starting up.)
166  runtime->GetThreadList()->WaitForGo();
167
168  // TODO: say "hi" to the debugger.
169  //if (gDvm.debuggerConnected) {
170  //  dvmDbgPostThreadStart(self);
171  //}
172
173  // Invoke the 'run' method of our java.lang.Thread.
174  CHECK(self->peer_ != NULL);
175  Object* receiver = self->peer_;
176  Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
177  m->Invoke(self, receiver, NULL, NULL);
178
179  // Detach.
180  runtime->GetThreadList()->Unregister();
181
182  return NULL;
183}
184
185void SetVmData(Object* managed_thread, Thread* native_thread) {
186  gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
187}
188
189Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
190  Object* thread = Decode<Object*>(env, java_thread);
191  return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
192}
193
194size_t FixStackSize(size_t stack_size) {
195  // A stack size of zero means "use the default".
196  if (stack_size == 0) {
197    stack_size = Runtime::Current()->GetDefaultStackSize();
198  }
199
200  // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
201  if (stack_size < PTHREAD_STACK_MIN) {
202    stack_size = PTHREAD_STACK_MIN;
203  }
204
205  // It's likely that callers are trying to ensure they have at least a certain amount of
206  // stack space, so we should add our reserved space on top of what they requested, rather
207  // than implicitly take it away from them.
208  stack_size += Thread::kStackOverflowReservedBytes;
209
210  // Some systems require the stack size to be a multiple of the system page size, so round up.
211  stack_size = RoundUp(stack_size, kPageSize);
212
213  return stack_size;
214}
215
216void Thread::Create(Object* peer, size_t stack_size) {
217  CHECK(peer != NULL);
218
219  stack_size = FixStackSize(stack_size);
220
221  Thread* native_thread = new Thread;
222  native_thread->peer_ = peer;
223
224  // Thread.start is synchronized, so we know that vmData is 0,
225  // and know that we're not racing to assign it.
226  SetVmData(peer, native_thread);
227
228  pthread_t new_pthread;
229  pthread_attr_t attr;
230  CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
231  CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
232  CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
233  CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
234  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
235
236  // Let the child know when it's safe to start running.
237  Runtime::Current()->GetThreadList()->SignalGo(native_thread);
238}
239
240void Thread::Attach(const Runtime* runtime) {
241  InitCpu();
242  InitFunctionPointers();
243
244  thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
245
246  InitTid();
247  InitStackHwm();
248
249  CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
250
251  jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
252
253  runtime->GetThreadList()->Register();
254}
255
256Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
257  Thread* self = new Thread;
258  self->Attach(runtime);
259
260  self->SetState(Thread::kNative);
261
262  SetThreadName(name);
263
264  // If we're the main thread, ClassLinker won't be created until after we're attached,
265  // so that thread needs a two-stage attach. Regular threads don't need this hack.
266  if (self->thin_lock_id_ != ThreadList::kMainId) {
267    self->CreatePeer(name, as_daemon);
268  }
269
270  self->GetJniEnv()->locals.AssertEmpty();
271
272  return self;
273}
274
275jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
276  ScopedLocalRef<jclass> thread_group_class(env, env->FindClass("java/lang/ThreadGroup"));
277  jfieldID fid = env->GetStaticFieldID(thread_group_class.get(), field_name, "Ljava/lang/ThreadGroup;");
278  return env->GetStaticObjectField(thread_group_class.get(), fid);
279}
280
281void Thread::CreatePeer(const char* name, bool as_daemon) {
282  JNIEnv* env = jni_env_;
283
284  const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
285  ScopedLocalRef<jobject> thread_group(env, GetWellKnownThreadGroup(env, field_name));
286  ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
287  jint thread_priority = GetNativePriority();
288  jboolean thread_is_daemon = as_daemon;
289
290  ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
291  jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
292
293  ScopedLocalRef<jobject> peer(env,
294      env->NewObject(c.get(), mid, thread_group.get(), thread_name.get(), thread_priority, thread_is_daemon));
295  peer_ = DecodeJObject(peer.get());
296  SetVmData(peer_, Thread::Current());
297
298  // Because we mostly run without code available (in the compiler, in tests), we
299  // manually assign the fields the constructor should have set.
300  // TODO: lose this.
301  gThread_daemon->SetBoolean(peer_, thread_is_daemon);
302  gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group.get()));
303  gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
304  gThread_priority->SetInt(peer_, thread_priority);
305
306  // Pre-allocate an OutOfMemoryError for the double-OOME case.
307  ThrowNewException("Ljava/lang/OutOfMemoryError;",
308      "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
309  ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
310  env->ExceptionClear();
311  pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
312}
313
314void Thread::InitStackHwm() {
315  pthread_attr_t attributes;
316  CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
317
318  void* temp_stack_base;
319  CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
320                     __FUNCTION__);
321  stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
322
323  if (stack_size_ <= kStackOverflowReservedBytes) {
324    LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
325  }
326
327  // Set stack_end_ to the bottom of the stack saving space of stack overflows
328  ResetDefaultStackEnd();
329
330  // Sanity check.
331  int stack_variable;
332  CHECK_GT(&stack_variable, (void*) stack_end_);
333
334  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
335}
336
337void Thread::Dump(std::ostream& os) const {
338  DumpState(os);
339  DumpStack(os);
340}
341
342std::string GetSchedulerGroup(pid_t tid) {
343  // /proc/<pid>/group looks like this:
344  // 2:devices:/
345  // 1:cpuacct,cpu:/
346  // We want the third field from the line whose second field contains the "cpu" token.
347  std::string cgroup_file;
348  if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
349    return "";
350  }
351  std::vector<std::string> cgroup_lines;
352  Split(cgroup_file, '\n', cgroup_lines);
353  for (size_t i = 0; i < cgroup_lines.size(); ++i) {
354    std::vector<std::string> cgroup_fields;
355    Split(cgroup_lines[i], ':', cgroup_fields);
356    std::vector<std::string> cgroups;
357    Split(cgroup_fields[1], ',', cgroups);
358    for (size_t i = 0; i < cgroups.size(); ++i) {
359      if (cgroups[i] == "cpu") {
360        return cgroup_fields[2].substr(1); // Skip the leading slash.
361      }
362    }
363  }
364  return "";
365}
366
367String* Thread::GetName() const {
368  return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
369}
370
371void Thread::DumpState(std::ostream& os) const {
372  std::string thread_name("<native thread without managed peer>");
373  std::string group_name;
374  int priority;
375  bool is_daemon = false;
376
377  if (peer_ != NULL) {
378    String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
379    thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
380    priority = gThread_priority->GetInt(peer_);
381    is_daemon = gThread_daemon->GetBoolean(peer_);
382
383    Object* thread_group = gThread_group->GetObject(peer_);
384    if (thread_group != NULL) {
385      String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
386      group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
387    }
388  } else {
389    // This name may be truncated, but it's the best we can do in the absence of a managed peer.
390    std::string stats;
391    if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
392      size_t start = stats.find('(') + 1;
393      size_t end = stats.find(')') - start;
394      thread_name = stats.substr(start, end);
395    }
396    priority = GetNativePriority();
397  }
398
399  int policy;
400  sched_param sp;
401  CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
402
403  std::string scheduler_group(GetSchedulerGroup(GetTid()));
404  if (scheduler_group.empty()) {
405    scheduler_group = "default";
406  }
407
408  os << '"' << thread_name << '"';
409  if (is_daemon) {
410    os << " daemon";
411  }
412  os << " prio=" << priority
413     << " tid=" << GetThinLockId()
414     << " " << GetState() << "\n";
415
416  int debug_suspend_count = 0; // TODO
417  os << "  | group=\"" << group_name << "\""
418     << " sCount=" << suspend_count_
419     << " dsCount=" << debug_suspend_count
420     << " obj=" << reinterpret_cast<void*>(peer_)
421     << " self=" << reinterpret_cast<const void*>(this) << "\n";
422  os << "  | sysTid=" << GetTid()
423     << " nice=" << getpriority(PRIO_PROCESS, GetTid())
424     << " sched=" << policy << "/" << sp.sched_priority
425     << " cgrp=" << scheduler_group
426     << " handle=" << pthread_self() << "\n";
427
428  // Grab the scheduler stats for this thread.
429  std::string scheduler_stats;
430  if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
431    scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
432  } else {
433    scheduler_stats = "0 0 0";
434  }
435
436  int utime = 0;
437  int stime = 0;
438  int task_cpu = 0;
439  std::string stats;
440  if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
441    // Skip the command, which may contain spaces.
442    stats = stats.substr(stats.find(')') + 2);
443    // Extract the three fields we care about.
444    std::vector<std::string> fields;
445    Split(stats, ' ', fields);
446    utime = strtoull(fields[11].c_str(), NULL, 10);
447    stime = strtoull(fields[12].c_str(), NULL, 10);
448    task_cpu = strtoull(fields[36].c_str(), NULL, 10);
449  }
450
451  os << "  | schedstat=( " << scheduler_stats << " )"
452     << " utm=" << utime
453     << " stm=" << stime
454     << " core=" << task_cpu
455     << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
456}
457
458void Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
459  Method **sp = top_of_managed_stack_.GetSP();
460#ifndef NDEBUG
461  if (sp != NULL) {
462    Method* m = *sp;
463    Heap::VerifyObject(m);
464    DCHECK((m == NULL) || m->IsMethod());
465  }
466#endif
467  record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
468  record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
469  record->link_ = native_to_managed_record_;
470  native_to_managed_record_ = record;
471  top_of_managed_stack_.SetSP(NULL);
472}
473
474void Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
475  native_to_managed_record_ = record.link_;
476  top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
477  top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
478}
479
480struct StackDumpVisitor : public Thread::StackVisitor {
481  StackDumpVisitor(std::ostream& os, const Thread* thread)
482      : os(os), thread(thread), frame_count(0) {
483  }
484
485  virtual ~StackDumpVisitor() {
486  }
487
488  void VisitFrame(const Frame& frame, uintptr_t pc) {
489    if (!frame.HasMethod()) {
490      return;
491    }
492
493    Method* m = frame.GetMethod();
494    Class* c = m->GetDeclaringClass();
495    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
496    const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
497
498    os << "  at " << PrettyMethod(m, false);
499    if (m->IsNative()) {
500      os << "(Native method)";
501    } else {
502      int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
503      os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
504    }
505    os << "\n";
506
507    if (frame_count++ == 0) {
508      Monitor::DescribeWait(os, thread);
509    }
510  }
511
512  std::ostream& os;
513  const Thread* thread;
514  int frame_count;
515};
516
517void Thread::DumpStack(std::ostream& os) const {
518  StackDumpVisitor dumper(os, this);
519  WalkStack(&dumper);
520}
521
522Thread::State Thread::SetState(Thread::State new_state) {
523  Thread::State old_state = state_;
524  if (old_state == new_state) {
525    return old_state;
526  }
527
528  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
529  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
530
531  if (new_state == Thread::kRunnable) {
532    /*
533     * Change our status to Thread::kRunnable.  The transition requires
534     * that we check for pending suspension, because the VM considers
535     * us to be "asleep" in all other states, and another thread could
536     * be performing a GC now.
537     *
538     * The order of operations is very significant here.  One way to
539     * do this wrong is:
540     *
541     *   GCing thread                   Our thread (in kNative)
542     *   ------------                   ----------------------
543     *                                  check suspend count (== 0)
544     *   SuspendAllThreads()
545     *   grab suspend-count lock
546     *   increment all suspend counts
547     *   release suspend-count lock
548     *   check thread state (== kNative)
549     *   all are suspended, begin GC
550     *                                  set state to kRunnable
551     *                                  (continue executing)
552     *
553     * We can correct this by grabbing the suspend-count lock and
554     * performing both of our operations (check suspend count, set
555     * state) while holding it, now we need to grab a mutex on every
556     * transition to kRunnable.
557     *
558     * What we do instead is change the order of operations so that
559     * the transition to kRunnable happens first.  If we then detect
560     * that the suspend count is nonzero, we switch to kSuspended.
561     *
562     * Appropriate compiler and memory barriers are required to ensure
563     * that the operations are observed in the expected order.
564     *
565     * This does create a small window of opportunity where a GC in
566     * progress could observe what appears to be a running thread (if
567     * it happens to look between when we set to kRunnable and when we
568     * switch to kSuspended).  At worst this only affects assertions
569     * and thread logging.  (We could work around it with some sort
570     * of intermediate "pre-running" state that is generally treated
571     * as equivalent to running, but that doesn't seem worthwhile.)
572     *
573     * We can also solve this by combining the "status" and "suspend
574     * count" fields into a single 32-bit value.  This trades the
575     * store/load barrier on transition to kRunnable for an atomic RMW
576     * op on all transitions and all suspend count updates (also, all
577     * accesses to status or the thread count require bit-fiddling).
578     * It also eliminates the brief transition through kRunnable when
579     * the thread is supposed to be suspended.  This is possibly faster
580     * on SMP and slightly more correct, but less convenient.
581     */
582    android_atomic_acquire_store(new_state, addr);
583    if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
584      Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
585    }
586  } else {
587    /*
588     * Not changing to Thread::kRunnable. No additional work required.
589     *
590     * We use a releasing store to ensure that, if we were runnable,
591     * any updates we previously made to objects on the managed heap
592     * will be observed before the state change.
593     */
594    android_atomic_release_store(new_state, addr);
595  }
596
597  return old_state;
598}
599
600void Thread::WaitUntilSuspended() {
601  // TODO: dalvik dropped the waiting thread's priority after a while.
602  // TODO: dalvik timed out and aborted.
603  useconds_t delay = 0;
604  while (GetState() == Thread::kRunnable) {
605    useconds_t new_delay = delay * 2;
606    CHECK_GE(new_delay, delay);
607    delay = new_delay;
608    if (delay == 0) {
609      sched_yield();
610      delay = 10000;
611    } else {
612      usleep(delay);
613    }
614  }
615}
616
617void Thread::ThreadExitCallback(void* arg) {
618  Thread* self = reinterpret_cast<Thread*>(arg);
619  LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
620}
621
622void Thread::Startup() {
623  // Allocate a TLS slot.
624  CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
625
626  // Double-check the TLS slot allocation.
627  if (pthread_getspecific(pthread_key_self_) != NULL) {
628    LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
629  }
630}
631
632// TODO: make more accessible?
633Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
634  Class* c = class_linker->FindPrimitiveClass(descriptor);
635  CHECK(c != NULL) << descriptor;
636  return c;
637}
638
639// TODO: make more accessible?
640Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
641  Class* c = class_linker->FindSystemClass(descriptor);
642  CHECK(c != NULL) << descriptor;
643  return c;
644}
645
646// TODO: make more accessible?
647Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
648  Field* f = c->FindDeclaredInstanceField(name, type);
649  CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
650  return f;
651}
652
653// TODO: make more accessible?
654Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
655  Method* m = c->FindVirtualMethod(name, signature);
656  CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
657  return m;
658}
659
660void Thread::FinishStartup() {
661  // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
662  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
663
664  Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
665  Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
666  Class* ClassLoader_class = FindClassOrDie(class_linker, "Ljava/lang/ClassLoader;");
667  Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
668  Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
669  Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
670  Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
671  gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
672  gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
673
674  gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
675  gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
676  gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
677  gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
678  gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
679  gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
680  gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
681  gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
682  gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
683
684  gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
685  gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
686  gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
687      "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
688
689  // Finish attaching the main thread.
690  Thread* self = Thread::Current();
691  self->CreatePeer("main", false);
692
693  const Field* Thread_contextClassLoader = FindFieldOrDie(Thread_class , "contextClassLoader", ClassLoader_class);
694  Thread_contextClassLoader->SetObject(self->GetPeer(), self->GetClassLoaderOverride());
695}
696
697void Thread::Shutdown() {
698  CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
699}
700
701uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
702  if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
703    return ThreadList::kInvalidId;
704  }
705  Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
706  if (managed_thread == NULL) {
707    return ThreadList::kInvalidId;
708  }
709  uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
710  Thread* thread = reinterpret_cast<Thread*>(vmData);
711  if (thread == NULL) {
712    return ThreadList::kInvalidId;
713  }
714  return thread->GetThinLockId();
715}
716
717Thread::Thread()
718    : peer_(NULL),
719      top_of_managed_stack_(),
720      top_of_managed_stack_pc_(0),
721      wait_mutex_(new Mutex("Thread wait mutex")),
722      wait_cond_(new ConditionVariable("Thread wait condition variable")),
723      wait_monitor_(NULL),
724      interrupted_(false),
725      wait_next_(NULL),
726      monitor_enter_object_(NULL),
727      card_table_(0),
728      stack_end_(NULL),
729      native_to_managed_record_(NULL),
730      top_sirt_(NULL),
731      jni_env_(NULL),
732      state_(Thread::kNative),
733      self_(NULL),
734      runtime_(NULL),
735      exception_(NULL),
736      suspend_count_(0),
737      class_loader_override_(NULL),
738      long_jump_context_(NULL),
739      throwing_OutOfMemoryError_(false),
740      pre_allocated_OutOfMemoryError_(NULL) {
741  CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
742}
743
744void MonitorExitVisitor(const Object* object, void*) {
745  Object* entered_monitor = const_cast<Object*>(object);
746  entered_monitor->MonitorExit(Thread::Current());
747}
748
749Thread::~Thread() {
750  SetState(Thread::kRunnable);
751
752  // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
753  if (jni_env_ != NULL) {
754    jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
755  }
756
757  if (peer_ != NULL) {
758    // this.group.removeThread(this);
759    // group can be null if we're in the compiler or a test.
760    Object* group = gThread_group->GetObject(peer_);
761    if (group != NULL) {
762      Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
763      Object* args = peer_;
764      m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
765    }
766
767    // this.vmData = 0;
768    SetVmData(peer_, NULL);
769
770    // TODO: say "bye" to the debugger.
771    //if (gDvm.debuggerConnected) {
772    //  dvmDbgPostThreadDeath(self);
773    //}
774
775    // Thread.join() is implemented as an Object.wait() on the Thread.lock
776    // object. Signal anyone who is waiting.
777    Thread* self = Thread::Current();
778    Object* lock = gThread_lock->GetObject(peer_);
779    // (This conditional is only needed for tests, where Thread.lock won't have been set.)
780    if (lock != NULL) {
781      lock->MonitorEnter(self);
782      lock->NotifyAll();
783      lock->MonitorExit(self);
784    }
785  }
786
787  delete jni_env_;
788  jni_env_ = NULL;
789
790  SetState(Thread::kTerminated);
791
792  delete wait_cond_;
793  delete wait_mutex_;
794
795  delete long_jump_context_;
796}
797
798void Thread::HandleUncaughtExceptions() {
799  if (!IsExceptionPending()) {
800    return;
801  }
802
803  ScopedThreadStateChange tsc(this, Thread::kRunnable);
804
805  // Get and clear the exception.
806  Object* exception = GetException();
807  ClearException();
808
809  // If the thread has its own handler, use that.
810  Object* handler = gThread_uncaughtHandler->GetObject(peer_);
811  if (handler == NULL) {
812    // Otherwise use the thread group's default handler.
813    handler = gThread_group->GetObject(peer_);
814  }
815
816  // Call the handler.
817  Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
818  Object* args[2];
819  args[0] = peer_;
820  args[1] = exception;
821  m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
822
823  // If the handler threw, clear that exception too.
824  ClearException();
825}
826
827size_t Thread::NumSirtReferences() {
828  size_t count = 0;
829  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
830    count += cur->NumberOfReferences();
831  }
832  return count;
833}
834
835bool Thread::SirtContains(jobject obj) {
836  Object** sirt_entry = reinterpret_cast<Object**>(obj);
837  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
838    if (cur->Contains(sirt_entry)) {
839      return true;
840    }
841  }
842  return false;
843}
844
845void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
846  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
847    size_t num_refs = cur->NumberOfReferences();
848    for (size_t j = 0; j < num_refs; j++) {
849      Object* object = cur->GetReference(j);
850      if (object != NULL) {
851        visitor(object, arg);
852      }
853    }
854  }
855}
856
857Object* Thread::DecodeJObject(jobject obj) {
858  DCHECK(CanAccessDirectReferences());
859  if (obj == NULL) {
860    return NULL;
861  }
862  IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
863  IndirectRefKind kind = GetIndirectRefKind(ref);
864  Object* result;
865  switch (kind) {
866  case kLocal:
867    {
868      IndirectReferenceTable& locals = jni_env_->locals;
869      result = const_cast<Object*>(locals.Get(ref));
870      break;
871    }
872  case kGlobal:
873    {
874      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
875      IndirectReferenceTable& globals = vm->globals;
876      MutexLock mu(vm->globals_lock);
877      result = const_cast<Object*>(globals.Get(ref));
878      break;
879    }
880  case kWeakGlobal:
881    {
882      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
883      IndirectReferenceTable& weak_globals = vm->weak_globals;
884      MutexLock mu(vm->weak_globals_lock);
885      result = const_cast<Object*>(weak_globals.Get(ref));
886      if (result == kClearedJniWeakGlobal) {
887        // This is a special case where it's okay to return NULL.
888        return NULL;
889      }
890      break;
891    }
892  case kSirtOrInvalid:
893  default:
894    // TODO: make stack indirect reference table lookup more efficient
895    // Check if this is a local reference in the SIRT
896    if (SirtContains(obj)) {
897      result = *reinterpret_cast<Object**>(obj);  // Read from SIRT
898    } else if (jni_env_->work_around_app_jni_bugs) {
899      // Assume an invalid local reference is actually a direct pointer.
900      result = reinterpret_cast<Object*>(obj);
901    } else {
902      result = kInvalidIndirectRefObject;
903    }
904  }
905
906  if (result == NULL) {
907    LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
908    JniAbort(NULL);
909  } else {
910    if (result != kInvalidIndirectRefObject) {
911      Heap::VerifyObject(result);
912    }
913  }
914  return result;
915}
916
917class CountStackDepthVisitor : public Thread::StackVisitor {
918 public:
919  CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
920
921  virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
922    // We want to skip frames up to and including the exception's constructor.
923    // Note we also skip the frame if it doesn't have a method (namely the callee
924    // save frame)
925    DCHECK(gThrowable != NULL);
926    if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
927      skipping_ = false;
928    }
929    if (!skipping_) {
930      ++depth_;
931    } else {
932      ++skip_depth_;
933    }
934  }
935
936  int GetDepth() const {
937    return depth_;
938  }
939
940  int GetSkipDepth() const {
941    return skip_depth_;
942  }
943
944 private:
945  uint32_t depth_;
946  uint32_t skip_depth_;
947  bool skipping_;
948};
949
950class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
951 public:
952  explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
953      : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
954    // Allocate method trace with an extra slot that will hold the PC trace
955    method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
956    if (method_trace_ == NULL) {
957      return;
958    }
959    // Register a local reference as IntArray::Alloc may trigger GC
960    local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
961    pc_trace_ = IntArray::Alloc(depth);
962    if (pc_trace_ == NULL) {
963      return;
964    }
965#ifdef MOVING_GARBAGE_COLLECTOR
966    // Re-read after potential GC
967    method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
968#endif
969    // Save PC trace in last element of method trace, also places it into the
970    // object graph.
971    method_trace_->Set(depth, pc_trace_);
972  }
973
974  virtual ~BuildInternalStackTraceVisitor() {}
975
976  virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
977    if (method_trace_ == NULL || pc_trace_ == NULL) {
978      return; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
979    }
980    if (skip_depth_ > 0) {
981      skip_depth_--;
982      return;
983    }
984    method_trace_->Set(count_, frame.GetMethod());
985    pc_trace_->Set(count_, pc);
986    ++count_;
987  }
988
989  jobject GetInternalStackTrace() const {
990    return local_ref_;
991  }
992
993 private:
994  // How many more frames to skip.
995  int32_t skip_depth_;
996  // Current position down stack trace
997  uint32_t count_;
998  // Array of return PC values
999  IntArray* pc_trace_;
1000  // An array of the methods on the stack, the last entry is a reference to the
1001  // PC trace
1002  ObjectArray<Object>* method_trace_;
1003  // Local indirect reference table entry for method trace
1004  jobject local_ref_;
1005};
1006
1007// TODO: remove this.
1008uintptr_t ManglePc(uintptr_t pc) {
1009  // Move the PC back 2 bytes as a call will frequently terminate the
1010  // decoding of a particular instruction and we want to make sure we
1011  // get the Dex PC of the instruction with the call and not the
1012  // instruction following.
1013  if (pc > 0) { pc -= 2; }
1014  return pc;
1015}
1016
1017// TODO: remove this.
1018uintptr_t DemanglePc(uintptr_t pc) {
1019  // Revert mangling for the case where we need the PC to return to the upcall
1020  return pc + 2;
1021}
1022
1023void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1024  sirt->SetLink(top_sirt_);
1025  top_sirt_ = sirt;
1026}
1027
1028StackIndirectReferenceTable* Thread::PopSirt() {
1029  CHECK(top_sirt_ != NULL);
1030  StackIndirectReferenceTable* sirt = top_sirt_;
1031  top_sirt_ = top_sirt_->GetLink();
1032  return sirt;
1033}
1034
1035void Thread::WalkStack(StackVisitor* visitor) const {
1036  Frame frame = GetTopOfStack();
1037  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1038  // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1039  // CHECK(native_to_managed_record_ != NULL);
1040  NativeToManagedRecord* record = native_to_managed_record_;
1041
1042  while (frame.GetSP() != 0) {
1043    for ( ; frame.GetMethod() != 0; frame.Next()) {
1044      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
1045      visitor->VisitFrame(frame, pc);
1046      pc = ManglePc(frame.GetReturnPC());
1047    }
1048    if (record == NULL) {
1049      break;
1050    }
1051    // last_tos should return Frame instead of sp?
1052    frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
1053    pc = ManglePc(record->last_top_of_managed_stack_pc_);
1054    record = record->link_;
1055  }
1056}
1057
1058void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
1059  Frame frame = GetTopOfStack();
1060  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1061
1062  if (frame.GetSP() != 0) {
1063    for ( ; frame.GetMethod() != 0; frame.Next()) {
1064      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
1065      visitor->VisitFrame(frame, pc);
1066      pc = ManglePc(frame.GetReturnPC());
1067    }
1068    if (include_upcall) {
1069      visitor->VisitFrame(frame, pc);
1070    }
1071  }
1072}
1073
1074jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
1075  // Compute depth of stack
1076  CountStackDepthVisitor count_visitor;
1077  WalkStack(&count_visitor);
1078  int32_t depth = count_visitor.GetDepth();
1079  int32_t skip_depth = count_visitor.GetSkipDepth();
1080
1081  // Transition into runnable state to work on Object*/Array*
1082  ScopedJniThreadState ts(env);
1083
1084  // Build internal stack trace
1085  BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
1086  WalkStack(&build_trace_visitor);
1087
1088  return build_trace_visitor.GetInternalStackTrace();
1089}
1090
1091jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1092    jobjectArray output_array, int* stack_depth) {
1093  // Transition into runnable state to work on Object*/Array*
1094  ScopedJniThreadState ts(env);
1095
1096  // Decode the internal stack trace into the depth, method trace and PC trace
1097  ObjectArray<Object>* method_trace =
1098      down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1099  int32_t depth = method_trace->GetLength()-1;
1100  IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1101
1102  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1103
1104  jobjectArray result;
1105  ObjectArray<StackTraceElement>* java_traces;
1106  if (output_array != NULL) {
1107    // Reuse the array we were given.
1108    result = output_array;
1109    java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1110        output_array));
1111    // ...adjusting the number of frames we'll write to not exceed the array length.
1112    depth = std::min(depth, java_traces->GetLength());
1113  } else {
1114    // Create java_trace array and place in local reference table
1115    java_traces = class_linker->AllocStackTraceElementArray(depth);
1116    if (java_traces == NULL) {
1117      return NULL;
1118    }
1119    result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1120  }
1121
1122  if (stack_depth != NULL) {
1123    *stack_depth = depth;
1124  }
1125
1126  for (int32_t i = 0; i < depth; ++i) {
1127    // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1128    Method* method = down_cast<Method*>(method_trace->Get(i));
1129    uint32_t native_pc = pc_trace->Get(i);
1130    Class* klass = method->GetDeclaringClass();
1131    std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
1132    int32_t line_number = -1;
1133    DexCache* dex_cache = klass->GetDexCache();
1134    if (dex_cache != NULL) {
1135      const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1136      line_number = dex_file.GetLineNumFromPC(method, method->ToDexPC(native_pc));
1137    }
1138    // Allocate element, potentially triggering GC
1139    // TODO: reuse class_name_object via Class::name_?
1140    SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1141    if (class_name_object.get() == NULL) {
1142      return NULL;
1143    }
1144    StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
1145                                                      method->GetName(),
1146                                                      klass->GetSourceFile(),
1147                                                      line_number);
1148    if (obj == NULL) {
1149      return NULL;
1150    }
1151#ifdef MOVING_GARBAGE_COLLECTOR
1152    // Re-read after potential GC
1153    java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1154    method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1155    pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1156#endif
1157    java_traces->Set(i, obj);
1158  }
1159  return result;
1160}
1161
1162void Thread::GetCurrentLocation(const char*& source_file, uint32_t& line_number) const {
1163  Frame f = top_of_managed_stack_;
1164  Method* m = f.GetMethod();
1165  // TODO: can this ever happen?
1166  if (m->IsCalleeSaveMethod()) {
1167    f.Next();
1168    m = f.GetMethod();
1169  }
1170
1171  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1172  Class* c = m->GetDeclaringClass();
1173  DexCache* dex_cache = c->GetDexCache();
1174  const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1175  const DexFile::ClassDef* class_def = dex_file.FindClassDef(c->GetDescriptor()->ToModifiedUtf8());
1176
1177  source_file = dex_file.dexGetSourceFile(*class_def);
1178
1179  uint32_t pc = ManglePc(f.GetReturnPC());
1180  line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1181}
1182
1183void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1184  va_list args;
1185  va_start(args, fmt);
1186  ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1187  va_end(args);
1188}
1189
1190void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1191  std::string msg;
1192  StringAppendV(&msg, fmt, ap);
1193  ThrowNewException(exception_class_descriptor, msg.c_str());
1194}
1195
1196void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
1197  // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
1198  CHECK_EQ('L', exception_class_descriptor[0]);
1199  std::string descriptor(exception_class_descriptor + 1);
1200  CHECK_EQ(';', descriptor[descriptor.length() - 1]);
1201  descriptor.erase(descriptor.length() - 1);
1202
1203  JNIEnv* env = GetJniEnv();
1204  ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
1205  if (exception_class.get() == NULL) {
1206    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1207               << PrettyTypeOf(GetException());
1208    CHECK(IsExceptionPending());
1209    return;
1210  }
1211  int rc = env->ThrowNew(exception_class.get(), msg);
1212  if (rc != JNI_OK) {
1213    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1214               << PrettyTypeOf(GetException());
1215    CHECK(IsExceptionPending());
1216    return;
1217  }
1218}
1219
1220void Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
1221  std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
1222      PrettyDescriptor(c->GetDescriptor()).c_str()));
1223  ThrowOutOfMemoryError(msg.c_str());
1224}
1225
1226void Thread::ThrowOutOfMemoryError(const char* msg) {
1227  LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1228      msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
1229  if (!throwing_OutOfMemoryError_) {
1230    throwing_OutOfMemoryError_ = true;
1231    ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
1232  } else {
1233    SetException(pre_allocated_OutOfMemoryError_);
1234  }
1235  throwing_OutOfMemoryError_ = false;
1236}
1237
1238
1239Thread* Thread::CurrentFromGdb() {
1240  return Thread::Current();
1241}
1242
1243void Thread::DumpFromGdb() const {
1244  Dump(std::cerr);
1245}
1246
1247class CatchBlockStackVisitor : public Thread::StackVisitor {
1248 public:
1249  CatchBlockStackVisitor(Class* to_find, Context* ljc)
1250      : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1251#ifndef NDEBUG
1252    handler_pc_ = 0xEBADC0DE;
1253    handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1254#endif
1255  }
1256
1257  virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1258    if (!found_) {
1259      Method* method = fr.GetMethod();
1260      if (method == NULL) {
1261        // This is the upcall, we remember the frame and last_pc so that we may
1262        // long jump to them
1263        handler_pc_ = DemanglePc(pc);
1264        handler_frame_ = fr;
1265        return;
1266      }
1267      uint32_t dex_pc = DexFile::kDexNoIndex;
1268      if (method->IsCalleeSaveMethod()) {
1269        // ignore callee save method
1270      } else if (method->IsNative()) {
1271        native_method_count_++;
1272      } else {
1273        dex_pc = method->ToDexPC(pc);
1274      }
1275      if (dex_pc != DexFile::kDexNoIndex) {
1276        uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1277        if (found_dex_pc != DexFile::kDexNoIndex) {
1278          found_ = true;
1279          handler_pc_ = method->ToNativePC(found_dex_pc);
1280          handler_frame_ = fr;
1281        }
1282      }
1283      if (!found_) {
1284        // Caller may be handler, fill in callee saves in context
1285        long_jump_context_->FillCalleeSaves(fr);
1286      }
1287    }
1288  }
1289
1290  // Did we find a catch block yet?
1291  bool found_;
1292  // The type of the exception catch block to find
1293  Class* to_find_;
1294  // Frame with found handler or last frame if no handler found
1295  Frame handler_frame_;
1296  // PC to branch to for the handler
1297  uintptr_t handler_pc_;
1298  // Context that will be the target of the long jump
1299  Context* long_jump_context_;
1300  // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1301  uint32_t native_method_count_;
1302};
1303
1304void Thread::DeliverException() {
1305  Throwable *exception = GetException();  // Set exception on thread
1306  CHECK(exception != NULL);
1307
1308  Context* long_jump_context = GetLongJumpContext();
1309  CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
1310  WalkStackUntilUpCall(&catch_finder, true);
1311
1312  long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1313  long_jump_context->SetPC(catch_finder.handler_pc_);
1314  long_jump_context->DoLongJump();
1315}
1316
1317Context* Thread::GetLongJumpContext() {
1318  Context* result = long_jump_context_;
1319  if (result == NULL) {
1320    result = Context::Create();
1321    long_jump_context_ = result;
1322  }
1323  return result;
1324}
1325
1326const Method* Thread::GetCurrentMethod() const {
1327  Method* m = top_of_managed_stack_.GetMethod();
1328  // We use JNI internally for exception throwing, so it's possible to arrive
1329  // here via a "FromCode" function, in which case there's a synthetic
1330  // callee-save method at the top of the stack. These shouldn't be user-visible,
1331  // so if we find one, skip it and return the compiled method underneath.
1332  if (m->IsCalleeSaveMethod()) {
1333    Frame f = top_of_managed_stack_;
1334    f.Next();
1335    m = f.GetMethod();
1336  }
1337  return m;
1338}
1339
1340bool Thread::HoldsLock(Object* object) {
1341  if (object == NULL) {
1342    return false;
1343  }
1344  return object->GetThinLockId() == thin_lock_id_;
1345}
1346
1347bool Thread::IsDaemon() {
1348  return gThread_daemon->GetBoolean(peer_);
1349}
1350
1351class ReferenceMapVisitor : public Thread::StackVisitor {
1352 public:
1353  ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1354    context_(context), root_visitor_(root_visitor), arg_(arg) {
1355  }
1356
1357  void VisitFrame(const Frame& frame, uintptr_t pc) {
1358    Method* m = frame.GetMethod();
1359    // Process register map (which native and callee save methods don't have)
1360    if (!m->IsNative() && !m->IsCalleeSaveMethod()) {
1361      UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
1362      const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(map.get(), m->ToDexPC(pc));
1363      if (false) {
1364        LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
1365                  << "@ PC: " << m->ToDexPC(pc);
1366      }
1367      CHECK(reg_bitmap != NULL);
1368      const uint16_t* vmap = m->GetVmapTable();
1369      // For all dex registers
1370      for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1371        // Does this register hold a reference?
1372        if (TestBitmap(reg, reg_bitmap)) {
1373          // Is the reference in the context or on the stack?
1374          bool in_context = false;
1375          uint32_t vmap_offset = 0xEBAD0FF5;
1376          // TODO: take advantage of the registers being ordered
1377          for (int i = 0; i < m->GetVmapTableLength(); i++) {
1378            if (vmap[i] == reg) {
1379              in_context = true;
1380              vmap_offset = i;
1381              break;
1382            }
1383          }
1384          Object* ref;
1385          if (in_context) {
1386            // Compute the register we need to load from the context
1387            uint32_t spill_mask = m->GetCoreSpillMask();
1388            uint32_t matches = 0;
1389            uint32_t spill_shifts = 0;
1390            while (matches != (vmap_offset + 1)) {
1391              CHECK_NE(spill_mask, 0u);
1392              matches += spill_mask & 1;  // Add 1 if the low bit is set
1393              spill_mask >>= 1;
1394              spill_shifts++;
1395            }
1396            spill_shifts--;  // wind back one as we want the last match
1397            ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
1398          } else {
1399            ref = reinterpret_cast<Object*>(frame.GetVReg(m, reg));
1400          }
1401          if (ref != NULL) {
1402            root_visitor_(ref, arg_);
1403          }
1404        }
1405      }
1406    }
1407    context_->FillCalleeSaves(frame);
1408  }
1409
1410 private:
1411  bool TestBitmap(int reg, const uint8_t* reg_vector) {
1412    return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1413  }
1414
1415  // Context used to build up picture of callee saves
1416  Context* context_;
1417  // Call-back when we visit a root
1418  Heap::RootVisitor* root_visitor_;
1419  // Argument to call-back
1420  void* arg_;
1421};
1422
1423void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
1424  if (exception_ != NULL) {
1425    visitor(exception_, arg);
1426  }
1427  if (peer_ != NULL) {
1428    visitor(peer_, arg);
1429  }
1430  if (pre_allocated_OutOfMemoryError_ != NULL) {
1431    visitor(pre_allocated_OutOfMemoryError_, arg);
1432  }
1433  if (class_loader_override_ != NULL) {
1434    visitor(class_loader_override_, arg);
1435  }
1436  jni_env_->locals.VisitRoots(visitor, arg);
1437  jni_env_->monitors.VisitRoots(visitor, arg);
1438
1439  SirtVisitRoots(visitor, arg);
1440
1441  // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1442  // delivery.
1443  Context* context = GetLongJumpContext();
1444  // Visit roots on this thread's stack
1445  ReferenceMapVisitor mapper(context, visitor, arg);
1446  WalkStack(&mapper);
1447}
1448
1449static const char* kStateNames[] = {
1450  "Terminated",
1451  "Runnable",
1452  "TimedWaiting",
1453  "Blocked",
1454  "Waiting",
1455  "Initializing",
1456  "Starting",
1457  "Native",
1458  "VmWait",
1459  "Suspended",
1460};
1461std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
1462  int32_t int_state = static_cast<int32_t>(state);
1463  if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1464    os << kStateNames[int_state];
1465  } else {
1466    os << "State[" << int_state << "]";
1467  }
1468  return os;
1469}
1470
1471std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1472  os << "Thread[" << &thread
1473     << ",tid=" << thread.GetTid()
1474     << ",id=" << thread.GetThinLockId()
1475     << ",state=" << thread.GetState()
1476     << ",peer=" << thread.GetPeer()
1477     << "]";
1478  return os;
1479}
1480
1481}  // namespace art
1482