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