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