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