OSDN Git Service

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