Home | History | Annotate | Download | only in vm
      1 /*
      2  * Copyright (C) 2008 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 /*
     18  * Thread support.
     19  */
     20 #include "Dalvik.h"
     21 #include "native/SystemThread.h"
     22 
     23 #include "utils/threads.h"      // need Android thread priorities
     24 
     25 #include <stdlib.h>
     26 #include <unistd.h>
     27 #include <sys/time.h>
     28 #include <sys/types.h>
     29 #include <sys/resource.h>
     30 #include <sys/mman.h>
     31 #include <signal.h>
     32 #include <errno.h>
     33 #include <fcntl.h>
     34 
     35 #if defined(HAVE_PRCTL)
     36 #include <sys/prctl.h>
     37 #endif
     38 
     39 #if defined(WITH_SELF_VERIFICATION)
     40 #include "interp/Jit.h"         // need for self verification
     41 #endif
     42 
     43 
     44 /* desktop Linux needs a little help with gettid() */
     45 #if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
     46 #define __KERNEL__
     47 # include <linux/unistd.h>
     48 #ifdef _syscall0
     49 _syscall0(pid_t,gettid)
     50 #else
     51 pid_t gettid() { return syscall(__NR_gettid);}
     52 #endif
     53 #undef __KERNEL__
     54 #endif
     55 
     56 // Change this to enable logging on cgroup errors
     57 #define ENABLE_CGROUP_ERR_LOGGING 0
     58 
     59 // change this to LOGV/LOGD to debug thread activity
     60 #define LOG_THREAD  LOGVV
     61 
     62 /*
     63 Notes on Threading
     64 
     65 All threads are native pthreads.  All threads, except the JDWP debugger
     66 thread, are visible to code running in the VM and to the debugger.  (We
     67 don't want the debugger to try to manipulate the thread that listens for
     68 instructions from the debugger.)  Internal VM threads are in the "system"
     69 ThreadGroup, all others are in the "main" ThreadGroup, per convention.
     70 
     71 The GC only runs when all threads have been suspended.  Threads are
     72 expected to suspend themselves, using a "safe point" mechanism.  We check
     73 for a suspend request at certain points in the main interpreter loop,
     74 and on requests coming in from native code (e.g. all JNI functions).
     75 Certain debugger events may inspire threads to self-suspend.
     76 
     77 Native methods must use JNI calls to modify object references to avoid
     78 clashes with the GC.  JNI doesn't provide a way for native code to access
     79 arrays of objects as such -- code must always get/set individual entries --
     80 so it should be possible to fully control access through JNI.
     81 
     82 Internal native VM threads, such as the finalizer thread, must explicitly
     83 check for suspension periodically.  In most cases they will be sound
     84 asleep on a condition variable, and won't notice the suspension anyway.
     85 
     86 Threads may be suspended by the GC, debugger, or the SIGQUIT listener
     87 thread.  The debugger may suspend or resume individual threads, while the
     88 GC always suspends all threads.  Each thread has a "suspend count" that
     89 is incremented on suspend requests and decremented on resume requests.
     90 When the count is zero, the thread is runnable.  This allows us to fulfill
     91 a debugger requirement: if the debugger suspends a thread, the thread is
     92 not allowed to run again until the debugger resumes it (or disconnects,
     93 in which case we must resume all debugger-suspended threads).
     94 
     95 Paused threads sleep on a condition variable, and are awoken en masse.
     96 Certain "slow" VM operations, such as starting up a new thread, will be
     97 done in a separate "VMWAIT" state, so that the rest of the VM doesn't
     98 freeze up waiting for the operation to finish.  Threads must check for
     99 pending suspension when leaving VMWAIT.
    100 
    101 Because threads suspend themselves while interpreting code or when native
    102 code makes JNI calls, there is no risk of suspending while holding internal
    103 VM locks.  All threads can enter a suspended (or native-code-only) state.
    104 Also, we don't have to worry about object references existing solely
    105 in hardware registers.
    106 
    107 We do, however, have to worry about objects that were allocated internally
    108 and aren't yet visible to anything else in the VM.  If we allocate an
    109 object, and then go to sleep on a mutex after changing to a non-RUNNING
    110 state (e.g. while trying to allocate a second object), the first object
    111 could be garbage-collected out from under us while we sleep.  To manage
    112 this, we automatically add all allocated objects to an internal object
    113 tracking list, and only remove them when we know we won't be suspended
    114 before the object appears in the GC root set.
    115 
    116 The debugger may choose to suspend or resume a single thread, which can
    117 lead to application-level deadlocks; this is expected behavior.  The VM
    118 will only check for suspension of single threads when the debugger is
    119 active (the java.lang.Thread calls for this are deprecated and hence are
    120 not supported).  Resumption of a single thread is handled by decrementing
    121 the thread's suspend count and sending a broadcast signal to the condition
    122 variable.  (This will cause all threads to wake up and immediately go back
    123 to sleep, which isn't tremendously efficient, but neither is having the
    124 debugger attached.)
    125 
    126 The debugger is not allowed to resume threads suspended by the GC.  This
    127 is trivially enforced by ignoring debugger requests while the GC is running
    128 (the JDWP thread is suspended during GC).
    129 
    130 The VM maintains a Thread struct for every pthread known to the VM.  There
    131 is a java/lang/Thread object associated with every Thread.  At present,
    132 there is no safe way to go from a Thread object to a Thread struct except by
    133 locking and scanning the list; this is necessary because the lifetimes of
    134 the two are not closely coupled.  We may want to change this behavior,
    135 though at present the only performance impact is on the debugger (see
    136 threadObjToThread()).  See also notes about dvmDetachCurrentThread().
    137 */
    138 /*
    139 Alternate implementation (signal-based):
    140 
    141 Threads run without safe points -- zero overhead.  The VM uses a signal
    142 (e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
    143 
    144 The trouble with using signals to suspend threads is that it means a thread
    145 can be in the middle of an operation when garbage collection starts.
    146 To prevent some sticky situations, we have to introduce critical sections
    147 to the VM code.
    148 
    149 Critical sections temporarily block suspension for a given thread.
    150 The thread must move to a non-blocked state (and self-suspend) after
    151 finishing its current task.  If the thread blocks on a resource held
    152 by a suspended thread, we're hosed.
    153 
    154 One approach is to require that no blocking operations, notably
    155 acquisition of mutexes, can be performed within a critical section.
    156 This is too limiting.  For example, if thread A gets suspended while
    157 holding the thread list lock, it will prevent the GC or debugger from
    158 being able to safely access the thread list.  We need to wrap the critical
    159 section around the entire operation (enter critical, get lock, do stuff,
    160 release lock, exit critical).
    161 
    162 A better approach is to declare that certain resources can only be held
    163 within critical sections.  A thread that enters a critical section and
    164 then gets blocked on the thread list lock knows that the thread it is
    165 waiting for is also in a critical section, and will release the lock
    166 before suspending itself.  Eventually all threads will complete their
    167 operations and self-suspend.  For this to work, the VM must:
    168 
    169  (1) Determine the set of resources that may be accessed from the GC or
    170      debugger threads.  The mutexes guarding those go into the "critical
    171      resource set" (CRS).
    172  (2) Ensure that no resource in the CRS can be acquired outside of a
    173      critical section.  This can be verified with an assert().
    174  (3) Ensure that only resources in the CRS can be held while in a critical
    175      section.  This is harder to enforce.
    176 
    177 If any of these conditions are not met, deadlock can ensue when grabbing
    178 resources in the GC or debugger (#1) or waiting for threads to suspend
    179 (#2,#3).  (You won't actually deadlock in the GC, because if the semantics
    180 above are followed you don't need to lock anything in the GC.  The risk is
    181 rather that the GC will access data structures in an intermediate state.)
    182 
    183 This approach requires more care and awareness in the VM than
    184 safe-pointing.  Because the GC and debugger are fairly intrusive, there
    185 really aren't any internal VM resources that aren't shared.  Thus, the
    186 enter/exit critical calls can be added to internal mutex wrappers, which
    187 makes it easy to get #1 and #2 right.
    188 
    189 An ordering should be established for all locks to avoid deadlocks.
    190 
    191 Monitor locks, which are also implemented with pthread calls, should not
    192 cause any problems here.  Threads fighting over such locks will not be in
    193 critical sections and can be suspended freely.
    194 
    195 This can get tricky if we ever need exclusive access to VM and non-VM
    196 resources at the same time.  It's not clear if this is a real concern.
    197 
    198 There are (at least) two ways to handle the incoming signals:
    199 
    200  (a) Always accept signals.  If we're in a critical section, the signal
    201      handler just returns without doing anything (the "suspend level"
    202      should have been incremented before the signal was sent).  Otherwise,
    203      if the "suspend level" is nonzero, we go to sleep.
    204  (b) Block signals in critical sections.  This ensures that we can't be
    205      interrupted in a critical section, but requires pthread_sigmask()
    206      calls on entry and exit.
    207 
    208 This is a choice between blocking the message and blocking the messenger.
    209 Because UNIX signals are unreliable (you can only know that you have been
    210 signaled, not whether you were signaled once or 10 times), the choice is
    211 not significant for correctness.  The choice depends on the efficiency
    212 of pthread_sigmask() and the desire to actually block signals.  Either way,
    213 it is best to ensure that there is only one indication of "blocked";
    214 having two (i.e. block signals and set a flag, then only send a signal
    215 if the flag isn't set) can lead to race conditions.
    216 
    217 The signal handler must take care to copy registers onto the stack (via
    218 setjmp), so that stack scans find all references.  Because we have to scan
    219 native stacks, "exact" GC is not possible with this approach.
    220 
    221 Some other concerns with flinging signals around:
    222  - Odd interactions with some debuggers (e.g. gdb on the Mac)
    223  - Restrictions on some standard library calls during GC (e.g. don't
    224    use printf on stdout to print GC debug messages)
    225 */
    226 
    227 #define kMaxThreadId        ((1 << 16) - 1)
    228 #define kMainThreadId       1
    229 
    230 
    231 static Thread* allocThread(int interpStackSize);
    232 static bool prepareThread(Thread* thread);
    233 static void setThreadSelf(Thread* thread);
    234 static void unlinkThread(Thread* thread);
    235 static void freeThread(Thread* thread);
    236 static void assignThreadId(Thread* thread);
    237 static bool createFakeEntryFrame(Thread* thread);
    238 static bool createFakeRunFrame(Thread* thread);
    239 static void* interpThreadStart(void* arg);
    240 static void* internalThreadStart(void* arg);
    241 static void threadExitUncaughtException(Thread* thread, Object* group);
    242 static void threadExitCheck(void* arg);
    243 static void waitForThreadSuspend(Thread* self, Thread* thread);
    244 static int getThreadPriorityFromSystem(void);
    245 
    246 /*
    247  * The JIT needs to know if any thread is suspended.  We do this by
    248  * maintaining a global sum of all threads' suspend counts.  All suspendCount
    249  * updates should go through this after aquiring threadSuspendCountLock.
    250  */
    251 static inline void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
    252 {
    253     *pSuspendCount += delta;
    254     gDvm.sumThreadSuspendCount += delta;
    255 }
    256 
    257 /*
    258  * Initialize thread list and main thread's environment.  We need to set
    259  * up some basic stuff so that dvmThreadSelf() will work when we start
    260  * loading classes (e.g. to check for exceptions).
    261  */
    262 bool dvmThreadStartup(void)
    263 {
    264     Thread* thread;
    265 
    266     /* allocate a TLS slot */
    267     if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
    268         LOGE("ERROR: pthread_key_create failed\n");
    269         return false;
    270     }
    271 
    272     /* test our pthread lib */
    273     if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
    274         LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
    275 
    276     /* prep thread-related locks and conditions */
    277     dvmInitMutex(&gDvm.threadListLock);
    278     pthread_cond_init(&gDvm.threadStartCond, NULL);
    279     //dvmInitMutex(&gDvm.vmExitLock);
    280     pthread_cond_init(&gDvm.vmExitCond, NULL);
    281     dvmInitMutex(&gDvm._threadSuspendLock);
    282     dvmInitMutex(&gDvm.threadSuspendCountLock);
    283     pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
    284 #ifdef WITH_DEADLOCK_PREDICTION
    285     dvmInitMutex(&gDvm.deadlockHistoryLock);
    286 #endif
    287 
    288     /*
    289      * Dedicated monitor for Thread.sleep().
    290      * TODO: change this to an Object* so we don't have to expose this
    291      * call, and we interact better with JDWP monitor calls.  Requires
    292      * deferring the object creation to much later (e.g. final "main"
    293      * thread prep) or until first use.
    294      */
    295     gDvm.threadSleepMon = dvmCreateMonitor(NULL);
    296 
    297     gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
    298 
    299     thread = allocThread(gDvm.stackSize);
    300     if (thread == NULL)
    301         return false;
    302 
    303     /* switch mode for when we run initializers */
    304     thread->status = THREAD_RUNNING;
    305 
    306     /*
    307      * We need to assign the threadId early so we can lock/notify
    308      * object monitors.  We'll set the "threadObj" field later.
    309      */
    310     prepareThread(thread);
    311     gDvm.threadList = thread;
    312 
    313 #ifdef COUNT_PRECISE_METHODS
    314     gDvm.preciseMethods = dvmPointerSetAlloc(200);
    315 #endif
    316 
    317     return true;
    318 }
    319 
    320 /*
    321  * We're a little farther up now, and can load some basic classes.
    322  *
    323  * We're far enough along that we can poke at java.lang.Thread and friends,
    324  * but should not assume that static initializers have run (or cause them
    325  * to do so).  That means no object allocations yet.
    326  */
    327 bool dvmThreadObjStartup(void)
    328 {
    329     /*
    330      * Cache the locations of these classes.  It's likely that we're the
    331      * first to reference them, so they're being loaded now.
    332      */
    333     gDvm.classJavaLangThread =
    334         dvmFindSystemClassNoInit("Ljava/lang/Thread;");
    335     gDvm.classJavaLangVMThread =
    336         dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
    337     gDvm.classJavaLangThreadGroup =
    338         dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
    339     if (gDvm.classJavaLangThread == NULL ||
    340         gDvm.classJavaLangThreadGroup == NULL ||
    341         gDvm.classJavaLangThreadGroup == NULL)
    342     {
    343         LOGE("Could not find one or more essential thread classes\n");
    344         return false;
    345     }
    346 
    347     /*
    348      * Cache field offsets.  This makes things a little faster, at the
    349      * expense of hard-coding non-public field names into the VM.
    350      */
    351     gDvm.offJavaLangThread_vmThread =
    352         dvmFindFieldOffset(gDvm.classJavaLangThread,
    353             "vmThread", "Ljava/lang/VMThread;");
    354     gDvm.offJavaLangThread_group =
    355         dvmFindFieldOffset(gDvm.classJavaLangThread,
    356             "group", "Ljava/lang/ThreadGroup;");
    357     gDvm.offJavaLangThread_daemon =
    358         dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
    359     gDvm.offJavaLangThread_name =
    360         dvmFindFieldOffset(gDvm.classJavaLangThread,
    361             "name", "Ljava/lang/String;");
    362     gDvm.offJavaLangThread_priority =
    363         dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
    364 
    365     if (gDvm.offJavaLangThread_vmThread < 0 ||
    366         gDvm.offJavaLangThread_group < 0 ||
    367         gDvm.offJavaLangThread_daemon < 0 ||
    368         gDvm.offJavaLangThread_name < 0 ||
    369         gDvm.offJavaLangThread_priority < 0)
    370     {
    371         LOGE("Unable to find all fields in java.lang.Thread\n");
    372         return false;
    373     }
    374 
    375     gDvm.offJavaLangVMThread_thread =
    376         dvmFindFieldOffset(gDvm.classJavaLangVMThread,
    377             "thread", "Ljava/lang/Thread;");
    378     gDvm.offJavaLangVMThread_vmData =
    379         dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
    380     if (gDvm.offJavaLangVMThread_thread < 0 ||
    381         gDvm.offJavaLangVMThread_vmData < 0)
    382     {
    383         LOGE("Unable to find all fields in java.lang.VMThread\n");
    384         return false;
    385     }
    386 
    387     /*
    388      * Cache the vtable offset for "run()".
    389      *
    390      * We don't want to keep the Method* because then we won't find see
    391      * methods defined in subclasses.
    392      */
    393     Method* meth;
    394     meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
    395     if (meth == NULL) {
    396         LOGE("Unable to find run() in java.lang.Thread\n");
    397         return false;
    398     }
    399     gDvm.voffJavaLangThread_run = meth->methodIndex;
    400 
    401     /*
    402      * Cache vtable offsets for ThreadGroup methods.
    403      */
    404     meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
    405         "removeThread", "(Ljava/lang/Thread;)V");
    406     if (meth == NULL) {
    407         LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
    408         return false;
    409     }
    410     gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
    411 
    412     return true;
    413 }
    414 
    415 /*
    416  * All threads should be stopped by now.  Clean up some thread globals.
    417  */
    418 void dvmThreadShutdown(void)
    419 {
    420     if (gDvm.threadList != NULL) {
    421         /*
    422          * If we walk through the thread list and try to free the
    423          * lingering thread structures (which should only be for daemon
    424          * threads), the daemon threads may crash if they execute before
    425          * the process dies.  Let them leak.
    426          */
    427         freeThread(gDvm.threadList);
    428         gDvm.threadList = NULL;
    429     }
    430 
    431     dvmFreeBitVector(gDvm.threadIdMap);
    432 
    433     dvmFreeMonitorList();
    434 
    435     pthread_key_delete(gDvm.pthreadKeySelf);
    436 }
    437 
    438 
    439 /*
    440  * Grab the suspend count global lock.
    441  */
    442 static inline void lockThreadSuspendCount(void)
    443 {
    444     /*
    445      * Don't try to change to VMWAIT here.  When we change back to RUNNING
    446      * we have to check for a pending suspend, which results in grabbing
    447      * this lock recursively.  Doesn't work with "fast" pthread mutexes.
    448      *
    449      * This lock is always held for very brief periods, so as long as
    450      * mutex ordering is respected we shouldn't stall.
    451      */
    452     int cc = pthread_mutex_lock(&gDvm.threadSuspendCountLock);
    453     assert(cc == 0);
    454 }
    455 
    456 /*
    457  * Release the suspend count global lock.
    458  */
    459 static inline void unlockThreadSuspendCount(void)
    460 {
    461     dvmUnlockMutex(&gDvm.threadSuspendCountLock);
    462 }
    463 
    464 /*
    465  * Grab the thread list global lock.
    466  *
    467  * This is held while "suspend all" is trying to make everybody stop.  If
    468  * the shutdown is in progress, and somebody tries to grab the lock, they'll
    469  * have to wait for the GC to finish.  Therefore it's important that the
    470  * thread not be in RUNNING mode.
    471  *
    472  * We don't have to check to see if we should be suspended once we have
    473  * the lock.  Nobody can suspend all threads without holding the thread list
    474  * lock while they do it, so by definition there isn't a GC in progress.
    475  *
    476  * TODO: consider checking for suspend after acquiring the lock, and
    477  * backing off if set.  As stated above, it can't happen during normal
    478  * execution, but it *can* happen during shutdown when daemon threads
    479  * are being suspended.
    480  */
    481 void dvmLockThreadList(Thread* self)
    482 {
    483     ThreadStatus oldStatus;
    484 
    485     if (self == NULL)       /* try to get it from TLS */
    486         self = dvmThreadSelf();
    487 
    488     if (self != NULL) {
    489         oldStatus = self->status;
    490         self->status = THREAD_VMWAIT;
    491     } else {
    492         /* happens during VM shutdown */
    493         //LOGW("NULL self in dvmLockThreadList\n");
    494         oldStatus = -1;         // shut up gcc
    495     }
    496 
    497     int cc = pthread_mutex_lock(&gDvm.threadListLock);
    498     assert(cc == 0);
    499 
    500     if (self != NULL)
    501         self->status = oldStatus;
    502 }
    503 
    504 /*
    505  * Release the thread list global lock.
    506  */
    507 void dvmUnlockThreadList(void)
    508 {
    509     int cc = pthread_mutex_unlock(&gDvm.threadListLock);
    510     assert(cc == 0);
    511 }
    512 
    513 /*
    514  * Convert SuspendCause to a string.
    515  */
    516 static const char* getSuspendCauseStr(SuspendCause why)
    517 {
    518     switch (why) {
    519     case SUSPEND_NOT:               return "NOT?";
    520     case SUSPEND_FOR_GC:            return "gc";
    521     case SUSPEND_FOR_DEBUG:         return "debug";
    522     case SUSPEND_FOR_DEBUG_EVENT:   return "debug-event";
    523     case SUSPEND_FOR_STACK_DUMP:    return "stack-dump";
    524 #if defined(WITH_JIT)
    525     case SUSPEND_FOR_TBL_RESIZE:    return "table-resize";
    526     case SUSPEND_FOR_IC_PATCH:      return "inline-cache-patch";
    527     case SUSPEND_FOR_CC_RESET:      return "reset-code-cache";
    528     case SUSPEND_FOR_REFRESH:       return "refresh jit status";
    529 #endif
    530     default:                        return "UNKNOWN";
    531     }
    532 }
    533 
    534 /*
    535  * Grab the "thread suspend" lock.  This is required to prevent the
    536  * GC and the debugger from simultaneously suspending all threads.
    537  *
    538  * If we fail to get the lock, somebody else is trying to suspend all
    539  * threads -- including us.  If we go to sleep on the lock we'll deadlock
    540  * the VM.  Loop until we get it or somebody puts us to sleep.
    541  */
    542 static void lockThreadSuspend(const char* who, SuspendCause why)
    543 {
    544     const int kSpinSleepTime = 3*1000*1000;        /* 3s */
    545     u8 startWhen = 0;       // init req'd to placate gcc
    546     int sleepIter = 0;
    547     int cc;
    548 
    549     do {
    550         cc = pthread_mutex_trylock(&gDvm._threadSuspendLock);
    551         if (cc != 0) {
    552             if (!dvmCheckSuspendPending(NULL)) {
    553                 /*
    554                  * Could be that a resume-all is in progress, and something
    555                  * grabbed the CPU when the wakeup was broadcast.  The thread
    556                  * performing the resume hasn't had a chance to release the
    557                  * thread suspend lock.  (We release before the broadcast,
    558                  * so this should be a narrow window.)
    559                  *
    560                  * Could be we hit the window as a suspend was started,
    561                  * and the lock has been grabbed but the suspend counts
    562                  * haven't been incremented yet.
    563                  *
    564                  * Could be an unusual JNI thread-attach thing.
    565                  *
    566                  * Could be the debugger telling us to resume at roughly
    567                  * the same time we're posting an event.
    568                  *
    569                  * Could be two app threads both want to patch predicted
    570                  * chaining cells around the same time.
    571                  */
    572                 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
    573                      " it's held, no suspend pending\n",
    574                     dvmThreadSelf()->threadId, who, getSuspendCauseStr(why));
    575             } else {
    576                 /* we suspended; reset timeout */
    577                 sleepIter = 0;
    578             }
    579 
    580             /* give the lock-holder a chance to do some work */
    581             if (sleepIter == 0)
    582                 startWhen = dvmGetRelativeTimeUsec();
    583             if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
    584                 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
    585                      " bailing\n",
    586                     dvmThreadSelf()->threadId, who, getSuspendCauseStr(why));
    587                 /* threads are not suspended, thread dump could crash */
    588                 dvmDumpAllThreads(false);
    589                 dvmAbort();
    590             }
    591         }
    592     } while (cc != 0);
    593     assert(cc == 0);
    594 }
    595 
    596 /*
    597  * Release the "thread suspend" lock.
    598  */
    599 static inline void unlockThreadSuspend(void)
    600 {
    601     int cc = pthread_mutex_unlock(&gDvm._threadSuspendLock);
    602     assert(cc == 0);
    603 }
    604 
    605 
    606 /*
    607  * Kill any daemon threads that still exist.  All of ours should be
    608  * stopped, so these should be Thread objects or JNI-attached threads
    609  * started by the application.  Actively-running threads are likely
    610  * to crash the process if they continue to execute while the VM
    611  * shuts down, so we really need to kill or suspend them.  (If we want
    612  * the VM to restart within this process, we need to kill them, but that
    613  * leaves open the possibility of orphaned resources.)
    614  *
    615  * Waiting for the thread to suspend may be unwise at this point, but
    616  * if one of these is wedged in a critical section then we probably
    617  * would've locked up on the last GC attempt.
    618  *
    619  * It's possible for this function to get called after a failed
    620  * initialization, so be careful with assumptions about the environment.
    621  *
    622  * This will be called from whatever thread calls DestroyJavaVM, usually
    623  * but not necessarily the main thread.  It's likely, but not guaranteed,
    624  * that the current thread has already been cleaned up.
    625  */
    626 void dvmSlayDaemons(void)
    627 {
    628     Thread* self = dvmThreadSelf();     // may be null
    629     Thread* target;
    630     int threadId = 0;
    631     bool doWait = false;
    632 
    633     //dvmEnterCritical(self);
    634     dvmLockThreadList(self);
    635 
    636     if (self != NULL)
    637         threadId = self->threadId;
    638 
    639     target = gDvm.threadList;
    640     while (target != NULL) {
    641         if (target == self) {
    642             target = target->next;
    643             continue;
    644         }
    645 
    646         if (!dvmGetFieldBoolean(target->threadObj,
    647                 gDvm.offJavaLangThread_daemon))
    648         {
    649             /* should never happen; suspend it with the rest */
    650             LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
    651                 threadId, target->threadId);
    652         }
    653 
    654         char* threadName = dvmGetThreadName(target);
    655         LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
    656             threadId, target->threadId, threadName);
    657         free(threadName);
    658 
    659         /* mark as suspended */
    660         lockThreadSuspendCount();
    661         dvmAddToThreadSuspendCount(&target->suspendCount, 1);
    662         unlockThreadSuspendCount();
    663         doWait = true;
    664 
    665         target = target->next;
    666     }
    667 
    668     //dvmDumpAllThreads(false);
    669 
    670     /*
    671      * Unlock the thread list, relocking it later if necessary.  It's
    672      * possible a thread is in VMWAIT after calling dvmLockThreadList,
    673      * and that function *doesn't* check for pending suspend after
    674      * acquiring the lock.  We want to let them finish their business
    675      * and see the pending suspend before we continue here.
    676      *
    677      * There's no guarantee of mutex fairness, so this might not work.
    678      * (The alternative is to have dvmLockThreadList check for suspend
    679      * after acquiring the lock and back off, something we should consider.)
    680      */
    681     dvmUnlockThreadList();
    682 
    683     if (doWait) {
    684         bool complained = false;
    685 
    686         usleep(200 * 1000);
    687 
    688         dvmLockThreadList(self);
    689 
    690         /*
    691          * Sleep for a bit until the threads have suspended.  We're trying
    692          * to exit, so don't wait for too long.
    693          */
    694         int i;
    695         for (i = 0; i < 10; i++) {
    696             bool allSuspended = true;
    697 
    698             target = gDvm.threadList;
    699             while (target != NULL) {
    700                 if (target == self) {
    701                     target = target->next;
    702                     continue;
    703                 }
    704 
    705                 if (target->status == THREAD_RUNNING && !target->isSuspended) {
    706                     if (!complained)
    707                         LOGD("threadid=%d not ready yet\n", target->threadId);
    708                     allSuspended = false;
    709                     /* keep going so we log each running daemon once */
    710                 }
    711 
    712                 target = target->next;
    713             }
    714 
    715             if (allSuspended) {
    716                 LOGD("threadid=%d: all daemons have suspended\n", threadId);
    717                 break;
    718             } else {
    719                 if (!complained) {
    720                     complained = true;
    721                     LOGD("threadid=%d: waiting briefly for daemon suspension\n",
    722                         threadId);
    723                 }
    724             }
    725 
    726             usleep(200 * 1000);
    727         }
    728         dvmUnlockThreadList();
    729     }
    730 
    731 #if 0   /* bad things happen if they come out of JNI or "spuriously" wake up */
    732     /*
    733      * Abandon the threads and recover their resources.
    734      */
    735     target = gDvm.threadList;
    736     while (target != NULL) {
    737         Thread* nextTarget = target->next;
    738         unlinkThread(target);
    739         freeThread(target);
    740         target = nextTarget;
    741     }
    742 #endif
    743 
    744     //dvmDumpAllThreads(true);
    745 }
    746 
    747 
    748 /*
    749  * Finish preparing the parts of the Thread struct required to support
    750  * JNI registration.
    751  */
    752 bool dvmPrepMainForJni(JNIEnv* pEnv)
    753 {
    754     Thread* self;
    755 
    756     /* main thread is always first in list at this point */
    757     self = gDvm.threadList;
    758     assert(self->threadId == kMainThreadId);
    759 
    760     /* create a "fake" JNI frame at the top of the main thread interp stack */
    761     if (!createFakeEntryFrame(self))
    762         return false;
    763 
    764     /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
    765     dvmSetJniEnvThreadId(pEnv, self);
    766     dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
    767 
    768     return true;
    769 }
    770 
    771 
    772 /*
    773  * Finish preparing the main thread, allocating some objects to represent
    774  * it.  As part of doing so, we finish initializing Thread and ThreadGroup.
    775  * This will execute some interpreted code (e.g. class initializers).
    776  */
    777 bool dvmPrepMainThread(void)
    778 {
    779     Thread* thread;
    780     Object* groupObj;
    781     Object* threadObj;
    782     Object* vmThreadObj;
    783     StringObject* threadNameStr;
    784     Method* init;
    785     JValue unused;
    786 
    787     LOGV("+++ finishing prep on main VM thread\n");
    788 
    789     /* main thread is always first in list at this point */
    790     thread = gDvm.threadList;
    791     assert(thread->threadId == kMainThreadId);
    792 
    793     /*
    794      * Make sure the classes are initialized.  We have to do this before
    795      * we create an instance of them.
    796      */
    797     if (!dvmInitClass(gDvm.classJavaLangClass)) {
    798         LOGE("'Class' class failed to initialize\n");
    799         return false;
    800     }
    801     if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
    802         !dvmInitClass(gDvm.classJavaLangThread) ||
    803         !dvmInitClass(gDvm.classJavaLangVMThread))
    804     {
    805         LOGE("thread classes failed to initialize\n");
    806         return false;
    807     }
    808 
    809     groupObj = dvmGetMainThreadGroup();
    810     if (groupObj == NULL)
    811         return false;
    812 
    813     /*
    814      * Allocate and construct a Thread with the internal-creation
    815      * constructor.
    816      */
    817     threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
    818     if (threadObj == NULL) {
    819         LOGE("unable to allocate main thread object\n");
    820         return false;
    821     }
    822     dvmReleaseTrackedAlloc(threadObj, NULL);
    823 
    824     threadNameStr = dvmCreateStringFromCstr("main", ALLOC_DEFAULT);
    825     if (threadNameStr == NULL)
    826         return false;
    827     dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
    828 
    829     init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
    830             "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
    831     assert(init != NULL);
    832     dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
    833         THREAD_NORM_PRIORITY, false);
    834     if (dvmCheckException(thread)) {
    835         LOGE("exception thrown while constructing main thread object\n");
    836         return false;
    837     }
    838 
    839     /*
    840      * Allocate and construct a VMThread.
    841      */
    842     vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
    843     if (vmThreadObj == NULL) {
    844         LOGE("unable to allocate main vmthread object\n");
    845         return false;
    846     }
    847     dvmReleaseTrackedAlloc(vmThreadObj, NULL);
    848 
    849     init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
    850             "(Ljava/lang/Thread;)V");
    851     dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
    852     if (dvmCheckException(thread)) {
    853         LOGE("exception thrown while constructing main vmthread object\n");
    854         return false;
    855     }
    856 
    857     /* set the VMThread.vmData field to our Thread struct */
    858     assert(gDvm.offJavaLangVMThread_vmData != 0);
    859     dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
    860 
    861     /*
    862      * Stuff the VMThread back into the Thread.  From this point on, other
    863      * Threads will see that this Thread is running (at least, they would,
    864      * if there were any).
    865      */
    866     dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
    867         vmThreadObj);
    868 
    869     thread->threadObj = threadObj;
    870 
    871     /*
    872      * Set the context class loader.  This invokes a ClassLoader method,
    873      * which could conceivably call Thread.currentThread(), so we want the
    874      * Thread to be fully configured before we do this.
    875      */
    876     Object* systemLoader = dvmGetSystemClassLoader();
    877     if (systemLoader == NULL) {
    878         LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
    879         /* keep going */
    880     }
    881     int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
    882         "contextClassLoader", "Ljava/lang/ClassLoader;");
    883     if (ctxtClassLoaderOffset < 0) {
    884         LOGE("Unable to find contextClassLoader field in Thread\n");
    885         return false;
    886     }
    887     dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
    888 
    889     /*
    890      * Finish our thread prep.
    891      */
    892 
    893     /* include self in non-daemon threads (mainly for AttachCurrentThread) */
    894     gDvm.nonDaemonThreadCount++;
    895 
    896     return true;
    897 }
    898 
    899 
    900 /*
    901  * Alloc and initialize a Thread struct.
    902  *
    903  * "threadObj" is the java.lang.Thread object.  It will be NULL for the
    904  * main VM thread, but non-NULL for everything else.
    905  *
    906  * Does not create any objects, just stuff on the system (malloc) heap.  (If
    907  * this changes, we need to use ALLOC_NO_GC.  And also verify that we're
    908  * ready to load classes at the time this is called.)
    909  */
    910 static Thread* allocThread(int interpStackSize)
    911 {
    912     Thread* thread;
    913     u1* stackBottom;
    914 
    915     thread = (Thread*) calloc(1, sizeof(Thread));
    916     if (thread == NULL)
    917         return NULL;
    918 
    919 #if defined(WITH_SELF_VERIFICATION)
    920     if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
    921         return NULL;
    922 #endif
    923 
    924     assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
    925 
    926     thread->status = THREAD_INITIALIZING;
    927     thread->suspendCount = 0;
    928 
    929 #ifdef WITH_ALLOC_LIMITS
    930     thread->allocLimit = -1;
    931 #endif
    932 
    933     /*
    934      * Allocate and initialize the interpreted code stack.  We essentially
    935      * "lose" the alloc pointer, which points at the bottom of the stack,
    936      * but we can get it back later because we know how big the stack is.
    937      *
    938      * The stack must be aligned on a 4-byte boundary.
    939      */
    940 #ifdef MALLOC_INTERP_STACK
    941     stackBottom = (u1*) malloc(interpStackSize);
    942     if (stackBottom == NULL) {
    943 #if defined(WITH_SELF_VERIFICATION)
    944         dvmSelfVerificationShadowSpaceFree(thread);
    945 #endif
    946         free(thread);
    947         return NULL;
    948     }
    949     memset(stackBottom, 0xc5, interpStackSize);     // stop valgrind complaints
    950 #else
    951     stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
    952         MAP_PRIVATE | MAP_ANON, -1, 0);
    953     if (stackBottom == MAP_FAILED) {
    954 #if defined(WITH_SELF_VERIFICATION)
    955         dvmSelfVerificationShadowSpaceFree(thread);
    956 #endif
    957         free(thread);
    958         return NULL;
    959     }
    960 #endif
    961 
    962     assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
    963     thread->interpStackSize = interpStackSize;
    964     thread->interpStackStart = stackBottom + interpStackSize;
    965     thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
    966 
    967     /* give the thread code a chance to set things up */
    968     dvmInitInterpStack(thread, interpStackSize);
    969 
    970     return thread;
    971 }
    972 
    973 /*
    974  * Get a meaningful thread ID.  At present this only has meaning under Linux,
    975  * where getpid() and gettid() sometimes agree and sometimes don't depending
    976  * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
    977  */
    978 pid_t dvmGetSysThreadId(void)
    979 {
    980 #ifdef HAVE_GETTID
    981     return gettid();
    982 #else
    983     return getpid();
    984 #endif
    985 }
    986 
    987 /*
    988  * Finish initialization of a Thread struct.
    989  *
    990  * This must be called while executing in the new thread, but before the
    991  * thread is added to the thread list.
    992  *
    993  * *** NOTE: The threadListLock must be held by the caller (needed for
    994  * assignThreadId()).
    995  */
    996 static bool prepareThread(Thread* thread)
    997 {
    998     assignThreadId(thread);
    999     thread->handle = pthread_self();
   1000     thread->systemTid = dvmGetSysThreadId();
   1001 
   1002     //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
   1003     //    (int) getpid());
   1004     setThreadSelf(thread);
   1005 
   1006     LOGV("threadid=%d: interp stack at %p\n",
   1007         thread->threadId, thread->interpStackStart - thread->interpStackSize);
   1008 
   1009     /*
   1010      * Initialize invokeReq.
   1011      */
   1012     dvmInitMutex(&thread->invokeReq.lock);
   1013     pthread_cond_init(&thread->invokeReq.cv, NULL);
   1014 
   1015     /*
   1016      * Initialize our reference tracking tables.
   1017      *
   1018      * Most threads won't use jniMonitorRefTable, so we clear out the
   1019      * structure but don't call the init function (which allocs storage).
   1020      */
   1021 #ifdef USE_INDIRECT_REF
   1022     if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
   1023             kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
   1024         return false;
   1025 #else
   1026     /*
   1027      * The JNI local ref table *must* be fixed-size because we keep pointers
   1028      * into the table in our stack frames.
   1029      */
   1030     if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
   1031             kJniLocalRefMax, kJniLocalRefMax))
   1032         return false;
   1033 #endif
   1034     if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
   1035             kInternalRefDefault, kInternalRefMax))
   1036         return false;
   1037 
   1038     memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
   1039 
   1040     pthread_cond_init(&thread->waitCond, NULL);
   1041     dvmInitMutex(&thread->waitMutex);
   1042 
   1043     return true;
   1044 }
   1045 
   1046 /*
   1047  * Remove a thread from the internal list.
   1048  * Clear out the links to make it obvious that the thread is
   1049  * no longer on the list.  Caller must hold gDvm.threadListLock.
   1050  */
   1051 static void unlinkThread(Thread* thread)
   1052 {
   1053     LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
   1054     if (thread == gDvm.threadList) {
   1055         assert(thread->prev == NULL);
   1056         gDvm.threadList = thread->next;
   1057     } else {
   1058         assert(thread->prev != NULL);
   1059         thread->prev->next = thread->next;
   1060     }
   1061     if (thread->next != NULL)
   1062         thread->next->prev = thread->prev;
   1063     thread->prev = thread->next = NULL;
   1064 }
   1065 
   1066 /*
   1067  * Free a Thread struct, and all the stuff allocated within.
   1068  */
   1069 static void freeThread(Thread* thread)
   1070 {
   1071     if (thread == NULL)
   1072         return;
   1073 
   1074     /* thread->threadId is zero at this point */
   1075     LOGVV("threadid=%d: freeing\n", thread->threadId);
   1076 
   1077     if (thread->interpStackStart != NULL) {
   1078         u1* interpStackBottom;
   1079 
   1080         interpStackBottom = thread->interpStackStart;
   1081         interpStackBottom -= thread->interpStackSize;
   1082 #ifdef MALLOC_INTERP_STACK
   1083         free(interpStackBottom);
   1084 #else
   1085         if (munmap(interpStackBottom, thread->interpStackSize) != 0)
   1086             LOGW("munmap(thread stack) failed\n");
   1087 #endif
   1088     }
   1089 
   1090 #ifdef USE_INDIRECT_REF
   1091     dvmClearIndirectRefTable(&thread->jniLocalRefTable);
   1092 #else
   1093     dvmClearReferenceTable(&thread->jniLocalRefTable);
   1094 #endif
   1095     dvmClearReferenceTable(&thread->internalLocalRefTable);
   1096     if (&thread->jniMonitorRefTable.table != NULL)
   1097         dvmClearReferenceTable(&thread->jniMonitorRefTable);
   1098 
   1099 #if defined(WITH_SELF_VERIFICATION)
   1100     dvmSelfVerificationShadowSpaceFree(thread);
   1101 #endif
   1102     free(thread);
   1103 }
   1104 
   1105 /*
   1106  * Like pthread_self(), but on a Thread*.
   1107  */
   1108 Thread* dvmThreadSelf(void)
   1109 {
   1110     return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
   1111 }
   1112 
   1113 /*
   1114  * Explore our sense of self.  Stuffs the thread pointer into TLS.
   1115  */
   1116 static void setThreadSelf(Thread* thread)
   1117 {
   1118     int cc;
   1119 
   1120     cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
   1121     if (cc != 0) {
   1122         /*
   1123          * Sometimes this fails under Bionic with EINVAL during shutdown.
   1124          * This can happen if the timing is just right, e.g. a thread
   1125          * fails to attach during shutdown, but the "fail" path calls
   1126          * here to ensure we clean up after ourselves.
   1127          */
   1128         if (thread != NULL) {
   1129             LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
   1130             dvmAbort();     /* the world is fundamentally hosed */
   1131         }
   1132     }
   1133 }
   1134 
   1135 /*
   1136  * This is associated with the pthreadKeySelf key.  It's called by the
   1137  * pthread library when a thread is exiting and the "self" pointer in TLS
   1138  * is non-NULL, meaning the VM hasn't had a chance to clean up.  In normal
   1139  * operation this will not be called.
   1140  *
   1141  * This is mainly of use to ensure that we don't leak resources if, for
   1142  * example, a thread attaches itself to us with AttachCurrentThread and
   1143  * then exits without notifying the VM.
   1144  *
   1145  * We could do the detach here instead of aborting, but this will lead to
   1146  * portability problems.  Other implementations do not do this check and
   1147  * will simply be unaware that the thread has exited, leading to resource
   1148  * leaks (and, if this is a non-daemon thread, an infinite hang when the
   1149  * VM tries to shut down).
   1150  *
   1151  * Because some implementations may want to use the pthread destructor
   1152  * to initiate the detach, and the ordering of destructors is not defined,
   1153  * we want to iterate a couple of times to give those a chance to run.
   1154  */
   1155 static void threadExitCheck(void* arg)
   1156 {
   1157     const int kMaxCount = 2;
   1158 
   1159     Thread* self = (Thread*) arg;
   1160     assert(self != NULL);
   1161 
   1162     LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
   1163         self->threadId, arg, self->threadExitCheckCount);
   1164 
   1165     if (self->status == THREAD_ZOMBIE) {
   1166         LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
   1167             self->threadId);
   1168         return;
   1169     }
   1170 
   1171     if (self->threadExitCheckCount < kMaxCount) {
   1172         /*
   1173          * Spin a couple of times to let other destructors fire.
   1174          */
   1175         LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
   1176             self->threadId, self->threadExitCheckCount);
   1177         self->threadExitCheckCount++;
   1178         int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
   1179         if (cc != 0) {
   1180             LOGE("threadid=%d: unable to re-add thread to TLS\n",
   1181                 self->threadId);
   1182             dvmAbort();
   1183         }
   1184     } else {
   1185         LOGE("threadid=%d: native thread exited without detaching\n",
   1186             self->threadId);
   1187         dvmAbort();
   1188     }
   1189 }
   1190 
   1191 
   1192 /*
   1193  * Assign the threadId.  This needs to be a small integer so that our
   1194  * "thin" locks fit in a small number of bits.
   1195  *
   1196  * We reserve zero for use as an invalid ID.
   1197  *
   1198  * This must be called with threadListLock held (unless we're still
   1199  * initializing the system).
   1200  */
   1201 static void assignThreadId(Thread* thread)
   1202 {
   1203     /*
   1204      * Find a small unique integer.  threadIdMap is a vector of
   1205      * kMaxThreadId bits;  dvmAllocBit() returns the index of a
   1206      * bit, meaning that it will always be < kMaxThreadId.
   1207      */
   1208     int num = dvmAllocBit(gDvm.threadIdMap);
   1209     if (num < 0) {
   1210         LOGE("Ran out of thread IDs\n");
   1211         dvmAbort();     // TODO: make this a non-fatal error result
   1212     }
   1213 
   1214     thread->threadId = num + 1;
   1215 
   1216     assert(thread->threadId != 0);
   1217     assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
   1218 }
   1219 
   1220 /*
   1221  * Give back the thread ID.
   1222  */
   1223 static void releaseThreadId(Thread* thread)
   1224 {
   1225     assert(thread->threadId > 0);
   1226     dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
   1227     thread->threadId = 0;
   1228 }
   1229 
   1230 
   1231 /*
   1232  * Add a stack frame that makes it look like the native code in the main
   1233  * thread was originally invoked from interpreted code.  This gives us a
   1234  * place to hang JNI local references.  The VM spec says (v2 5.2) that the
   1235  * VM begins by executing "main" in a class, so in a way this brings us
   1236  * closer to the spec.
   1237  */
   1238 static bool createFakeEntryFrame(Thread* thread)
   1239 {
   1240     assert(thread->threadId == kMainThreadId);      // main thread only
   1241 
   1242     /* find the method on first use */
   1243     if (gDvm.methFakeNativeEntry == NULL) {
   1244         ClassObject* nativeStart;
   1245         Method* mainMeth;
   1246 
   1247         nativeStart = dvmFindSystemClassNoInit(
   1248                 "Ldalvik/system/NativeStart;");
   1249         if (nativeStart == NULL) {
   1250             LOGE("Unable to find dalvik.system.NativeStart class\n");
   1251             return false;
   1252         }
   1253 
   1254         /*
   1255          * Because we are creating a frame that represents application code, we
   1256          * want to stuff the application class loader into the method's class
   1257          * loader field, even though we're using the system class loader to
   1258          * load it.  This makes life easier over in JNI FindClass (though it
   1259          * could bite us in other ways).
   1260          *
   1261          * Unfortunately this is occurring too early in the initialization,
   1262          * of necessity coming before JNI is initialized, and we're not quite
   1263          * ready to set up the application class loader.
   1264          *
   1265          * So we save a pointer to the method in gDvm.methFakeNativeEntry
   1266          * and check it in FindClass.  The method is private so nobody else
   1267          * can call it.
   1268          */
   1269         //nativeStart->classLoader = dvmGetSystemClassLoader();
   1270 
   1271         mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
   1272                     "main", "([Ljava/lang/String;)V");
   1273         if (mainMeth == NULL) {
   1274             LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
   1275             return false;
   1276         }
   1277 
   1278         gDvm.methFakeNativeEntry = mainMeth;
   1279     }
   1280 
   1281     return dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry);
   1282 }
   1283 
   1284 
   1285 /*
   1286  * Add a stack frame that makes it look like the native thread has been
   1287  * executing interpreted code.  This gives us a place to hang JNI local
   1288  * references.
   1289  */
   1290 static bool createFakeRunFrame(Thread* thread)
   1291 {
   1292     ClassObject* nativeStart;
   1293     Method* runMeth;
   1294 
   1295     nativeStart =
   1296         dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
   1297     if (nativeStart == NULL) {
   1298         LOGE("Unable to find dalvik.system.NativeStart class\n");
   1299         return false;
   1300     }
   1301 
   1302     runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
   1303     if (runMeth == NULL) {
   1304         LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
   1305         return false;
   1306     }
   1307 
   1308     return dvmPushJNIFrame(thread, runMeth);
   1309 }
   1310 
   1311 /*
   1312  * Helper function to set the name of the current thread
   1313  */
   1314 static void setThreadName(const char *threadName)
   1315 {
   1316 #if defined(HAVE_PRCTL)
   1317     int hasAt = 0;
   1318     int hasDot = 0;
   1319     const char *s = threadName;
   1320     while (*s) {
   1321         if (*s == '.') hasDot = 1;
   1322         else if (*s == '@') hasAt = 1;
   1323         s++;
   1324     }
   1325     int len = s - threadName;
   1326     if (len < 15 || hasAt || !hasDot) {
   1327         s = threadName;
   1328     } else {
   1329         s = threadName + len - 15;
   1330     }
   1331     prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
   1332 #endif
   1333 }
   1334 
   1335 /*
   1336  * Create a thread as a result of java.lang.Thread.start().
   1337  *
   1338  * We do have to worry about some concurrency problems, e.g. programs
   1339  * that try to call Thread.start() on the same object from multiple threads.
   1340  * (This will fail for all but one, but we have to make sure that it succeeds
   1341  * for exactly one.)
   1342  *
   1343  * Some of the complexity here arises from our desire to mimic the
   1344  * Thread vs. VMThread class decomposition we inherited.  We've been given
   1345  * a Thread, and now we need to create a VMThread and then populate both
   1346  * objects.  We also need to create one of our internal Thread objects.
   1347  *
   1348  * Pass in a stack size of 0 to get the default.
   1349  */
   1350 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
   1351 {
   1352     pthread_attr_t threadAttr;
   1353     pthread_t threadHandle;
   1354     Thread* self;
   1355     Thread* newThread = NULL;
   1356     Object* vmThreadObj = NULL;
   1357     int stackSize;
   1358 
   1359     assert(threadObj != NULL);
   1360 
   1361     if(gDvm.zygote) {
   1362         // Allow the sampling profiler thread. We shut it down before forking.
   1363         StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
   1364                     gDvm.offJavaLangThread_name);
   1365         char* threadName = dvmCreateCstrFromString(nameStr);
   1366         bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
   1367         free(threadName);
   1368         if (!profilerThread) {
   1369             dvmThrowException("Ljava/lang/IllegalStateException;",
   1370                 "No new threads in -Xzygote mode");
   1371 
   1372             goto fail;
   1373         }
   1374     }
   1375 
   1376     self = dvmThreadSelf();
   1377     if (reqStackSize == 0)
   1378         stackSize = gDvm.stackSize;
   1379     else if (reqStackSize < kMinStackSize)
   1380         stackSize = kMinStackSize;
   1381     else if (reqStackSize > kMaxStackSize)
   1382         stackSize = kMaxStackSize;
   1383     else
   1384         stackSize = reqStackSize;
   1385 
   1386     pthread_attr_init(&threadAttr);
   1387     pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
   1388 
   1389     /*
   1390      * To minimize the time spent in the critical section, we allocate the
   1391      * vmThread object here.
   1392      */
   1393     vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
   1394     if (vmThreadObj == NULL)
   1395         goto fail;
   1396 
   1397     newThread = allocThread(stackSize);
   1398     if (newThread == NULL)
   1399         goto fail;
   1400     newThread->threadObj = threadObj;
   1401 
   1402     assert(newThread->status == THREAD_INITIALIZING);
   1403 
   1404     /*
   1405      * We need to lock out other threads while we test and set the
   1406      * "vmThread" field in java.lang.Thread, because we use that to determine
   1407      * if this thread has been started before.  We use the thread list lock
   1408      * because it's handy and we're going to need to grab it again soon
   1409      * anyway.
   1410      */
   1411     dvmLockThreadList(self);
   1412 
   1413     if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
   1414         dvmUnlockThreadList();
   1415         dvmThrowException("Ljava/lang/IllegalThreadStateException;",
   1416             "thread has already been started");
   1417         goto fail;
   1418     }
   1419 
   1420     /*
   1421      * There are actually three data structures: Thread (object), VMThread
   1422      * (object), and Thread (C struct).  All of them point to at least one
   1423      * other.
   1424      *
   1425      * As soon as "VMThread.vmData" is assigned, other threads can start
   1426      * making calls into us (e.g. setPriority).
   1427      */
   1428     dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
   1429     dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
   1430 
   1431     /*
   1432      * Thread creation might take a while, so release the lock.
   1433      */
   1434     dvmUnlockThreadList();
   1435 
   1436     int cc, oldStatus;
   1437     oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
   1438     cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
   1439             newThread);
   1440     oldStatus = dvmChangeStatus(self, oldStatus);
   1441 
   1442     if (cc != 0) {
   1443         /*
   1444          * Failure generally indicates that we have exceeded system
   1445          * resource limits.  VirtualMachineError is probably too severe,
   1446          * so use OutOfMemoryError.
   1447          */
   1448         LOGE("Thread creation failed (err=%s)\n", strerror(errno));
   1449 
   1450         dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
   1451 
   1452         dvmThrowException("Ljava/lang/OutOfMemoryError;",
   1453             "thread creation failed");
   1454         goto fail;
   1455     }
   1456 
   1457     /*
   1458      * We need to wait for the thread to start.  Otherwise, depending on
   1459      * the whims of the OS scheduler, we could return and the code in our
   1460      * thread could try to do operations on the new thread before it had
   1461      * finished starting.
   1462      *
   1463      * The new thread will lock the thread list, change its state to
   1464      * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
   1465      * on gDvm.threadStartCond (which uses the thread list lock).  This
   1466      * thread (the parent) will either see that the thread is already ready
   1467      * after we grab the thread list lock, or will be awakened from the
   1468      * condition variable on the broadcast.
   1469      *
   1470      * We don't want to stall the rest of the VM while the new thread
   1471      * starts, which can happen if the GC wakes up at the wrong moment.
   1472      * So, we change our own status to VMWAIT, and self-suspend if
   1473      * necessary after we finish adding the new thread.
   1474      *
   1475      *
   1476      * We have to deal with an odd race with the GC/debugger suspension
   1477      * mechanism when creating a new thread.  The information about whether
   1478      * or not a thread should be suspended is contained entirely within
   1479      * the Thread struct; this is usually cleaner to deal with than having
   1480      * one or more globally-visible suspension flags.  The trouble is that
   1481      * we could create the thread while the VM is trying to suspend all
   1482      * threads.  The suspend-count won't be nonzero for the new thread,
   1483      * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
   1484      *
   1485      * The easiest way to deal with this is to prevent the new thread from
   1486      * running until the parent says it's okay.  This results in the
   1487      * following (correct) sequence of events for a "badly timed" GC
   1488      * (where '-' is us, 'o' is the child, and '+' is some other thread):
   1489      *
   1490      *  - call pthread_create()
   1491      *  - lock thread list
   1492      *  - put self into THREAD_VMWAIT so GC doesn't wait for us
   1493      *  - sleep on condition var (mutex = thread list lock) until child starts
   1494      *  + GC triggered by another thread
   1495      *  + thread list locked; suspend counts updated; thread list unlocked
   1496      *  + loop waiting for all runnable threads to suspend
   1497      *  + success, start GC
   1498      *  o child thread wakes, signals condition var to wake parent
   1499      *  o child waits for parent ack on condition variable
   1500      *  - we wake up, locking thread list
   1501      *  - add child to thread list
   1502      *  - unlock thread list
   1503      *  - change our state back to THREAD_RUNNING; GC causes us to suspend
   1504      *  + GC finishes; all threads in thread list are resumed
   1505      *  - lock thread list
   1506      *  - set child to THREAD_VMWAIT, and signal it to start
   1507      *  - unlock thread list
   1508      *  o child resumes
   1509      *  o child changes state to THREAD_RUNNING
   1510      *
   1511      * The above shows the GC starting up during thread creation, but if
   1512      * it starts anywhere after VMThread.create() is called it will
   1513      * produce the same series of events.
   1514      *
   1515      * Once the child is in the thread list, it will be suspended and
   1516      * resumed like any other thread.  In the above scenario the resume-all
   1517      * code will try to resume the new thread, which was never actually
   1518      * suspended, and try to decrement the child's thread suspend count to -1.
   1519      * We can catch this in the resume-all code.
   1520      *
   1521      * Bouncing back and forth between threads like this adds a small amount
   1522      * of scheduler overhead to thread startup.
   1523      *
   1524      * One alternative to having the child wait for the parent would be
   1525      * to have the child inherit the parents' suspension count.  This
   1526      * would work for a GC, since we can safely assume that the parent
   1527      * thread didn't cause it, but we must only do so if the parent suspension
   1528      * was caused by a suspend-all.  If the parent was being asked to
   1529      * suspend singly by the debugger, the child should not inherit the value.
   1530      *
   1531      * We could also have a global "new thread suspend count" that gets
   1532      * picked up by new threads before changing state to THREAD_RUNNING.
   1533      * This would be protected by the thread list lock and set by a
   1534      * suspend-all.
   1535      */
   1536     dvmLockThreadList(self);
   1537     assert(self->status == THREAD_RUNNING);
   1538     self->status = THREAD_VMWAIT;
   1539     while (newThread->status != THREAD_STARTING)
   1540         pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
   1541 
   1542     LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
   1543     newThread->next = gDvm.threadList->next;
   1544     if (newThread->next != NULL)
   1545         newThread->next->prev = newThread;
   1546     newThread->prev = gDvm.threadList;
   1547     gDvm.threadList->next = newThread;
   1548 
   1549     if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
   1550         gDvm.nonDaemonThreadCount++;        // guarded by thread list lock
   1551 
   1552     dvmUnlockThreadList();
   1553 
   1554     /* change status back to RUNNING, self-suspending if necessary */
   1555     dvmChangeStatus(self, THREAD_RUNNING);
   1556 
   1557     /*
   1558      * Tell the new thread to start.
   1559      *
   1560      * We must hold the thread list lock before messing with another thread.
   1561      * In the general case we would also need to verify that newThread was
   1562      * still in the thread list, but in our case the thread has not started
   1563      * executing user code and therefore has not had a chance to exit.
   1564      *
   1565      * We move it to VMWAIT, and it then shifts itself to RUNNING, which
   1566      * comes with a suspend-pending check.
   1567      */
   1568     dvmLockThreadList(self);
   1569 
   1570     assert(newThread->status == THREAD_STARTING);
   1571     newThread->status = THREAD_VMWAIT;
   1572     pthread_cond_broadcast(&gDvm.threadStartCond);
   1573 
   1574     dvmUnlockThreadList();
   1575 
   1576     dvmReleaseTrackedAlloc(vmThreadObj, NULL);
   1577     return true;
   1578 
   1579 fail:
   1580     freeThread(newThread);
   1581     dvmReleaseTrackedAlloc(vmThreadObj, NULL);
   1582     return false;
   1583 }
   1584 
   1585 /*
   1586  * pthread entry function for threads started from interpreted code.
   1587  */
   1588 static void* interpThreadStart(void* arg)
   1589 {
   1590     Thread* self = (Thread*) arg;
   1591 
   1592     char *threadName = dvmGetThreadName(self);
   1593     setThreadName(threadName);
   1594     free(threadName);
   1595 
   1596     /*
   1597      * Finish initializing the Thread struct.
   1598      */
   1599     prepareThread(self);
   1600 
   1601     LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
   1602 
   1603     /*
   1604      * Change our status and wake our parent, who will add us to the
   1605      * thread list and advance our state to VMWAIT.
   1606      */
   1607     dvmLockThreadList(self);
   1608     self->status = THREAD_STARTING;
   1609     pthread_cond_broadcast(&gDvm.threadStartCond);
   1610 
   1611     /*
   1612      * Wait until the parent says we can go.  Assuming there wasn't a
   1613      * suspend pending, this will happen immediately.  When it completes,
   1614      * we're full-fledged citizens of the VM.
   1615      *
   1616      * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
   1617      * because the pthread_cond_wait below needs to reacquire a lock that
   1618      * suspend-all is also interested in.  If we get unlucky, the parent could
   1619      * change us to THREAD_RUNNING, then a GC could start before we get
   1620      * signaled, and suspend-all will grab the thread list lock and then
   1621      * wait for us to suspend.  We'll be in the tail end of pthread_cond_wait
   1622      * trying to get the lock.
   1623      */
   1624     while (self->status != THREAD_VMWAIT)
   1625         pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
   1626 
   1627     dvmUnlockThreadList();
   1628 
   1629     /*
   1630      * Add a JNI context.
   1631      */
   1632     self->jniEnv = dvmCreateJNIEnv(self);
   1633 
   1634     /*
   1635      * Change our state so the GC will wait for us from now on.  If a GC is
   1636      * in progress this call will suspend us.
   1637      */
   1638     dvmChangeStatus(self, THREAD_RUNNING);
   1639 
   1640     /*
   1641      * Notify the debugger & DDM.  The debugger notification may cause
   1642      * us to suspend ourselves (and others).
   1643      */
   1644     if (gDvm.debuggerConnected)
   1645         dvmDbgPostThreadStart(self);
   1646 
   1647     /*
   1648      * Set the system thread priority according to the Thread object's
   1649      * priority level.  We don't usually need to do this, because both the
   1650      * Thread object and system thread priorities inherit from parents.  The
   1651      * tricky case is when somebody creates a Thread object, calls
   1652      * setPriority(), and then starts the thread.  We could manage this with
   1653      * a "needs priority update" flag to avoid the redundant call.
   1654      */
   1655     int priority = dvmGetFieldInt(self->threadObj,
   1656                         gDvm.offJavaLangThread_priority);
   1657     dvmChangeThreadPriority(self, priority);
   1658 
   1659     /*
   1660      * Execute the "run" method.
   1661      *
   1662      * At this point our stack is empty, so somebody who comes looking for
   1663      * stack traces right now won't have much to look at.  This is normal.
   1664      */
   1665     Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
   1666     JValue unused;
   1667 
   1668     LOGV("threadid=%d: calling run()\n", self->threadId);
   1669     assert(strcmp(run->name, "run") == 0);
   1670     dvmCallMethod(self, run, self->threadObj, &unused);
   1671     LOGV("threadid=%d: exiting\n", self->threadId);
   1672 
   1673     /*
   1674      * Remove the thread from various lists, report its death, and free
   1675      * its resources.
   1676      */
   1677     dvmDetachCurrentThread();
   1678 
   1679     return NULL;
   1680 }
   1681 
   1682 /*
   1683  * The current thread is exiting with an uncaught exception.  The
   1684  * Java programming language allows the application to provide a
   1685  * thread-exit-uncaught-exception handler for the VM, for a specific
   1686  * Thread, and for all threads in a ThreadGroup.
   1687  *
   1688  * Version 1.5 added the per-thread handler.  We need to call
   1689  * "uncaughtException" in the handler object, which is either the
   1690  * ThreadGroup object or the Thread-specific handler.
   1691  */
   1692 static void threadExitUncaughtException(Thread* self, Object* group)
   1693 {
   1694     Object* exception;
   1695     Object* handlerObj;
   1696     ClassObject* throwable;
   1697     Method* uncaughtHandler = NULL;
   1698     InstField* threadHandler;
   1699 
   1700     LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
   1701         self->threadId, group);
   1702     assert(group != NULL);
   1703 
   1704     /*
   1705      * Get a pointer to the exception, then clear out the one in the
   1706      * thread.  We don't want to have it set when executing interpreted code.
   1707      */
   1708     exception = dvmGetException(self);
   1709     dvmAddTrackedAlloc(exception, self);
   1710     dvmClearException(self);
   1711 
   1712     /*
   1713      * Get the Thread's "uncaughtHandler" object.  Use it if non-NULL;
   1714      * else use "group" (which is an instance of UncaughtExceptionHandler).
   1715      */
   1716     threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
   1717             "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
   1718     if (threadHandler == NULL) {
   1719         LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
   1720         goto bail;
   1721     }
   1722     handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
   1723     if (handlerObj == NULL)
   1724         handlerObj = group;
   1725 
   1726     /*
   1727      * Find the "uncaughtHandler" field in this object.
   1728      */
   1729     uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
   1730             "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
   1731 
   1732     if (uncaughtHandler != NULL) {
   1733         //LOGI("+++ calling %s.uncaughtException\n",
   1734         //     handlerObj->clazz->descriptor);
   1735         JValue unused;
   1736         dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
   1737             self->threadObj, exception);
   1738     } else {
   1739         /* restore it and dump a stack trace */
   1740         LOGW("WARNING: no 'uncaughtException' method in class %s\n",
   1741             handlerObj->clazz->descriptor);
   1742         dvmSetException(self, exception);
   1743         dvmLogExceptionStackTrace();
   1744     }
   1745 
   1746 bail:
   1747 #if defined(WITH_JIT)
   1748     /* Remove this thread's suspendCount from global suspendCount sum */
   1749     lockThreadSuspendCount();
   1750     dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
   1751     unlockThreadSuspendCount();
   1752 #endif
   1753     dvmReleaseTrackedAlloc(exception, self);
   1754 }
   1755 
   1756 
   1757 /*
   1758  * Create an internal VM thread, for things like JDWP and finalizers.
   1759  *
   1760  * The easiest way to do this is create a new thread and then use the
   1761  * JNI AttachCurrentThread implementation.
   1762  *
   1763  * This does not return until after the new thread has begun executing.
   1764  */
   1765 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
   1766     InternalThreadStart func, void* funcArg)
   1767 {
   1768     InternalStartArgs* pArgs;
   1769     Object* systemGroup;
   1770     pthread_attr_t threadAttr;
   1771     volatile Thread* newThread = NULL;
   1772     volatile int createStatus = 0;
   1773 
   1774     systemGroup = dvmGetSystemThreadGroup();
   1775     if (systemGroup == NULL)
   1776         return false;
   1777 
   1778     pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
   1779     pArgs->func = func;
   1780     pArgs->funcArg = funcArg;
   1781     pArgs->name = strdup(name);     // storage will be owned by new thread
   1782     pArgs->group = systemGroup;
   1783     pArgs->isDaemon = true;
   1784     pArgs->pThread = &newThread;
   1785     pArgs->pCreateStatus = &createStatus;
   1786 
   1787     pthread_attr_init(&threadAttr);
   1788     //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
   1789 
   1790     if (pthread_create(pHandle, &threadAttr, internalThreadStart,
   1791             pArgs) != 0)
   1792     {
   1793         LOGE("internal thread creation failed\n");
   1794         free(pArgs->name);
   1795         free(pArgs);
   1796         return false;
   1797     }
   1798 
   1799     /*
   1800      * Wait for the child to start.  This gives us an opportunity to make
   1801      * sure that the thread started correctly, and allows our caller to
   1802      * assume that the thread has started running.
   1803      *
   1804      * Because we aren't holding a lock across the thread creation, it's
   1805      * possible that the child will already have completed its
   1806      * initialization.  Because the child only adjusts "createStatus" while
   1807      * holding the thread list lock, the initial condition on the "while"
   1808      * loop will correctly avoid the wait if this occurs.
   1809      *
   1810      * It's also possible that we'll have to wait for the thread to finish
   1811      * being created, and as part of allocating a Thread object it might
   1812      * need to initiate a GC.  We switch to VMWAIT while we pause.
   1813      */
   1814     Thread* self = dvmThreadSelf();
   1815     int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
   1816     dvmLockThreadList(self);
   1817     while (createStatus == 0)
   1818         pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
   1819 
   1820     if (newThread == NULL) {
   1821         LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
   1822         assert(createStatus < 0);
   1823         /* don't free pArgs -- if pthread_create succeeded, child owns it */
   1824         dvmUnlockThreadList();
   1825         dvmChangeStatus(self, oldStatus);
   1826         return false;
   1827     }
   1828 
   1829     /* thread could be in any state now (except early init states) */
   1830     //assert(newThread->status == THREAD_RUNNING);
   1831 
   1832     dvmUnlockThreadList();
   1833     dvmChangeStatus(self, oldStatus);
   1834 
   1835     return true;
   1836 }
   1837 
   1838 /*
   1839  * pthread entry function for internally-created threads.
   1840  *
   1841  * We are expected to free "arg" and its contents.  If we're a daemon
   1842  * thread, and we get cancelled abruptly when the VM shuts down, the
   1843  * storage won't be freed.  If this becomes a concern we can make a copy
   1844  * on the stack.
   1845  */
   1846 static void* internalThreadStart(void* arg)
   1847 {
   1848     InternalStartArgs* pArgs = (InternalStartArgs*) arg;
   1849     JavaVMAttachArgs jniArgs;
   1850 
   1851     jniArgs.version = JNI_VERSION_1_2;
   1852     jniArgs.name = pArgs->name;
   1853     jniArgs.group = pArgs->group;
   1854 
   1855     setThreadName(pArgs->name);
   1856 
   1857     /* use local jniArgs as stack top */
   1858     if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
   1859         /*
   1860          * Tell the parent of our success.
   1861          *
   1862          * threadListLock is the mutex for threadStartCond.
   1863          */
   1864         dvmLockThreadList(dvmThreadSelf());
   1865         *pArgs->pCreateStatus = 1;
   1866         *pArgs->pThread = dvmThreadSelf();
   1867         pthread_cond_broadcast(&gDvm.threadStartCond);
   1868         dvmUnlockThreadList();
   1869 
   1870         LOG_THREAD("threadid=%d: internal '%s'\n",
   1871             dvmThreadSelf()->threadId, pArgs->name);
   1872 
   1873         /* execute */
   1874         (*pArgs->func)(pArgs->funcArg);
   1875 
   1876         /* detach ourselves */
   1877         dvmDetachCurrentThread();
   1878     } else {
   1879         /*
   1880          * Tell the parent of our failure.  We don't have a Thread struct,
   1881          * so we can't be suspended, so we don't need to enter a critical
   1882          * section.
   1883          */
   1884         dvmLockThreadList(dvmThreadSelf());
   1885         *pArgs->pCreateStatus = -1;
   1886         assert(*pArgs->pThread == NULL);
   1887         pthread_cond_broadcast(&gDvm.threadStartCond);
   1888         dvmUnlockThreadList();
   1889 
   1890         assert(*pArgs->pThread == NULL);
   1891     }
   1892 
   1893     free(pArgs->name);
   1894     free(pArgs);
   1895     return NULL;
   1896 }
   1897 
   1898 /*
   1899  * Attach the current thread to the VM.
   1900  *
   1901  * Used for internally-created threads and JNI's AttachCurrentThread.
   1902  */
   1903 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
   1904 {
   1905     Thread* self = NULL;
   1906     Object* threadObj = NULL;
   1907     Object* vmThreadObj = NULL;
   1908     StringObject* threadNameStr = NULL;
   1909     Method* init;
   1910     bool ok, ret;
   1911 
   1912     /* establish a basic sense of self */
   1913     self = allocThread(gDvm.stackSize);
   1914     if (self == NULL)
   1915         goto fail;
   1916     setThreadSelf(self);
   1917 
   1918     /*
   1919      * Create Thread and VMThread objects.  We have to use ALLOC_NO_GC
   1920      * because this thread is not yet visible to the VM.  We could also
   1921      * just grab the GC lock earlier, but that leaves us executing
   1922      * interpreted code with the lock held, which is not prudent.
   1923      *
   1924      * The alloc calls will block if a GC is in progress, so we don't need
   1925      * to check for global suspension here.
   1926      *
   1927      * It's also possible for the allocation calls to *cause* a GC.
   1928      */
   1929     //BUG: deadlock if a GC happens here during HeapWorker creation
   1930     threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_NO_GC);
   1931     if (threadObj == NULL)
   1932         goto fail;
   1933     vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_NO_GC);
   1934     if (vmThreadObj == NULL)
   1935         goto fail;
   1936 
   1937     self->threadObj = threadObj;
   1938     dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
   1939 
   1940     /*
   1941      * Do some java.lang.Thread constructor prep before we lock stuff down.
   1942      */
   1943     if (pArgs->name != NULL) {
   1944         threadNameStr = dvmCreateStringFromCstr(pArgs->name, ALLOC_NO_GC);
   1945         if (threadNameStr == NULL) {
   1946             assert(dvmCheckException(dvmThreadSelf()));
   1947             goto fail;
   1948         }
   1949     }
   1950 
   1951     init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
   1952             "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
   1953     if (init == NULL) {
   1954         assert(dvmCheckException(dvmThreadSelf()));
   1955         goto fail;
   1956     }
   1957 
   1958     /*
   1959      * Finish our thread prep.  We need to do this before invoking any
   1960      * interpreted code.  prepareThread() requires that we hold the thread
   1961      * list lock.
   1962      */
   1963     dvmLockThreadList(self);
   1964     ok = prepareThread(self);
   1965     dvmUnlockThreadList();
   1966     if (!ok)
   1967         goto fail;
   1968 
   1969     self->jniEnv = dvmCreateJNIEnv(self);
   1970     if (self->jniEnv == NULL)
   1971         goto fail;
   1972 
   1973     /*
   1974      * Create a "fake" JNI frame at the top of the main thread interp stack.
   1975      * It isn't really necessary for the internal threads, but it gives
   1976      * the debugger something to show.  It is essential for the JNI-attached
   1977      * threads.
   1978      */
   1979     if (!createFakeRunFrame(self))
   1980         goto fail;
   1981 
   1982     /*
   1983      * The native side of the thread is ready;  add it to the list.
   1984      */
   1985     LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
   1986 
   1987     /* Start off in VMWAIT, because we may be about to block
   1988      * on the heap lock, and we don't want any suspensions
   1989      * to wait for us.
   1990      */
   1991     self->status = THREAD_VMWAIT;
   1992 
   1993     /*
   1994      * Add ourselves to the thread list.  Once we finish here we are
   1995      * visible to the debugger and the GC.
   1996      */
   1997     dvmLockThreadList(self);
   1998 
   1999     self->next = gDvm.threadList->next;
   2000     if (self->next != NULL)
   2001         self->next->prev = self;
   2002     self->prev = gDvm.threadList;
   2003     gDvm.threadList->next = self;
   2004     if (!isDaemon)
   2005         gDvm.nonDaemonThreadCount++;
   2006 
   2007     dvmUnlockThreadList();
   2008 
   2009     /*
   2010      * It's possible that a GC is currently running.  Our thread
   2011      * wasn't in the list when the GC started, so it's not properly
   2012      * suspended in that case.  Synchronize on the heap lock (held
   2013      * when a GC is happening) to guarantee that any GCs from here
   2014      * on will see this thread in the list.
   2015      */
   2016     dvmLockMutex(&gDvm.gcHeapLock);
   2017     dvmUnlockMutex(&gDvm.gcHeapLock);
   2018 
   2019     /*
   2020      * Switch to the running state now that we're ready for
   2021      * suspensions.  This call may suspend.
   2022      */
   2023     dvmChangeStatus(self, THREAD_RUNNING);
   2024 
   2025     /*
   2026      * Now we're ready to run some interpreted code.
   2027      *
   2028      * We need to construct the Thread object and set the VMThread field.
   2029      * Setting VMThread tells interpreted code that we're alive.
   2030      *
   2031      * Call the (group, name, priority, daemon) constructor on the Thread.
   2032      * This sets the thread's name and adds it to the specified group, and
   2033      * provides values for priority and daemon (which are normally inherited
   2034      * from the current thread).
   2035      */
   2036     JValue unused;
   2037     dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
   2038         threadNameStr, getThreadPriorityFromSystem(), isDaemon);
   2039     if (dvmCheckException(self)) {
   2040         LOGE("exception thrown while constructing attached thread object\n");
   2041         goto fail_unlink;
   2042     }
   2043     //if (isDaemon)
   2044     //    dvmSetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon, true);
   2045 
   2046     /*
   2047      * Set the VMThread field, which tells interpreted code that we're alive.
   2048      *
   2049      * The risk of a thread start collision here is very low; somebody
   2050      * would have to be deliberately polling the ThreadGroup list and
   2051      * trying to start threads against anything it sees, which would
   2052      * generally cause problems for all thread creation.  However, for
   2053      * correctness we test "vmThread" before setting it.
   2054      */
   2055     if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
   2056         dvmThrowException("Ljava/lang/IllegalThreadStateException;",
   2057             "thread has already been started");
   2058         /* We don't want to free anything associated with the thread
   2059          * because someone is obviously interested in it.  Just let
   2060          * it go and hope it will clean itself up when its finished.
   2061          * This case should never happen anyway.
   2062          *
   2063          * Since we're letting it live, we need to finish setting it up.
   2064          * We just have to let the caller know that the intended operation
   2065          * has failed.
   2066          *
   2067          * [ This seems strange -- stepping on the vmThread object that's
   2068          * already present seems like a bad idea.  TODO: figure this out. ]
   2069          */
   2070         ret = false;
   2071     } else
   2072         ret = true;
   2073     dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
   2074 
   2075     /* These are now reachable from the thread groups. */
   2076     dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
   2077     dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
   2078 
   2079     /*
   2080      * The thread is ready to go;  let the debugger see it.
   2081      */
   2082     self->threadObj = threadObj;
   2083 
   2084     LOG_THREAD("threadid=%d: attached from native, name=%s\n",
   2085         self->threadId, pArgs->name);
   2086 
   2087     /* tell the debugger & DDM */
   2088     if (gDvm.debuggerConnected)
   2089         dvmDbgPostThreadStart(self);
   2090 
   2091     return ret;
   2092 
   2093 fail_unlink:
   2094     dvmLockThreadList(self);
   2095     unlinkThread(self);
   2096     if (!isDaemon)
   2097         gDvm.nonDaemonThreadCount--;
   2098     dvmUnlockThreadList();
   2099     /* fall through to "fail" */
   2100 fail:
   2101     dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
   2102     dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
   2103     if (self != NULL) {
   2104         if (self->jniEnv != NULL) {
   2105             dvmDestroyJNIEnv(self->jniEnv);
   2106             self->jniEnv = NULL;
   2107         }
   2108         freeThread(self);
   2109     }
   2110     setThreadSelf(NULL);
   2111     return false;
   2112 }
   2113 
   2114 /*
   2115  * Detach the thread from the various data structures, notify other threads
   2116  * that are waiting to "join" it, and free up all heap-allocated storage.
   2117  *
   2118  * Used for all threads.
   2119  *
   2120  * When we get here the interpreted stack should be empty.  The JNI 1.6 spec
   2121  * requires us to enforce this for the DetachCurrentThread call, probably
   2122  * because it also says that DetachCurrentThread causes all monitors
   2123  * associated with the thread to be released.  (Because the stack is empty,
   2124  * we only have to worry about explicit JNI calls to MonitorEnter.)
   2125  *
   2126  * THOUGHT:
   2127  * We might want to avoid freeing our internal Thread structure until the
   2128  * associated Thread/VMThread objects get GCed.  Our Thread is impossible to
   2129  * get to once the thread shuts down, but there is a small possibility of
   2130  * an operation starting in another thread before this thread halts, and
   2131  * finishing much later (perhaps the thread got stalled by a weird OS bug).
   2132  * We don't want something like Thread.isInterrupted() crawling through
   2133  * freed storage.  Can do with a Thread finalizer, or by creating a
   2134  * dedicated ThreadObject class for java/lang/Thread and moving all of our
   2135  * state into that.
   2136  */
   2137 void dvmDetachCurrentThread(void)
   2138 {
   2139     Thread* self = dvmThreadSelf();
   2140     Object* vmThread;
   2141     Object* group;
   2142 
   2143     /*
   2144      * Make sure we're not detaching a thread that's still running.  (This
   2145      * could happen with an explicit JNI detach call.)
   2146      *
   2147      * A thread created by interpreted code will finish with a depth of
   2148      * zero, while a JNI-attached thread will have the synthetic "stack
   2149      * starter" native method at the top.
   2150      */
   2151     int curDepth = dvmComputeExactFrameDepth(self->curFrame);
   2152     if (curDepth != 0) {
   2153         bool topIsNative = false;
   2154 
   2155         if (curDepth == 1) {
   2156             /* not expecting a lingering break frame; just look at curFrame */
   2157             assert(!dvmIsBreakFrame(self->curFrame));
   2158             StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
   2159             if (dvmIsNativeMethod(ssa->method))
   2160                 topIsNative = true;
   2161         }
   2162 
   2163         if (!topIsNative) {
   2164             LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
   2165                 curDepth);
   2166             dvmDumpThread(self, false);
   2167             dvmAbort();
   2168         }
   2169     }
   2170 
   2171     group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
   2172     LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
   2173 
   2174     /*
   2175      * Release any held monitors.  Since there are no interpreted stack
   2176      * frames, the only thing left are the monitors held by JNI MonitorEnter
   2177      * calls.
   2178      */
   2179     dvmReleaseJniMonitors(self);
   2180 
   2181     /*
   2182      * Do some thread-exit uncaught exception processing if necessary.
   2183      */
   2184     if (dvmCheckException(self))
   2185         threadExitUncaughtException(self, group);
   2186 
   2187     /*
   2188      * Remove the thread from the thread group.
   2189      */
   2190     if (group != NULL) {
   2191         Method* removeThread =
   2192             group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
   2193         JValue unused;
   2194         dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
   2195     }
   2196 
   2197     /*
   2198      * Clear the vmThread reference in the Thread object.  Interpreted code
   2199      * will now see that this Thread is not running.  As this may be the
   2200      * only reference to the VMThread object that the VM knows about, we
   2201      * have to create an internal reference to it first.
   2202      */
   2203     vmThread = dvmGetFieldObject(self->threadObj,
   2204                     gDvm.offJavaLangThread_vmThread);
   2205     dvmAddTrackedAlloc(vmThread, self);
   2206     dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
   2207 
   2208     /* clear out our struct Thread pointer, since it's going away */
   2209     dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
   2210 
   2211     /*
   2212      * Tell the debugger & DDM.  This may cause the current thread or all
   2213      * threads to suspend.
   2214      *
   2215      * The JDWP spec is somewhat vague about when this happens, other than
   2216      * that it's issued by the dying thread, which may still appear in
   2217      * an "all threads" listing.
   2218      */
   2219     if (gDvm.debuggerConnected)
   2220         dvmDbgPostThreadDeath(self);
   2221 
   2222     /*
   2223      * Thread.join() is implemented as an Object.wait() on the VMThread
   2224      * object.  Signal anyone who is waiting.
   2225      */
   2226     dvmLockObject(self, vmThread);
   2227     dvmObjectNotifyAll(self, vmThread);
   2228     dvmUnlockObject(self, vmThread);
   2229 
   2230     dvmReleaseTrackedAlloc(vmThread, self);
   2231     vmThread = NULL;
   2232 
   2233     /*
   2234      * We're done manipulating objects, so it's okay if the GC runs in
   2235      * parallel with us from here out.  It's important to do this if
   2236      * profiling is enabled, since we can wait indefinitely.
   2237      */
   2238     self->status = THREAD_VMWAIT;
   2239 
   2240 #ifdef WITH_PROFILER
   2241     /*
   2242      * If we're doing method trace profiling, we don't want threads to exit,
   2243      * because if they do we'll end up reusing thread IDs.  This complicates
   2244      * analysis and makes it impossible to have reasonable output in the
   2245      * "threads" section of the "key" file.
   2246      *
   2247      * We need to do this after Thread.join() completes, or other threads
   2248      * could get wedged.  Since self->threadObj is still valid, the Thread
   2249      * object will not get GCed even though we're no longer in the ThreadGroup
   2250      * list (which is important since the profiling thread needs to get
   2251      * the thread's name).
   2252      */
   2253     MethodTraceState* traceState = &gDvm.methodTrace;
   2254 
   2255     dvmLockMutex(&traceState->startStopLock);
   2256     if (traceState->traceEnabled) {
   2257         LOGI("threadid=%d: waiting for method trace to finish\n",
   2258             self->threadId);
   2259         while (traceState->traceEnabled) {
   2260             int cc;
   2261             cc = pthread_cond_wait(&traceState->threadExitCond,
   2262                     &traceState->startStopLock);
   2263             assert(cc == 0);
   2264         }
   2265     }
   2266     dvmUnlockMutex(&traceState->startStopLock);
   2267 #endif
   2268 
   2269     dvmLockThreadList(self);
   2270 
   2271     /*
   2272      * Lose the JNI context.
   2273      */
   2274     dvmDestroyJNIEnv(self->jniEnv);
   2275     self->jniEnv = NULL;
   2276 
   2277     self->status = THREAD_ZOMBIE;
   2278 
   2279     /*
   2280      * Remove ourselves from the internal thread list.
   2281      */
   2282     unlinkThread(self);
   2283 
   2284     /*
   2285      * If we're the last one standing, signal anybody waiting in
   2286      * DestroyJavaVM that it's okay to exit.
   2287      */
   2288     if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
   2289         gDvm.nonDaemonThreadCount--;        // guarded by thread list lock
   2290 
   2291         if (gDvm.nonDaemonThreadCount == 0) {
   2292             int cc;
   2293 
   2294             LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
   2295             //dvmDumpAllThreads(false);
   2296             // cond var guarded by threadListLock, which we already hold
   2297             cc = pthread_cond_signal(&gDvm.vmExitCond);
   2298             assert(cc == 0);
   2299         }
   2300     }
   2301 
   2302     LOGV("threadid=%d: bye!\n", self->threadId);
   2303     releaseThreadId(self);
   2304     dvmUnlockThreadList();
   2305 
   2306     setThreadSelf(NULL);
   2307 
   2308     dvmDetachSystemThread(self);
   2309 
   2310     freeThread(self);
   2311 }
   2312 
   2313 
   2314 /*
   2315  * Suspend a single thread.  Do not use to suspend yourself.
   2316  *
   2317  * This is used primarily for debugger/DDMS activity.  Does not return
   2318  * until the thread has suspended or is in a "safe" state (e.g. executing
   2319  * native code outside the VM).
   2320  *
   2321  * The thread list lock should be held before calling here -- it's not
   2322  * entirely safe to hang on to a Thread* from another thread otherwise.
   2323  * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
   2324  */
   2325 void dvmSuspendThread(Thread* thread)
   2326 {
   2327     assert(thread != NULL);
   2328     assert(thread != dvmThreadSelf());
   2329     //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
   2330 
   2331     lockThreadSuspendCount();
   2332     dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
   2333     thread->dbgSuspendCount++;
   2334 
   2335     LOG_THREAD("threadid=%d: suspend++, now=%d\n",
   2336         thread->threadId, thread->suspendCount);
   2337     unlockThreadSuspendCount();
   2338 
   2339     waitForThreadSuspend(dvmThreadSelf(), thread);
   2340 }
   2341 
   2342 /*
   2343  * Reduce the suspend count of a thread.  If it hits zero, tell it to
   2344  * resume.
   2345  *
   2346  * Used primarily for debugger/DDMS activity.  The thread in question
   2347  * might have been suspended singly or as part of a suspend-all operation.
   2348  *
   2349  * The thread list lock should be held before calling here -- it's not
   2350  * entirely safe to hang on to a Thread* from another thread otherwise.
   2351  * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
   2352  */
   2353 void dvmResumeThread(Thread* thread)
   2354 {
   2355     assert(thread != NULL);
   2356     assert(thread != dvmThreadSelf());
   2357     //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
   2358 
   2359     lockThreadSuspendCount();
   2360     if (thread->suspendCount > 0) {
   2361         dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
   2362         thread->dbgSuspendCount--;
   2363     } else {
   2364         LOG_THREAD("threadid=%d:  suspendCount already zero\n",
   2365             thread->threadId);
   2366     }
   2367 
   2368     LOG_THREAD("threadid=%d: suspend--, now=%d\n",
   2369         thread->threadId, thread->suspendCount);
   2370 
   2371     if (thread->suspendCount == 0) {
   2372         int cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
   2373         assert(cc == 0);
   2374     }
   2375 
   2376     unlockThreadSuspendCount();
   2377 }
   2378 
   2379 /*
   2380  * Suspend yourself, as a result of debugger activity.
   2381  */
   2382 void dvmSuspendSelf(bool jdwpActivity)
   2383 {
   2384     Thread* self = dvmThreadSelf();
   2385 
   2386     /* debugger thread may not suspend itself due to debugger activity! */
   2387     assert(gDvm.jdwpState != NULL);
   2388     if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
   2389         assert(false);
   2390         return;
   2391     }
   2392 
   2393     /*
   2394      * Collisions with other suspends aren't really interesting.  We want
   2395      * to ensure that we're the only one fiddling with the suspend count
   2396      * though.
   2397      */
   2398     lockThreadSuspendCount();
   2399     dvmAddToThreadSuspendCount(&self->suspendCount, 1);
   2400     self->dbgSuspendCount++;
   2401 
   2402     /*
   2403      * Suspend ourselves.
   2404      */
   2405     assert(self->suspendCount > 0);
   2406     self->isSuspended = true;
   2407     LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
   2408 
   2409     /*
   2410      * Tell JDWP that we've completed suspension.  The JDWP thread can't
   2411      * tell us to resume before we're fully asleep because we hold the
   2412      * suspend count lock.
   2413      *
   2414      * If we got here via waitForDebugger(), don't do this part.
   2415      */
   2416     if (jdwpActivity) {
   2417         //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
   2418         //    self->threadId, (int) self->handle);
   2419         dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
   2420     }
   2421 
   2422     while (self->suspendCount != 0) {
   2423         int cc;
   2424         cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
   2425                 &gDvm.threadSuspendCountLock);
   2426         assert(cc == 0);
   2427         if (self->suspendCount != 0) {
   2428             /*
   2429              * The condition was signaled but we're still suspended.  This
   2430              * can happen if the debugger lets go while a SIGQUIT thread
   2431              * dump event is pending (assuming SignalCatcher was resumed for
   2432              * just long enough to try to grab the thread-suspend lock).
   2433              */
   2434             LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
   2435                 self->threadId, self->suspendCount, self->dbgSuspendCount,
   2436                 self->isSuspended ? 'Y' : 'N');
   2437         }
   2438     }
   2439     assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
   2440     self->isSuspended = false;
   2441     LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
   2442         self->threadId, self->status);
   2443 
   2444     unlockThreadSuspendCount();
   2445 }
   2446 
   2447 
   2448 #ifdef HAVE_GLIBC
   2449 # define NUM_FRAMES  20
   2450 # include <execinfo.h>
   2451 /*
   2452  * glibc-only stack dump function.  Requires link with "--export-dynamic".
   2453  *
   2454  * TODO: move this into libs/cutils and make it work for all platforms.
   2455  */
   2456 static void printBackTrace(void)
   2457 {
   2458     void* array[NUM_FRAMES];
   2459     size_t size;
   2460     char** strings;
   2461     size_t i;
   2462 
   2463     size = backtrace(array, NUM_FRAMES);
   2464     strings = backtrace_symbols(array, size);
   2465 
   2466     LOGW("Obtained %zd stack frames.\n", size);
   2467 
   2468     for (i = 0; i < size; i++)
   2469         LOGW("%s\n", strings[i]);
   2470 
   2471     free(strings);
   2472 }
   2473 #else
   2474 static void printBackTrace(void) {}
   2475 #endif
   2476 
   2477 /*
   2478  * Dump the state of the current thread and that of another thread that
   2479  * we think is wedged.
   2480  */
   2481 static void dumpWedgedThread(Thread* thread)
   2482 {
   2483     dvmDumpThread(dvmThreadSelf(), false);
   2484     printBackTrace();
   2485 
   2486     // dumping a running thread is risky, but could be useful
   2487     dvmDumpThread(thread, true);
   2488 
   2489     // stop now and get a core dump
   2490     //abort();
   2491 }
   2492 
   2493 /*
   2494  * If the thread is running at below-normal priority, temporarily elevate
   2495  * it to "normal".
   2496  *
   2497  * Returns zero if no changes were made.  Otherwise, returns bit flags
   2498  * indicating what was changed, storing the previous values in the
   2499  * provided locations.
   2500  */
   2501 int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
   2502     SchedPolicy* pSavedThreadPolicy)
   2503 {
   2504     errno = 0;
   2505     *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
   2506     if (errno != 0) {
   2507         LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
   2508             thread->threadId, thread->systemTid);
   2509         return 0;
   2510     }
   2511     if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
   2512         LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
   2513             thread->threadId, thread->systemTid);
   2514         return 0;
   2515     }
   2516 
   2517     int changeFlags = 0;
   2518 
   2519     /*
   2520      * Change the priority if we're in the background group.
   2521      */
   2522     if (*pSavedThreadPolicy == SP_BACKGROUND) {
   2523         if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
   2524             LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
   2525         } else {
   2526             changeFlags |= kChangedPolicy;
   2527             LOGD("Temporarily moving tid %d to fg (was %d)\n",
   2528                 thread->systemTid, *pSavedThreadPolicy);
   2529         }
   2530     }
   2531 
   2532     /*
   2533      * getpriority() returns the "nice" value, so larger numbers indicate
   2534      * lower priority, with 0 being normal.
   2535      */
   2536     if (*pSavedThreadPrio > 0) {
   2537         const int kHigher = 0;
   2538         if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
   2539             LOGW("Couldn't raise priority on tid %d to %d\n",
   2540                 thread->systemTid, kHigher);
   2541         } else {
   2542             changeFlags |= kChangedPriority;
   2543             LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
   2544                 thread->systemTid, *pSavedThreadPrio, kHigher);
   2545         }
   2546     }
   2547 
   2548     return changeFlags;
   2549 }
   2550 
   2551 /*
   2552  * Reset the priority values for the thread in question.
   2553  */
   2554 void dvmResetThreadPriority(Thread* thread, int changeFlags,
   2555     int savedThreadPrio, SchedPolicy savedThreadPolicy)
   2556 {
   2557     if ((changeFlags & kChangedPolicy) != 0) {
   2558         if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
   2559             LOGW("NOTE: couldn't reset tid %d to (%d)\n",
   2560                 thread->systemTid, savedThreadPolicy);
   2561         } else {
   2562             LOGD("Restored policy of %d to %d\n",
   2563                 thread->systemTid, savedThreadPolicy);
   2564         }
   2565     }
   2566 
   2567     if ((changeFlags & kChangedPriority) != 0) {
   2568         if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
   2569         {
   2570             LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
   2571                 thread->systemTid, savedThreadPrio);
   2572         } else {
   2573             LOGD("Restored priority on %d to %d\n",
   2574                 thread->systemTid, savedThreadPrio);
   2575         }
   2576     }
   2577 }
   2578 
   2579 /*
   2580  * Wait for another thread to see the pending suspension and stop running.
   2581  * It can either suspend itself or go into a non-running state such as
   2582  * VMWAIT or NATIVE in which it cannot interact with the GC.
   2583  *
   2584  * If we're running at a higher priority, sched_yield() may not do anything,
   2585  * so we need to sleep for "long enough" to guarantee that the other
   2586  * thread has a chance to finish what it's doing.  Sleeping for too short
   2587  * a period (e.g. less than the resolution of the sleep clock) might cause
   2588  * the scheduler to return immediately, so we want to start with a
   2589  * "reasonable" value and expand.
   2590  *
   2591  * This does not return until the other thread has stopped running.
   2592  * Eventually we time out and the VM aborts.
   2593  *
   2594  * This does not try to detect the situation where two threads are
   2595  * waiting for each other to suspend.  In normal use this is part of a
   2596  * suspend-all, which implies that the suspend-all lock is held, or as
   2597  * part of a debugger action in which the JDWP thread is always the one
   2598  * doing the suspending.  (We may need to re-evaluate this now that
   2599  * getThreadStackTrace is implemented as suspend-snapshot-resume.)
   2600  *
   2601  * TODO: track basic stats about time required to suspend VM.
   2602  */
   2603 #define FIRST_SLEEP (250*1000)    /* 0.25s */
   2604 #define MORE_SLEEP  (750*1000)    /* 0.75s */
   2605 static void waitForThreadSuspend(Thread* self, Thread* thread)
   2606 {
   2607     const int kMaxRetries = 10;
   2608     int spinSleepTime = FIRST_SLEEP;
   2609     bool complained = false;
   2610     int priChangeFlags = 0;
   2611     int savedThreadPrio = -500;
   2612     SchedPolicy savedThreadPolicy = SP_FOREGROUND;
   2613 
   2614     int sleepIter = 0;
   2615     int retryCount = 0;
   2616     u8 startWhen = 0;       // init req'd to placate gcc
   2617     u8 firstStartWhen = 0;
   2618 
   2619     while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
   2620         if (sleepIter == 0) {           // get current time on first iteration
   2621             startWhen = dvmGetRelativeTimeUsec();
   2622             if (firstStartWhen == 0)    // first iteration of first attempt
   2623                 firstStartWhen = startWhen;
   2624 
   2625             /*
   2626              * After waiting for a bit, check to see if the target thread is
   2627              * running at a reduced priority.  If so, bump it up temporarily
   2628              * to give it more CPU time.
   2629              */
   2630             if (retryCount == 2) {
   2631                 assert(thread->systemTid != 0);
   2632                 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
   2633                     &savedThreadPrio, &savedThreadPolicy);
   2634             }
   2635         }
   2636 
   2637 #if defined (WITH_JIT)
   2638         /*
   2639          * If we're still waiting after the first timeout, unchain all
   2640          * translations iff:
   2641          *   1) There are new chains formed since the last unchain
   2642          *   2) The top VM frame of the running thread is running JIT'ed code
   2643          */
   2644         if (gDvmJit.pJitEntryTable && retryCount > 0 &&
   2645             gDvmJit.hasNewChain && thread->inJitCodeCache) {
   2646             LOGD("JIT unchain all for threadid=%d", thread->threadId);
   2647             dvmJitUnchainAll();
   2648         }
   2649 #endif
   2650 
   2651         /*
   2652          * Sleep briefly.  The iterative sleep call returns false if we've
   2653          * exceeded the total time limit for this round of sleeping.
   2654          */
   2655         if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
   2656             if (spinSleepTime != FIRST_SLEEP) {
   2657                 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
   2658                     self->threadId, retryCount,
   2659                     thread->threadId, priChangeFlags);
   2660                 if (retryCount > 1) {
   2661                     /* stack trace logging is slow; skip on first iter */
   2662                     dumpWedgedThread(thread);
   2663                 }
   2664                 complained = true;
   2665             }
   2666 
   2667             // keep going; could be slow due to valgrind
   2668             sleepIter = 0;
   2669             spinSleepTime = MORE_SLEEP;
   2670 
   2671             if (retryCount++ == kMaxRetries) {
   2672                 LOGE("Fatal spin-on-suspend, dumping threads\n");
   2673                 dvmDumpAllThreads(false);
   2674 
   2675                 /* log this after -- long traces will scroll off log */
   2676                 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
   2677                     self->threadId, thread->threadId);
   2678 
   2679                 /* try to get a debuggerd dump from the spinning thread */
   2680                 dvmNukeThread(thread);
   2681                 /* abort the VM */
   2682                 dvmAbort();
   2683             }
   2684         }
   2685     }
   2686 
   2687     if (complained) {
   2688         LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
   2689             self->threadId,
   2690             (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
   2691         //dvmDumpThread(thread, false);   /* suspended, so dump is safe */
   2692     }
   2693     if (priChangeFlags != 0) {
   2694         dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
   2695             savedThreadPolicy);
   2696     }
   2697 }
   2698 
   2699 /*
   2700  * Suspend all threads except the current one.  This is used by the GC,
   2701  * the debugger, and by any thread that hits a "suspend all threads"
   2702  * debugger event (e.g. breakpoint or exception).
   2703  *
   2704  * If thread N hits a "suspend all threads" breakpoint, we don't want it
   2705  * to suspend the JDWP thread.  For the GC, we do, because the debugger can
   2706  * create objects and even execute arbitrary code.  The "why" argument
   2707  * allows the caller to say why the suspension is taking place.
   2708  *
   2709  * This can be called when a global suspend has already happened, due to
   2710  * various debugger gymnastics, so keeping an "everybody is suspended" flag
   2711  * doesn't work.
   2712  *
   2713  * DO NOT grab any locks before calling here.  We grab & release the thread
   2714  * lock and suspend lock here (and we're not using recursive threads), and
   2715  * we might have to self-suspend if somebody else beats us here.
   2716  *
   2717  * The current thread may not be attached to the VM.  This can happen if
   2718  * we happen to GC as the result of an allocation of a Thread object.
   2719  */
   2720 void dvmSuspendAllThreads(SuspendCause why)
   2721 {
   2722     Thread* self = dvmThreadSelf();
   2723     Thread* thread;
   2724 
   2725     assert(why != 0);
   2726 
   2727     /*
   2728      * Start by grabbing the thread suspend lock.  If we can't get it, most
   2729      * likely somebody else is in the process of performing a suspend or
   2730      * resume, so lockThreadSuspend() will cause us to self-suspend.
   2731      *
   2732      * We keep the lock until all other threads are suspended.
   2733      */
   2734     lockThreadSuspend("susp-all", why);
   2735 
   2736     LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
   2737 
   2738     /*
   2739      * This is possible if the current thread was in VMWAIT mode when a
   2740      * suspend-all happened, and then decided to do its own suspend-all.
   2741      * This can happen when a couple of threads have simultaneous events
   2742      * of interest to the debugger.
   2743      */
   2744     //assert(self->suspendCount == 0);
   2745 
   2746     /*
   2747      * Increment everybody's suspend count (except our own).
   2748      */
   2749     dvmLockThreadList(self);
   2750 
   2751     lockThreadSuspendCount();
   2752     for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
   2753         if (thread == self)
   2754             continue;
   2755 
   2756         /* debugger events don't suspend JDWP thread */
   2757         if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
   2758             thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
   2759             continue;
   2760 
   2761         dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
   2762         if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
   2763             thread->dbgSuspendCount++;
   2764     }
   2765     unlockThreadSuspendCount();
   2766 
   2767     /*
   2768      * Wait for everybody in THREAD_RUNNING state to stop.  Other states
   2769      * indicate the code is either running natively or sleeping quietly.
   2770      * Any attempt to transition back to THREAD_RUNNING will cause a check
   2771      * for suspension, so it should be impossible for anything to execute
   2772      * interpreted code or modify objects (assuming native code plays nicely).
   2773      *
   2774      * It's also okay if the thread transitions to a non-RUNNING state.
   2775      *
   2776      * Note we released the threadSuspendCountLock before getting here,
   2777      * so if another thread is fiddling with its suspend count (perhaps
   2778      * self-suspending for the debugger) it won't block while we're waiting
   2779      * in here.
   2780      */
   2781     for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
   2782         if (thread == self)
   2783             continue;
   2784 
   2785         /* debugger events don't suspend JDWP thread */
   2786         if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
   2787             thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
   2788             continue;
   2789 
   2790         /* wait for the other thread to see the pending suspend */
   2791         waitForThreadSuspend(self, thread);
   2792 
   2793         LOG_THREAD("threadid=%d:   threadid=%d status=%d c=%d dc=%d isSusp=%d\n",
   2794             self->threadId,
   2795             thread->threadId, thread->status, thread->suspendCount,
   2796             thread->dbgSuspendCount, thread->isSuspended);
   2797     }
   2798 
   2799     dvmUnlockThreadList();
   2800     unlockThreadSuspend();
   2801 
   2802     LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
   2803 }
   2804 
   2805 /*
   2806  * Resume all threads that are currently suspended.
   2807  *
   2808  * The "why" must match with the previous suspend.
   2809  */
   2810 void dvmResumeAllThreads(SuspendCause why)
   2811 {
   2812     Thread* self = dvmThreadSelf();
   2813     Thread* thread;
   2814     int cc;
   2815 
   2816     lockThreadSuspend("res-all", why);  /* one suspend/resume at a time */
   2817     LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
   2818 
   2819     /*
   2820      * Decrement the suspend counts for all threads.  No need for atomic
   2821      * writes, since nobody should be moving until we decrement the count.
   2822      * We do need to hold the thread list because of JNI attaches.
   2823      */
   2824     dvmLockThreadList(self);
   2825     lockThreadSuspendCount();
   2826     for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
   2827         if (thread == self)
   2828             continue;
   2829 
   2830         /* debugger events don't suspend JDWP thread */
   2831         if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
   2832             thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
   2833         {
   2834             continue;
   2835         }
   2836 
   2837         if (thread->suspendCount > 0) {
   2838             dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
   2839             if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
   2840                 thread->dbgSuspendCount--;
   2841         } else {
   2842             LOG_THREAD("threadid=%d:  suspendCount already zero\n",
   2843                 thread->threadId);
   2844         }
   2845     }
   2846     unlockThreadSuspendCount();
   2847     dvmUnlockThreadList();
   2848 
   2849     /*
   2850      * In some ways it makes sense to continue to hold the thread-suspend
   2851      * lock while we issue the wakeup broadcast.  It allows us to complete
   2852      * one operation before moving on to the next, which simplifies the
   2853      * thread activity debug traces.
   2854      *
   2855      * This approach caused us some difficulty under Linux, because the
   2856      * condition variable broadcast not only made the threads runnable,
   2857      * but actually caused them to execute, and it was a while before
   2858      * the thread performing the wakeup had an opportunity to release the
   2859      * thread-suspend lock.
   2860      *
   2861      * This is a problem because, when a thread tries to acquire that
   2862      * lock, it times out after 3 seconds.  If at some point the thread
   2863      * is told to suspend, the clock resets; but since the VM is still
   2864      * theoretically mid-resume, there's no suspend pending.  If, for
   2865      * example, the GC was waking threads up while the SIGQUIT handler
   2866      * was trying to acquire the lock, we would occasionally time out on
   2867      * a busy system and SignalCatcher would abort.
   2868      *
   2869      * We now perform the unlock before the wakeup broadcast.  The next
   2870      * suspend can't actually start until the broadcast completes and
   2871      * returns, because we're holding the thread-suspend-count lock, but the
   2872      * suspending thread is now able to make progress and we avoid the abort.
   2873      *
   2874      * (Technically there is a narrow window between when we release
   2875      * the thread-suspend lock and grab the thread-suspend-count lock.
   2876      * This could cause us to send a broadcast to threads with nonzero
   2877      * suspend counts, but this is expected and they'll all just fall
   2878      * right back to sleep.  It's probably safe to grab the suspend-count
   2879      * lock before releasing thread-suspend, since we're still following
   2880      * the correct order of acquisition, but it feels weird.)
   2881      */
   2882 
   2883     LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
   2884     unlockThreadSuspend();
   2885 
   2886     /*
   2887      * Broadcast a notification to all suspended threads, some or all of
   2888      * which may choose to wake up.  No need to wait for them.
   2889      */
   2890     lockThreadSuspendCount();
   2891     cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
   2892     assert(cc == 0);
   2893     unlockThreadSuspendCount();
   2894 
   2895     LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
   2896 }
   2897 
   2898 /*
   2899  * Undo any debugger suspensions.  This is called when the debugger
   2900  * disconnects.
   2901  */
   2902 void dvmUndoDebuggerSuspensions(void)
   2903 {
   2904     Thread* self = dvmThreadSelf();
   2905     Thread* thread;
   2906     int cc;
   2907 
   2908     lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
   2909     LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
   2910 
   2911     /*
   2912      * Decrement the suspend counts for all threads.  No need for atomic
   2913      * writes, since nobody should be moving until we decrement the count.
   2914      * We do need to hold the thread list because of JNI attaches.
   2915      */
   2916     dvmLockThreadList(self);
   2917     lockThreadSuspendCount();
   2918     for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
   2919         if (thread == self)
   2920             continue;
   2921 
   2922         /* debugger events don't suspend JDWP thread */
   2923         if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
   2924             assert(thread->dbgSuspendCount == 0);
   2925             continue;
   2926         }
   2927 
   2928         assert(thread->suspendCount >= thread->dbgSuspendCount);
   2929         dvmAddToThreadSuspendCount(&thread->suspendCount,
   2930                                    -thread->dbgSuspendCount);
   2931         thread->dbgSuspendCount = 0;
   2932     }
   2933     unlockThreadSuspendCount();
   2934     dvmUnlockThreadList();
   2935 
   2936     /*
   2937      * Broadcast a notification to all suspended threads, some or all of
   2938      * which may choose to wake up.  No need to wait for them.
   2939      */
   2940     lockThreadSuspendCount();
   2941     cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
   2942     assert(cc == 0);
   2943     unlockThreadSuspendCount();
   2944 
   2945     unlockThreadSuspend();
   2946 
   2947     LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
   2948 }
   2949 
   2950 /*
   2951  * Determine if a thread is suspended.
   2952  *
   2953  * As with all operations on foreign threads, the caller should hold
   2954  * the thread list lock before calling.
   2955  */
   2956 bool dvmIsSuspended(Thread* thread)
   2957 {
   2958     /*
   2959      * The thread could be:
   2960      *  (1) Running happily.  status is RUNNING, isSuspended is false,
   2961      *      suspendCount is zero.  Return "false".
   2962      *  (2) Pending suspend.  status is RUNNING, isSuspended is false,
   2963      *      suspendCount is nonzero.  Return "false".
   2964      *  (3) Suspended.  suspendCount is nonzero, and either (status is
   2965      *      RUNNING and isSuspended is true) OR (status is !RUNNING).
   2966      *      Return "true".
   2967      *  (4) Waking up.  suspendCount is zero, status is RUNNING and
   2968      *      isSuspended is true.  Return "false" (since it could change
   2969      *      out from under us, unless we hold suspendCountLock).
   2970      */
   2971 
   2972     return (thread->suspendCount != 0 &&
   2973             ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
   2974              (thread->status != THREAD_RUNNING)));
   2975 }
   2976 
   2977 /*
   2978  * Wait until another thread self-suspends.  This is specifically for
   2979  * synchronization between the JDWP thread and a thread that has decided
   2980  * to suspend itself after sending an event to the debugger.
   2981  *
   2982  * Threads that encounter "suspend all" events work as well -- the thread
   2983  * in question suspends everybody else and then itself.
   2984  *
   2985  * We can't hold a thread lock here or in the caller, because we could
   2986  * get here just before the to-be-waited-for-thread issues a "suspend all".
   2987  * There's an opportunity for badness if the thread we're waiting for exits
   2988  * and gets cleaned up, but since the thread in question is processing a
   2989  * debugger event, that's not really a possibility.  (To avoid deadlock,
   2990  * it's important that we not be in THREAD_RUNNING while we wait.)
   2991  */
   2992 void dvmWaitForSuspend(Thread* thread)
   2993 {
   2994     Thread* self = dvmThreadSelf();
   2995 
   2996     LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
   2997         self->threadId, thread->threadId);
   2998 
   2999     assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
   3000     assert(thread != self);
   3001     assert(self->status != THREAD_RUNNING);
   3002 
   3003     waitForThreadSuspend(self, thread);
   3004 
   3005     LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
   3006         self->threadId, thread->threadId);
   3007 }
   3008 
   3009 /*
   3010  * Check to see if we need to suspend ourselves.  If so, go to sleep on
   3011  * a condition variable.
   3012  *
   3013  * Takes "self" as an argument as an optimization.  Pass in NULL to have
   3014  * it do the lookup.
   3015  *
   3016  * Returns "true" if we suspended ourselves.
   3017  */
   3018 bool dvmCheckSuspendPending(Thread* self)
   3019 {
   3020     bool didSuspend;
   3021 
   3022     if (self == NULL)
   3023         self = dvmThreadSelf();
   3024 
   3025     /* fast path: if count is zero, bail immediately */
   3026     if (self->suspendCount == 0)
   3027         return false;
   3028 
   3029     lockThreadSuspendCount();   /* grab gDvm.threadSuspendCountLock */
   3030 
   3031     assert(self->suspendCount >= 0);        /* XXX: valid? useful? */
   3032 
   3033     didSuspend = (self->suspendCount != 0);
   3034     self->isSuspended = true;
   3035     LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
   3036     while (self->suspendCount != 0) {
   3037         /* wait for wakeup signal; releases lock */
   3038         int cc;
   3039         cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
   3040                 &gDvm.threadSuspendCountLock);
   3041         assert(cc == 0);
   3042     }
   3043     assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
   3044     self->isSuspended = false;
   3045     LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
   3046         self->threadId, self->status);
   3047 
   3048     unlockThreadSuspendCount();
   3049 
   3050     return didSuspend;
   3051 }
   3052 
   3053 /*
   3054  * Update our status.
   3055  *
   3056  * The "self" argument, which may be NULL, is accepted as an optimization.
   3057  *
   3058  * Returns the old status.
   3059  */
   3060 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
   3061 {
   3062     ThreadStatus oldStatus;
   3063 
   3064     if (self == NULL)
   3065         self = dvmThreadSelf();
   3066 
   3067     LOGVV("threadid=%d: (status %d -> %d)\n",
   3068         self->threadId, self->status, newStatus);
   3069 
   3070     oldStatus = self->status;
   3071 
   3072     if (newStatus == THREAD_RUNNING) {
   3073         /*
   3074          * Change our status to THREAD_RUNNING.  The transition requires
   3075          * that we check for pending suspension, because the VM considers
   3076          * us to be "asleep" in all other states.
   3077          *
   3078          * We need to do the "suspend pending" check FIRST, because it grabs
   3079          * a lock that could be held by something that wants us to suspend.
   3080          * If we're in RUNNING it will wait for us, and we'll be waiting
   3081          * for the lock it holds.
   3082          */
   3083         assert(self->status != THREAD_RUNNING);
   3084 
   3085         dvmCheckSuspendPending(self);
   3086         self->status = THREAD_RUNNING;
   3087     } else {
   3088         /*
   3089          * Change from one state to another, neither of which is
   3090          * THREAD_RUNNING.  This is most common during system or thread
   3091          * initialization.
   3092          */
   3093         self->status = newStatus;
   3094     }
   3095 
   3096     return oldStatus;
   3097 }
   3098 
   3099 /*
   3100  * Get a statically defined thread group from a field in the ThreadGroup
   3101  * Class object.  Expected arguments are "mMain" and "mSystem".
   3102  */
   3103 static Object* getStaticThreadGroup(const char* fieldName)
   3104 {
   3105     StaticField* groupField;
   3106     Object* groupObj;
   3107 
   3108     groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
   3109         fieldName, "Ljava/lang/ThreadGroup;");
   3110     if (groupField == NULL) {
   3111         LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
   3112         dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
   3113         return NULL;
   3114     }
   3115     groupObj = dvmGetStaticFieldObject(groupField);
   3116     if (groupObj == NULL) {
   3117         LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
   3118         dvmThrowException("Ljava/lang/InternalError;", NULL);
   3119         return NULL;
   3120     }
   3121 
   3122     return groupObj;
   3123 }
   3124 Object* dvmGetSystemThreadGroup(void)
   3125 {
   3126     return getStaticThreadGroup("mSystem");
   3127 }
   3128 Object* dvmGetMainThreadGroup(void)
   3129 {
   3130     return getStaticThreadGroup("mMain");
   3131 }
   3132 
   3133 /*
   3134  * Given a VMThread object, return the associated Thread*.
   3135  *
   3136  * NOTE: if the thread detaches, the struct Thread will disappear, and
   3137  * we will be touching invalid data.  For safety, lock the thread list
   3138  * before calling this.
   3139  */
   3140 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
   3141 {
   3142     int vmData;
   3143 
   3144     vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
   3145 
   3146     if (false) {
   3147         Thread* thread = gDvm.threadList;
   3148         while (thread != NULL) {
   3149             if ((Thread*)vmData == thread)
   3150                 break;
   3151 
   3152             thread = thread->next;
   3153         }
   3154 
   3155         if (thread == NULL) {
   3156             LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
   3157                 vmThreadObj, (Thread*)vmData);
   3158             vmData = 0;
   3159         }
   3160     }
   3161 
   3162     return (Thread*) vmData;
   3163 }
   3164 
   3165 /*
   3166  * Given a pthread handle, return the associated Thread*.
   3167  * Caller must hold the thread list lock.
   3168  *
   3169  * Returns NULL if the thread was not found.
   3170  */
   3171 Thread* dvmGetThreadByHandle(pthread_t handle)
   3172 {
   3173     Thread* thread;
   3174     for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
   3175         if (thread->handle == handle)
   3176             break;
   3177     }
   3178     return thread;
   3179 }
   3180 
   3181 /*
   3182  * Given a threadId, return the associated Thread*.
   3183  * Caller must hold the thread list lock.
   3184  *
   3185  * Returns NULL if the thread was not found.
   3186  */
   3187 Thread* dvmGetThreadByThreadId(u4 threadId)
   3188 {
   3189     Thread* thread;
   3190     for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
   3191         if (thread->threadId == threadId)
   3192             break;
   3193     }
   3194     return thread;
   3195 }
   3196 
   3197 
   3198 /*
   3199  * Conversion map for "nice" values.
   3200  *
   3201  * We use Android thread priority constants to be consistent with the rest
   3202  * of the system.  In some cases adjacent entries may overlap.
   3203  */
   3204 static const int kNiceValues[10] = {
   3205     ANDROID_PRIORITY_LOWEST,                /* 1 (MIN_PRIORITY) */
   3206     ANDROID_PRIORITY_BACKGROUND + 6,
   3207     ANDROID_PRIORITY_BACKGROUND + 3,
   3208     ANDROID_PRIORITY_BACKGROUND,
   3209     ANDROID_PRIORITY_NORMAL,                /* 5 (NORM_PRIORITY) */
   3210     ANDROID_PRIORITY_NORMAL - 2,
   3211     ANDROID_PRIORITY_NORMAL - 4,
   3212     ANDROID_PRIORITY_URGENT_DISPLAY + 3,
   3213     ANDROID_PRIORITY_URGENT_DISPLAY + 2,
   3214     ANDROID_PRIORITY_URGENT_DISPLAY         /* 10 (MAX_PRIORITY) */
   3215 };
   3216 
   3217 /*
   3218  * Change the priority of a system thread to match that of the Thread object.
   3219  *
   3220  * We map a priority value from 1-10 to Linux "nice" values, where lower
   3221  * numbers indicate higher priority.
   3222  */
   3223 void dvmChangeThreadPriority(Thread* thread, int newPriority)
   3224 {
   3225     pid_t pid = thread->systemTid;
   3226     int newNice;
   3227 
   3228     if (newPriority < 1 || newPriority > 10) {
   3229         LOGW("bad priority %d\n", newPriority);
   3230         newPriority = 5;
   3231     }
   3232     newNice = kNiceValues[newPriority-1];
   3233 
   3234     if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
   3235         set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
   3236     } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
   3237         set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
   3238     }
   3239 
   3240     if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
   3241         char* str = dvmGetThreadName(thread);
   3242         LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
   3243             pid, str, newPriority, newNice, strerror(errno));
   3244         free(str);
   3245     } else {
   3246         LOGV("setPriority(%d) to prio=%d(n=%d)\n",
   3247             pid, newPriority, newNice);
   3248     }
   3249 }
   3250 
   3251 /*
   3252  * Get the thread priority for the current thread by querying the system.
   3253  * This is useful when attaching a thread through JNI.
   3254  *
   3255  * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
   3256  */
   3257 static int getThreadPriorityFromSystem(void)
   3258 {
   3259     int i, sysprio, jprio;
   3260 
   3261     errno = 0;
   3262     sysprio = getpriority(PRIO_PROCESS, 0);
   3263     if (sysprio == -1 && errno != 0) {
   3264         LOGW("getpriority() failed: %s\n", strerror(errno));
   3265         return THREAD_NORM_PRIORITY;
   3266     }
   3267 
   3268     jprio = THREAD_MIN_PRIORITY;
   3269     for (i = 0; i < NELEM(kNiceValues); i++) {
   3270         if (sysprio >= kNiceValues[i])
   3271             break;
   3272         jprio++;
   3273     }
   3274     if (jprio > THREAD_MAX_PRIORITY)
   3275         jprio = THREAD_MAX_PRIORITY;
   3276 
   3277     return jprio;
   3278 }
   3279 
   3280 
   3281 /*
   3282  * Return true if the thread is on gDvm.threadList.
   3283  * Caller should not hold gDvm.threadListLock.
   3284  */
   3285 bool dvmIsOnThreadList(const Thread* thread)
   3286 {
   3287     bool ret = false;
   3288 
   3289     dvmLockThreadList(NULL);
   3290     if (thread == gDvm.threadList) {
   3291         ret = true;
   3292     } else {
   3293         ret = thread->prev != NULL || thread->next != NULL;
   3294     }
   3295     dvmUnlockThreadList();
   3296 
   3297     return ret;
   3298 }
   3299 
   3300 /*
   3301  * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
   3302  * output target.
   3303  */
   3304 void dvmDumpThread(Thread* thread, bool isRunning)
   3305 {
   3306     DebugOutputTarget target;
   3307 
   3308     dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
   3309     dvmDumpThreadEx(&target, thread, isRunning);
   3310 }
   3311 
   3312 /*
   3313  * Try to get the scheduler group.
   3314  *
   3315  * The data from /proc/<pid>/cgroup looks (something) like:
   3316  *  2:cpu:/bg_non_interactive
   3317  *  1:cpuacct:/
   3318  *
   3319  * We return the part after the "/", which will be an empty string for
   3320  * the default cgroup.  If the string is longer than "bufLen", the string
   3321  * will be truncated.
   3322  *
   3323  * TODO: this is cloned from a static function in libcutils; expose that?
   3324  */
   3325 static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
   3326 {
   3327 #ifdef HAVE_ANDROID_OS
   3328     char pathBuf[32];
   3329     char lineBuf[256];
   3330     FILE *fp;
   3331 
   3332     snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
   3333     if (!(fp = fopen(pathBuf, "r"))) {
   3334         return -1;
   3335     }
   3336 
   3337     while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
   3338         char *next = lineBuf;
   3339         char *subsys;
   3340         char *grp;
   3341         size_t len;
   3342 
   3343         /* Junk the first field */
   3344         if (!strsep(&next, ":")) {
   3345             goto out_bad_data;
   3346         }
   3347 
   3348         if (!(subsys = strsep(&next, ":"))) {
   3349             goto out_bad_data;
   3350         }
   3351 
   3352         if (strcmp(subsys, "cpu")) {
   3353             /* Not the subsys we're looking for */
   3354             continue;
   3355         }
   3356 
   3357         if (!(grp = strsep(&next, ":"))) {
   3358             goto out_bad_data;
   3359         }
   3360         grp++; /* Drop the leading '/' */
   3361         len = strlen(grp);
   3362         grp[len-1] = '\0'; /* Drop the trailing '\n' */
   3363 
   3364         if (bufLen <= len) {
   3365             len = bufLen - 1;
   3366         }
   3367         strncpy(buf, grp, len);
   3368         buf[len] = '\0';
   3369         fclose(fp);
   3370         return 0;
   3371     }
   3372 
   3373     LOGE("Failed to find cpu subsys");
   3374     fclose(fp);
   3375     return -1;
   3376  out_bad_data:
   3377     LOGE("Bad cgroup data {%s}", lineBuf);
   3378     fclose(fp);
   3379     return -1;
   3380 #else
   3381     errno = ENOSYS;
   3382     return -1;
   3383 #endif
   3384 }
   3385 
   3386 /*
   3387  * Convert ThreadStatus to a string.
   3388  */
   3389 const char* dvmGetThreadStatusStr(ThreadStatus status)
   3390 {
   3391     switch (status) {
   3392     case THREAD_ZOMBIE:         return "ZOMBIE";
   3393     case THREAD_RUNNING:        return "RUNNABLE";
   3394     case THREAD_TIMED_WAIT:     return "TIMED_WAIT";
   3395     case THREAD_MONITOR:        return "MONITOR";
   3396     case THREAD_WAIT:           return "WAIT";
   3397     case THREAD_INITIALIZING:   return "INITIALIZING";
   3398     case THREAD_STARTING:       return "STARTING";
   3399     case THREAD_NATIVE:         return "NATIVE";
   3400     case THREAD_VMWAIT:         return "VMWAIT";
   3401     default:                    return "UNKNOWN";
   3402     }
   3403 }
   3404 
   3405 /*
   3406  * Print information about the specified thread.
   3407  *
   3408  * Works best when the thread in question is "self" or has been suspended.
   3409  * When dumping a separate thread that's still running, set "isRunning" to
   3410  * use a more cautious thread dump function.
   3411  */
   3412 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
   3413     bool isRunning)
   3414 {
   3415     Object* threadObj;
   3416     Object* groupObj;
   3417     StringObject* nameStr;
   3418     char* threadName = NULL;
   3419     char* groupName = NULL;
   3420     char schedulerGroupBuf[32];
   3421     bool isDaemon;
   3422     int priority;               // java.lang.Thread priority
   3423     int policy;                 // pthread policy
   3424     struct sched_param sp;      // pthread scheduling parameters
   3425     char schedstatBuf[64];      // contents of /proc/[pid]/task/[tid]/schedstat
   3426     int schedstatFd;
   3427 
   3428     threadObj = thread->threadObj;
   3429     if (threadObj == NULL) {
   3430         LOGW("Can't dump thread %d: threadObj not set\n", thread->threadId);
   3431         return;
   3432     }
   3433     nameStr = (StringObject*) dvmGetFieldObject(threadObj,
   3434                 gDvm.offJavaLangThread_name);
   3435     threadName = dvmCreateCstrFromString(nameStr);
   3436 
   3437     priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
   3438     isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
   3439 
   3440     if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
   3441         LOGW("Warning: pthread_getschedparam failed\n");
   3442         policy = -1;
   3443         sp.sched_priority = -1;
   3444     }
   3445     if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
   3446             sizeof(schedulerGroupBuf)) != 0)
   3447     {
   3448         strcpy(schedulerGroupBuf, "unknown");
   3449     } else if (schedulerGroupBuf[0] == '\0') {
   3450         strcpy(schedulerGroupBuf, "default");
   3451     }
   3452 
   3453     /* a null value for group is not expected, but deal with it anyway */
   3454     groupObj = (Object*) dvmGetFieldObject(threadObj,
   3455                 gDvm.offJavaLangThread_group);
   3456     if (groupObj != NULL) {
   3457         int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
   3458             "name", "Ljava/lang/String;");
   3459         if (offset < 0) {
   3460             LOGW("Unable to find 'name' field in ThreadGroup\n");
   3461         } else {
   3462             nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
   3463             groupName = dvmCreateCstrFromString(nameStr);
   3464         }
   3465     }
   3466     if (groupName == NULL)
   3467         groupName = strdup("(BOGUS GROUP)");
   3468 
   3469     dvmPrintDebugMessage(target,
   3470         "\"%s\"%s prio=%d tid=%d %s%s\n",
   3471         threadName, isDaemon ? " daemon" : "",
   3472         priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
   3473 #if defined(WITH_JIT)
   3474         thread->inJitCodeCache ? " JIT" : ""
   3475 #else
   3476         ""
   3477 #endif
   3478         );
   3479     dvmPrintDebugMessage(target,
   3480         "  | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
   3481         groupName, thread->suspendCount, thread->dbgSuspendCount,
   3482         thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
   3483     dvmPrintDebugMessage(target,
   3484         "  | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
   3485         thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
   3486         policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
   3487 
   3488     snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/%d/task/%d/schedstat",
   3489              getpid(), thread->systemTid);
   3490     schedstatFd = open(schedstatBuf, O_RDONLY);
   3491     if (schedstatFd >= 0) {
   3492         int bytes;
   3493         bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
   3494         close(schedstatFd);
   3495         if (bytes > 1) {
   3496             schedstatBuf[bytes-1] = 0;  // trailing newline
   3497             dvmPrintDebugMessage(target, "  | schedstat=( %s )\n", schedstatBuf);
   3498         }
   3499     }
   3500 
   3501 #ifdef WITH_MONITOR_TRACKING
   3502     if (!isRunning) {
   3503         LockedObjectData* lod = thread->pLockedObjects;
   3504         if (lod != NULL)
   3505             dvmPrintDebugMessage(target, "  | monitors held:\n");
   3506         else
   3507             dvmPrintDebugMessage(target, "  | monitors held: <none>\n");
   3508         while (lod != NULL) {
   3509             Object* obj = lod->obj;
   3510             if (obj->clazz == gDvm.classJavaLangClass) {
   3511                 ClassObject* clazz = (ClassObject*) obj;
   3512                 dvmPrintDebugMessage(target, "  >  %p[%d] (%s object for class %s)\n",
   3513                     obj, lod->recursionCount, obj->clazz->descriptor,
   3514                     clazz->descriptor);
   3515             } else {
   3516                 dvmPrintDebugMessage(target, "  >  %p[%d] (%s)\n",
   3517                     obj, lod->recursionCount, obj->clazz->descriptor);
   3518             }
   3519             lod = lod->next;
   3520         }
   3521     }
   3522 #endif
   3523 
   3524     if (isRunning)
   3525         dvmDumpRunningThreadStack(target, thread);
   3526     else
   3527         dvmDumpThreadStack(target, thread);
   3528 
   3529     free(threadName);
   3530     free(groupName);
   3531 
   3532 }
   3533 
   3534 /*
   3535  * Get the name of a thread.
   3536  *
   3537  * For correctness, the caller should hold the thread list lock to ensure
   3538  * that the thread doesn't go away mid-call.
   3539  *
   3540  * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
   3541  */
   3542 char* dvmGetThreadName(Thread* thread)
   3543 {
   3544     StringObject* nameObj;
   3545 
   3546     if (thread->threadObj == NULL) {
   3547         LOGW("threadObj is NULL, name not available\n");
   3548         return strdup("-unknown-");
   3549     }
   3550 
   3551     nameObj = (StringObject*)
   3552         dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
   3553     return dvmCreateCstrFromString(nameObj);
   3554 }
   3555 
   3556 /*
   3557  * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
   3558  * an output target.
   3559  */
   3560 void dvmDumpAllThreads(bool grabLock)
   3561 {
   3562     DebugOutputTarget target;
   3563 
   3564     dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
   3565     dvmDumpAllThreadsEx(&target, grabLock);
   3566 }
   3567 
   3568 /*
   3569  * Print information about all known threads.  Assumes they have been
   3570  * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
   3571  *
   3572  * If "grabLock" is true, we grab the thread lock list.  This is important
   3573  * to do unless the caller already holds the lock.
   3574  */
   3575 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
   3576 {
   3577     Thread* thread;
   3578 
   3579     dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
   3580 
   3581     if (grabLock)
   3582         dvmLockThreadList(dvmThreadSelf());
   3583 
   3584     thread = gDvm.threadList;
   3585     while (thread != NULL) {
   3586         dvmDumpThreadEx(target, thread, false);
   3587 
   3588         /* verify link */
   3589         assert(thread->next == NULL || thread->next->prev == thread);
   3590 
   3591         thread = thread->next;
   3592     }
   3593 
   3594     if (grabLock)
   3595         dvmUnlockThreadList();
   3596 }
   3597 
   3598 /*
   3599  * Nuke the target thread from orbit.
   3600  *
   3601  * The idea is to send a "crash" signal to the target thread so that
   3602  * debuggerd will take notice and dump an appropriate stack trace.
   3603  * Because of the way debuggerd works, we have to throw the same signal
   3604  * at it twice.
   3605  *
   3606  * This does not necessarily cause the entire process to stop, but once a
   3607  * thread has been nuked the rest of the system is likely to be unstable.
   3608  * This returns so that some limited set of additional operations may be
   3609  * performed, but it's advisable (and expected) to call dvmAbort soon.
   3610  * (This is NOT a way to simply cancel a thread.)
   3611  */
   3612 void dvmNukeThread(Thread* thread)
   3613 {
   3614     /* suppress the heapworker watchdog to assist anyone using a debugger */
   3615     gDvm.nativeDebuggerActive = true;
   3616 
   3617     /*
   3618      * Send the signals, separated by a brief interval to allow debuggerd
   3619      * to work its magic.  An uncommon signal like SIGFPE or SIGSTKFLT
   3620      * can be used instead of SIGSEGV to avoid making it look like the
   3621      * code actually crashed at the current point of execution.
   3622      *
   3623      * (Observed behavior: with SIGFPE, debuggerd will dump the target
   3624      * thread and then the thread that calls dvmAbort.  With SIGSEGV,
   3625      * you don't get the second stack trace; possibly something in the
   3626      * kernel decides that a signal has already been sent and it's time
   3627      * to just kill the process.  The position in the current thread is
   3628      * generally known, so the second dump is not useful.)
   3629      *
   3630      * The target thread can continue to execute between the two signals.
   3631      * (The first just causes debuggerd to attach to it.)
   3632      */
   3633     LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
   3634          " cause debuggerd dump\n",
   3635         dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
   3636     pthread_kill(thread->handle, SIGSTKFLT);
   3637     usleep(2 * 1000 * 1000);    // TODO: timed-wait until debuggerd attaches
   3638     pthread_kill(thread->handle, SIGSTKFLT);
   3639     LOGD("Sent, pausing to let debuggerd run\n");
   3640     usleep(8 * 1000 * 1000);    // TODO: timed-wait until debuggerd finishes
   3641 
   3642     /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
   3643     signal(SIGSEGV, SIG_IGN);
   3644     LOGD("Continuing\n");
   3645 }
   3646 
   3647 #ifdef WITH_MONITOR_TRACKING
   3648 /*
   3649  * Count up the #of locked objects in the current thread.
   3650  */
   3651 static int getThreadObjectCount(const Thread* self)
   3652 {
   3653     LockedObjectData* lod;
   3654     int count = 0;
   3655 
   3656     lod = self->pLockedObjects;
   3657     while (lod != NULL) {
   3658         count++;
   3659         lod = lod->next;
   3660     }
   3661     return count;
   3662 }
   3663 
   3664 /*
   3665  * Add the object to the thread's locked object list if it doesn't already
   3666  * exist.  The most recently added object is the most likely to be released
   3667  * next, so we insert at the head of the list.
   3668  *
   3669  * If it already exists, we increase the recursive lock count.
   3670  *
   3671  * The object's lock may be thin or fat.
   3672  */
   3673 void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
   3674 {
   3675     LockedObjectData* newLod;
   3676     LockedObjectData* lod;
   3677     int* trace;
   3678     int depth;
   3679 
   3680     lod = self->pLockedObjects;
   3681     while (lod != NULL) {
   3682         if (lod->obj == obj) {
   3683             lod->recursionCount++;
   3684             LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
   3685             return;
   3686         }
   3687         lod = lod->next;
   3688     }
   3689 
   3690     newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
   3691     if (newLod == NULL) {
   3692         LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
   3693         return;
   3694     }
   3695     newLod->obj = obj;
   3696     newLod->recursionCount = 0;
   3697 
   3698     if (withTrace) {
   3699         trace = dvmFillInStackTraceRaw(self, &depth);
   3700         newLod->rawStackTrace = trace;
   3701         newLod->stackDepth = depth;
   3702     }
   3703 
   3704     newLod->next = self->pLockedObjects;
   3705     self->pLockedObjects = newLod;
   3706 
   3707     LOGV("+++ threadid=%d: added %p, now %d\n",
   3708         self->threadId, newLod, getThreadObjectCount(self));
   3709 }
   3710 
   3711 /*
   3712  * Remove the object from the thread's locked object list.  If the entry
   3713  * has a nonzero recursion count, we just decrement the count instead.
   3714  */
   3715 void dvmRemoveFromMonitorList(Thread* self, Object* obj)
   3716 {
   3717     LockedObjectData* lod;
   3718     LockedObjectData* prevLod;
   3719 
   3720     lod = self->pLockedObjects;
   3721     prevLod = NULL;
   3722     while (lod != NULL) {
   3723         if (lod->obj == obj) {
   3724             if (lod->recursionCount > 0) {
   3725                 lod->recursionCount--;
   3726                 LOGV("+++ -recursive lock %p -> %d\n",
   3727                     obj, lod->recursionCount);
   3728                 return;
   3729             } else {
   3730                 break;
   3731             }
   3732         }
   3733         prevLod = lod;
   3734         lod = lod->next;
   3735     }
   3736 
   3737     if (lod == NULL) {
   3738         LOGW("BUG: object %p not found in thread's lock list\n", obj);
   3739         return;
   3740     }
   3741     if (prevLod == NULL) {
   3742         /* first item in list */
   3743         assert(self->pLockedObjects == lod);
   3744         self->pLockedObjects = lod->next;
   3745     } else {
   3746         /* middle/end of list */
   3747         prevLod->next = lod->next;
   3748     }
   3749 
   3750     LOGV("+++ threadid=%d: removed %p, now %d\n",
   3751         self->threadId, lod, getThreadObjectCount(self));
   3752     free(lod->rawStackTrace);
   3753     free(lod);
   3754 }
   3755 
   3756 /*
   3757  * If the specified object is already in the thread's locked object list,
   3758  * return the LockedObjectData struct.  Otherwise return NULL.
   3759  */
   3760 LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
   3761 {
   3762     LockedObjectData* lod;
   3763 
   3764     lod = self->pLockedObjects;
   3765     while (lod != NULL) {
   3766         if (lod->obj == obj)
   3767             return lod;
   3768         lod = lod->next;
   3769     }
   3770     return NULL;
   3771 }
   3772 #endif /*WITH_MONITOR_TRACKING*/
   3773 
   3774 
   3775 /*
   3776  * GC helper functions
   3777  */
   3778 
   3779 /*
   3780  * Add the contents of the registers from the interpreted call stack.
   3781  */
   3782 static void gcScanInterpStackReferences(Thread *thread)
   3783 {
   3784     const u4 *framePtr;
   3785 #if WITH_EXTRA_GC_CHECKS > 1
   3786     bool first = true;
   3787 #endif
   3788 
   3789     framePtr = (const u4 *)thread->curFrame;
   3790     while (framePtr != NULL) {
   3791         const StackSaveArea *saveArea;
   3792         const Method *method;
   3793 
   3794         saveArea = SAVEAREA_FROM_FP(framePtr);
   3795         method = saveArea->method;
   3796         if (method != NULL && !dvmIsNativeMethod(method)) {
   3797 #ifdef COUNT_PRECISE_METHODS
   3798             /* the GC is running, so no lock required */
   3799             if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
   3800                 LOGI("PGC: added %s.%s %p\n",
   3801                     method->clazz->descriptor, method->name, method);
   3802 #endif
   3803 #if WITH_EXTRA_GC_CHECKS > 1
   3804             /*
   3805              * May also want to enable the memset() in the "invokeMethod"
   3806              * goto target in the portable interpreter.  That sets the stack
   3807              * to a pattern that makes referring to uninitialized data
   3808              * very obvious.
   3809              */
   3810 
   3811             if (first) {
   3812                 /*
   3813                  * First frame, isn't native, check the "alternate" saved PC
   3814                  * as a sanity check.
   3815                  *
   3816                  * It seems like we could check the second frame if the first
   3817                  * is native, since the PCs should be the same.  It turns out
   3818                  * this doesn't always work.  The problem is that we could
   3819                  * have calls in the sequence:
   3820                  *   interp method #2
   3821                  *   native method
   3822                  *   interp method #1
   3823                  *
   3824                  * and then GC while in the native method after returning
   3825                  * from interp method #2.  The currentPc on the stack is
   3826                  * for interp method #1, but thread->currentPc2 is still
   3827                  * set for the last thing interp method #2 did.
   3828                  *
   3829                  * This can also happen in normal execution:
   3830                  * - sget-object on not-yet-loaded class
   3831                  * - class init updates currentPc2
   3832                  * - static field init is handled by parsing annotations;
   3833                  *   static String init requires creation of a String object,
   3834                  *   which can cause a GC
   3835                  *
   3836                  * Essentially, any pattern that involves executing
   3837                  * interpreted code and then causes an allocation without
   3838                  * executing instructions in the original method will hit
   3839                  * this.  These are rare enough that the test still has
   3840                  * some value.
   3841                  */
   3842                 if (saveArea->xtra.currentPc != thread->currentPc2) {
   3843                     LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
   3844                         saveArea->xtra.currentPc, thread->currentPc2,
   3845                         method->clazz->descriptor, method->name, method->insns);
   3846                     if (saveArea->xtra.currentPc != NULL)
   3847                         LOGE("  pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
   3848                     if (thread->currentPc2 != NULL)
   3849                         LOGE("  pc2 inst = 0x%04x\n", *thread->currentPc2);
   3850                     dvmDumpThread(thread, false);
   3851                 }
   3852             } else {
   3853                 /*
   3854                  * It's unusual, but not impossible, for a non-first frame
   3855                  * to be at something other than a method invocation.  For
   3856                  * example, if we do a new-instance on a nonexistent class,
   3857                  * we'll have a lot of class loader activity on the stack
   3858                  * above the frame with the "new" operation.  Could also
   3859                  * happen while we initialize a Throwable when an instruction
   3860                  * fails.
   3861                  *
   3862                  * So there's not much we can do here to verify the PC,
   3863                  * except to verify that it's a GC point.
   3864                  */
   3865             }
   3866             assert(saveArea->xtra.currentPc != NULL);
   3867 #endif
   3868 
   3869             const RegisterMap* pMap;
   3870             const u1* regVector;
   3871             int i;
   3872 
   3873             Method* nonConstMethod = (Method*) method;  // quiet gcc
   3874             pMap = dvmGetExpandedRegisterMap(nonConstMethod);
   3875             if (pMap != NULL) {
   3876                 /* found map, get registers for this address */
   3877                 int addr = saveArea->xtra.currentPc - method->insns;
   3878                 regVector = dvmRegisterMapGetLine(pMap, addr);
   3879                 if (regVector == NULL) {
   3880                     LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
   3881                         method->clazz->descriptor, method->name, addr);
   3882                 } else {
   3883                     LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
   3884                         method->clazz->descriptor, method->name, addr,
   3885                         thread->threadId);
   3886                 }
   3887             } else {
   3888                 /*
   3889                  * No map found.  If precise GC is disabled this is
   3890                  * expected -- we don't create pointers to the map data even
   3891                  * if it's present -- but if it's enabled it means we're
   3892                  * unexpectedly falling back on a conservative scan, so it's
   3893                  * worth yelling a little.
   3894                  */
   3895                 if (gDvm.preciseGc) {
   3896                     LOGVV("PGC: no map for %s.%s\n",
   3897                         method->clazz->descriptor, method->name);
   3898                 }
   3899                 regVector = NULL;
   3900             }
   3901 
   3902             if (regVector == NULL) {
   3903                 /* conservative scan */
   3904                 for (i = method->registersSize - 1; i >= 0; i--) {
   3905                     u4 rval = *framePtr++;
   3906                     if (rval != 0 && (rval & 0x3) == 0) {
   3907                         dvmMarkIfObject((Object *)rval);
   3908                     }
   3909                 }
   3910             } else {
   3911                 /*
   3912                  * Precise scan.  v0 is at the lowest address on the
   3913                  * interpreted stack, and is the first bit in the register
   3914                  * vector, so we can walk through the register map and
   3915                  * memory in the same direction.
   3916                  *
   3917                  * A '1' bit indicates a live reference.
   3918                  */
   3919                 u2 bits = 1 << 1;
   3920                 for (i = method->registersSize - 1; i >= 0; i--) {
   3921                     u4 rval = *framePtr++;
   3922 
   3923                     bits >>= 1;
   3924                     if (bits == 1) {
   3925                         /* set bit 9 so we can tell when we're empty */
   3926                         bits = *regVector++ | 0x0100;
   3927                         LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
   3928                     }
   3929 
   3930                     if (rval != 0 && (bits & 0x01) != 0) {
   3931                         /*
   3932                          * Non-null, register marked as live reference.  This
   3933                          * should always be a valid object.
   3934                          */
   3935 #if WITH_EXTRA_GC_CHECKS > 0
   3936                         if ((rval & 0x3) != 0 ||
   3937                             !dvmIsValidObject((Object*) rval))
   3938                         {
   3939                             /* this is very bad */
   3940                             LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
   3941                                 method->registersSize-1 - i, rval);
   3942                         } else
   3943 #endif
   3944                         {
   3945                             dvmMarkObjectNonNull((Object *)rval);
   3946                         }
   3947                     } else {
   3948                         /*
   3949                          * Null or non-reference, do nothing at all.
   3950                          */
   3951 #if WITH_EXTRA_GC_CHECKS > 1
   3952                         if (dvmIsValidObject((Object*) rval)) {
   3953                             /* this is normal, but we feel chatty */
   3954                             LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
   3955                                 method->registersSize-1 - i, rval);
   3956                         }
   3957 #endif
   3958                     }
   3959                 }
   3960                 dvmReleaseRegisterMapLine(pMap, regVector);
   3961             }
   3962         }
   3963         /* else this is a break frame and there is nothing to mark, or
   3964          * this is a native method and the registers are just the "ins",
   3965          * copied from various registers in the caller's set.
   3966          */
   3967 
   3968 #if WITH_EXTRA_GC_CHECKS > 1
   3969         first = false;
   3970 #endif
   3971 
   3972         /* Don't fall into an infinite loop if things get corrupted.
   3973          */
   3974         assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
   3975                saveArea->prevFrame == NULL);
   3976         framePtr = saveArea->prevFrame;
   3977     }
   3978 }
   3979 
   3980 static void gcScanReferenceTable(ReferenceTable *refTable)
   3981 {
   3982     Object **op;
   3983 
   3984     //TODO: these asserts are overkill; turn them off when things stablize.
   3985     assert(refTable != NULL);
   3986     assert(refTable->table != NULL);
   3987     assert(refTable->nextEntry != NULL);
   3988     assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
   3989     assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
   3990 
   3991     op = refTable->table;
   3992     while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
   3993         dvmMarkObjectNonNull(*(op++));
   3994     }
   3995 }
   3996 
   3997 static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
   3998 {
   3999     Object** op = pRefTable->table;
   4000     int numEntries = dvmIndirectRefTableEntries(pRefTable);
   4001     int i;
   4002 
   4003     for (i = 0; i < numEntries; i++) {
   4004         Object* obj = *op;
   4005         if (obj != NULL)
   4006             dvmMarkObjectNonNull(obj);
   4007         op++;
   4008     }
   4009 }
   4010 
   4011 /*
   4012  * Scan a Thread and mark any objects it references.
   4013  */
   4014 static void gcScanThread(Thread *thread)
   4015 {
   4016     assert(thread != NULL);
   4017 
   4018     /*
   4019      * The target thread must be suspended or in a state where it can't do
   4020      * any harm (e.g. in Object.wait()).  The only exception is the current
   4021      * thread, which will still be active and in the "running" state.
   4022      *
   4023      * (Newly-created threads shouldn't be able to shift themselves to
   4024      * RUNNING without a suspend-pending check, so this shouldn't cause
   4025      * a false-positive.)
   4026      */
   4027     if (thread->status == THREAD_RUNNING && !thread->isSuspended &&
   4028         thread != dvmThreadSelf())
   4029     {
   4030         Thread* self = dvmThreadSelf();
   4031         LOGW("threadid=%d: BUG: GC scanning a running thread (%d)\n",
   4032             self->threadId, thread->threadId);
   4033         dvmDumpThread(thread, true);
   4034         LOGW("Found by:\n");
   4035         dvmDumpThread(self, false);
   4036 
   4037         /* continue anyway? */
   4038         dvmAbort();
   4039     }
   4040 
   4041     HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
   4042 
   4043     dvmMarkObject(thread->threadObj);   // could be NULL, when constructing
   4044 
   4045     HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
   4046 
   4047     dvmMarkObject(thread->exception);   // usually NULL
   4048     gcScanReferenceTable(&thread->internalLocalRefTable);
   4049 
   4050     HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
   4051 
   4052 #ifdef USE_INDIRECT_REF
   4053     gcScanIndirectRefTable(&thread->jniLocalRefTable);
   4054 #else
   4055     gcScanReferenceTable(&thread->jniLocalRefTable);
   4056 #endif
   4057 
   4058     if (thread->jniMonitorRefTable.table != NULL) {
   4059         HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
   4060 
   4061         gcScanReferenceTable(&thread->jniMonitorRefTable);
   4062     }
   4063 
   4064     HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
   4065 
   4066     gcScanInterpStackReferences(thread);
   4067 
   4068     HPROF_CLEAR_GC_SCAN_STATE();
   4069 }
   4070 
   4071 static void gcScanAllThreads()
   4072 {
   4073     Thread *thread;
   4074 
   4075     /* Lock the thread list so we can safely use the
   4076      * next/prev pointers.
   4077      */
   4078     dvmLockThreadList(dvmThreadSelf());
   4079 
   4080     for (thread = gDvm.threadList; thread != NULL;
   4081             thread = thread->next)
   4082     {
   4083         /* We need to scan our own stack, so don't special-case
   4084          * the current thread.
   4085          */
   4086         gcScanThread(thread);
   4087     }
   4088 
   4089     dvmUnlockThreadList();
   4090 }
   4091 
   4092 void dvmGcScanRootThreadGroups()
   4093 {
   4094     /* We scan the VM's list of threads instead of going
   4095      * through the actual ThreadGroups, but it should be
   4096      * equivalent.
   4097      *
   4098      * This assumes that the ThreadGroup class object is in
   4099      * the root set, which should always be true;  it's
   4100      * loaded by the built-in class loader, which is part
   4101      * of the root set.
   4102      */
   4103     gcScanAllThreads();
   4104 }
   4105