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