2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include "utils/threads.h" // need Android thread priorities
26 #include <sys/resource.h>
30 #if defined(HAVE_PRCTL)
31 #include <sys/prctl.h>
34 /* desktop Linux needs a little help with gettid() */
35 #if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
37 # include <linux/unistd.h>
39 _syscall0(pid_t,gettid)
41 pid_t gettid() { return syscall(__NR_gettid);}
46 // Change this to enable logging on cgroup errors
47 #define ENABLE_CGROUP_ERR_LOGGING 0
49 // change this to LOGV/LOGD to debug thread activity
50 #define LOG_THREAD LOGVV
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.
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.
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.
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.
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).
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.
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.
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.
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
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).
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().
129 Alternate implementation (signal-based):
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.
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
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.
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).
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:
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
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.
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.)
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.
179 An ordering should be established for all locks to avoid deadlocks.
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.
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.
188 There are (at least) two ways to handle the incoming signals:
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.
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.
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.
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)
217 #define kMaxThreadId ((1<<15) - 1)
218 #define kMainThreadId ((1<<1) | 1)
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);
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).
242 bool dvmThreadStartup(void)
246 /* allocate a TLS slot */
247 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
248 LOGE("ERROR: pthread_key_create failed\n");
252 /* test our pthread lib */
253 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
254 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
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);
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.
275 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
277 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
279 thread = allocThread(gDvm.stackSize);
283 /* switch mode for when we run initializers */
284 thread->status = THREAD_RUNNING;
287 * We need to assign the threadId early so we can lock/notify
288 * object monitors. We'll set the "threadObj" field later.
290 prepareThread(thread);
291 gDvm.threadList = thread;
293 #ifdef COUNT_PRECISE_METHODS
294 gDvm.preciseMethods = dvmPointerSetAlloc(200);
301 * We're a little farther up now, and can load some basic classes.
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.
307 bool dvmThreadObjStartup(void)
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.
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)
323 LOGE("Could not find one or more essential thread classes\n");
328 * Cache field offsets. This makes things a little faster, at the
329 * expense of hard-coding non-public field names into the VM.
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");
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)
351 LOGE("Unable to find all fields in java.lang.Thread\n");
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)
363 LOGE("Unable to find all fields in java.lang.VMThread\n");
368 * Cache the vtable offset for "run()".
370 * We don't want to keep the Method* because then we won't find see
371 * methods defined in subclasses.
374 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
376 LOGE("Unable to find run() in java.lang.Thread\n");
379 gDvm.voffJavaLangThread_run = meth->methodIndex;
382 * Cache vtable offsets for ThreadGroup methods.
384 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
385 "removeThread", "(Ljava/lang/Thread;)V");
387 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
390 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
396 * All threads should be stopped by now. Clean up some thread globals.
398 void dvmThreadShutdown(void)
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;
407 dvmFreeBitVector(gDvm.threadIdMap);
409 dvmFreeMonitorList();
411 pthread_key_delete(gDvm.pthreadKeySelf);
416 * Grab the suspend count global lock.
418 static inline void lockThreadSuspendCount(void)
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.
425 * This lock is always held for very brief periods, so as long as
426 * mutex ordering is respected we shouldn't stall.
428 int cc = pthread_mutex_lock(&gDvm.threadSuspendCountLock);
433 * Release the suspend count global lock.
435 static inline void unlockThreadSuspendCount(void)
437 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
441 * Grab the thread list global lock.
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.
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.
452 void dvmLockThreadList(Thread* self)
454 ThreadStatus oldStatus;
456 if (self == NULL) /* try to get it from TLS */
457 self = dvmThreadSelf();
460 oldStatus = self->status;
461 self->status = THREAD_VMWAIT;
463 /* happens for JNI AttachCurrentThread [not anymore?] */
464 //LOGW("NULL self in dvmLockThreadList\n");
465 oldStatus = -1; // shut up gcc
468 int cc = pthread_mutex_lock(&gDvm.threadListLock);
472 self->status = oldStatus;
476 * Release the thread list global lock.
478 void dvmUnlockThreadList(void)
480 int cc = pthread_mutex_unlock(&gDvm.threadListLock);
485 * Convert SuspendCause to a string.
487 static const char* getSuspendCauseStr(SuspendCause why)
490 case SUSPEND_NOT: return "NOT?";
491 case SUSPEND_FOR_GC: return "gc";
492 case SUSPEND_FOR_DEBUG: return "debug";
493 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
494 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
495 default: return "UNKNOWN";
500 * Grab the "thread suspend" lock. This is required to prevent the
501 * GC and the debugger from simultaneously suspending all threads.
503 * If we fail to get the lock, somebody else is trying to suspend all
504 * threads -- including us. If we go to sleep on the lock we'll deadlock
505 * the VM. Loop until we get it or somebody puts us to sleep.
507 static void lockThreadSuspend(const char* who, SuspendCause why)
509 const int kSpinSleepTime = 3*1000*1000; /* 3s */
510 u8 startWhen = 0; // init req'd to placate gcc
515 cc = pthread_mutex_trylock(&gDvm._threadSuspendLock);
517 if (!dvmCheckSuspendPending(NULL)) {
519 * Could be that a resume-all is in progress, and something
520 * grabbed the CPU when the wakeup was broadcast. The thread
521 * performing the resume hasn't had a chance to release the
522 * thread suspend lock. (Should no longer be an issue --
523 * we now release before broadcast.)
525 * Could be we hit the window as a suspend was started,
526 * and the lock has been grabbed but the suspend counts
527 * haven't been incremented yet.
529 * Could be an unusual JNI thread-attach thing.
531 * Could be the debugger telling us to resume at roughly
532 * the same time we're posting an event.
534 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
535 " it's held, no suspend pending\n",
536 dvmThreadSelf()->threadId, who, getSuspendCauseStr(why));
538 /* we suspended; reset timeout */
542 /* give the lock-holder a chance to do some work */
544 startWhen = dvmGetRelativeTimeUsec();
545 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
546 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
548 dvmThreadSelf()->threadId, who, getSuspendCauseStr(why));
549 /* threads are not suspended, thread dump could crash */
550 dvmDumpAllThreads(false);
559 * Release the "thread suspend" lock.
561 static inline void unlockThreadSuspend(void)
563 int cc = pthread_mutex_unlock(&gDvm._threadSuspendLock);
569 * Kill any daemon threads that still exist. All of ours should be
570 * stopped, so these should be Thread objects or JNI-attached threads
571 * started by the application. Actively-running threads are likely
572 * to crash the process if they continue to execute while the VM
573 * shuts down, so we really need to kill or suspend them. (If we want
574 * the VM to restart within this process, we need to kill them, but that
575 * leaves open the possibility of orphaned resources.)
577 * Waiting for the thread to suspend may be unwise at this point, but
578 * if one of these is wedged in a critical section then we probably
579 * would've locked up on the last GC attempt.
581 * It's possible for this function to get called after a failed
582 * initialization, so be careful with assumptions about the environment.
584 void dvmSlayDaemons(void)
586 Thread* self = dvmThreadSelf();
593 //dvmEnterCritical(self);
594 dvmLockThreadList(self);
596 target = gDvm.threadList;
597 while (target != NULL) {
598 if (target == self) {
599 target = target->next;
603 if (!dvmGetFieldBoolean(target->threadObj,
604 gDvm.offJavaLangThread_daemon))
606 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
607 self->threadId, target->threadId);
608 target = target->next;
612 LOGI("threadid=%d: killing leftover daemon threadid=%d [TODO]\n",
613 self->threadId, target->threadId);
614 // TODO: suspend and/or kill the thread
615 // (at the very least, we can "rescind their JNI privileges")
617 /* remove from list */
618 nextTarget = target->next;
619 unlinkThread(target);
625 dvmUnlockThreadList();
626 //dvmExitCritical(self);
631 * Finish preparing the parts of the Thread struct required to support
634 bool dvmPrepMainForJni(JNIEnv* pEnv)
638 /* main thread is always first in list at this point */
639 self = gDvm.threadList;
640 assert(self->threadId == kMainThreadId);
642 /* create a "fake" JNI frame at the top of the main thread interp stack */
643 if (!createFakeEntryFrame(self))
646 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
647 dvmSetJniEnvThreadId(pEnv, self);
648 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
655 * Finish preparing the main thread, allocating some objects to represent
656 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
657 * This will execute some interpreted code (e.g. class initializers).
659 bool dvmPrepMainThread(void)
665 StringObject* threadNameStr;
669 LOGV("+++ finishing prep on main VM thread\n");
671 /* main thread is always first in list at this point */
672 thread = gDvm.threadList;
673 assert(thread->threadId == kMainThreadId);
676 * Make sure the classes are initialized. We have to do this before
677 * we create an instance of them.
679 if (!dvmInitClass(gDvm.classJavaLangClass)) {
680 LOGE("'Class' class failed to initialize\n");
683 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
684 !dvmInitClass(gDvm.classJavaLangThread) ||
685 !dvmInitClass(gDvm.classJavaLangVMThread))
687 LOGE("thread classes failed to initialize\n");
691 groupObj = dvmGetMainThreadGroup();
692 if (groupObj == NULL)
696 * Allocate and construct a Thread with the internal-creation
699 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
700 if (threadObj == NULL) {
701 LOGE("unable to allocate main thread object\n");
704 dvmReleaseTrackedAlloc(threadObj, NULL);
706 threadNameStr = dvmCreateStringFromCstr("main", ALLOC_DEFAULT);
707 if (threadNameStr == NULL)
709 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
711 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
712 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
713 assert(init != NULL);
714 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
715 THREAD_NORM_PRIORITY, false);
716 if (dvmCheckException(thread)) {
717 LOGE("exception thrown while constructing main thread object\n");
722 * Allocate and construct a VMThread.
724 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
725 if (vmThreadObj == NULL) {
726 LOGE("unable to allocate main vmthread object\n");
729 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
731 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
732 "(Ljava/lang/Thread;)V");
733 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
734 if (dvmCheckException(thread)) {
735 LOGE("exception thrown while constructing main vmthread object\n");
739 /* set the VMThread.vmData field to our Thread struct */
740 assert(gDvm.offJavaLangVMThread_vmData != 0);
741 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
744 * Stuff the VMThread back into the Thread. From this point on, other
745 * Threads will see that this Thread is running (at least, they would,
746 * if there were any).
748 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
751 thread->threadObj = threadObj;
754 * Set the context class loader. This invokes a ClassLoader method,
755 * which could conceivably call Thread.currentThread(), so we want the
756 * Thread to be fully configured before we do this.
758 Object* systemLoader = dvmGetSystemClassLoader();
759 if (systemLoader == NULL) {
760 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
763 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
764 "contextClassLoader", "Ljava/lang/ClassLoader;");
765 if (ctxtClassLoaderOffset < 0) {
766 LOGE("Unable to find contextClassLoader field in Thread\n");
769 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
772 * Finish our thread prep.
775 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
776 gDvm.nonDaemonThreadCount++;
783 * Alloc and initialize a Thread struct.
785 * "threadObj" is the java.lang.Thread object. It will be NULL for the
786 * main VM thread, but non-NULL for everything else.
788 * Does not create any objects, just stuff on the system (malloc) heap. (If
789 * this changes, we need to use ALLOC_NO_GC. And also verify that we're
790 * ready to load classes at the time this is called.)
792 static Thread* allocThread(int interpStackSize)
797 thread = (Thread*) calloc(1, sizeof(Thread));
801 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
803 thread->status = THREAD_INITIALIZING;
804 thread->suspendCount = 0;
806 #ifdef WITH_ALLOC_LIMITS
807 thread->allocLimit = -1;
811 * Allocate and initialize the interpreted code stack. We essentially
812 * "lose" the alloc pointer, which points at the bottom of the stack,
813 * but we can get it back later because we know how big the stack is.
815 * The stack must be aligned on a 4-byte boundary.
817 #ifdef MALLOC_INTERP_STACK
818 stackBottom = (u1*) malloc(interpStackSize);
819 if (stackBottom == NULL) {
823 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
825 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
826 MAP_PRIVATE | MAP_ANON, -1, 0);
827 if (stackBottom == MAP_FAILED) {
833 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
834 thread->interpStackSize = interpStackSize;
835 thread->interpStackStart = stackBottom + interpStackSize;
836 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
838 /* give the thread code a chance to set things up */
839 dvmInitInterpStack(thread, interpStackSize);
845 * Get a meaningful thread ID. At present this only has meaning under Linux,
846 * where getpid() and gettid() sometimes agree and sometimes don't depending
847 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
849 pid_t dvmGetSysThreadId(void)
859 * Finish initialization of a Thread struct.
861 * This must be called while executing in the new thread, but before the
862 * thread is added to the thread list.
864 * *** NOTE: The threadListLock must be held by the caller (needed for
867 static bool prepareThread(Thread* thread)
869 assignThreadId(thread);
870 thread->handle = pthread_self();
871 thread->systemTid = dvmGetSysThreadId();
873 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
875 setThreadSelf(thread);
877 LOGV("threadid=%d: interp stack at %p\n",
878 thread->threadId, thread->interpStackStart - thread->interpStackSize);
881 * Initialize invokeReq.
883 pthread_mutex_init(&thread->invokeReq.lock, NULL);
884 pthread_cond_init(&thread->invokeReq.cv, NULL);
887 * Initialize our reference tracking tables.
889 * The JNI local ref table *must* be fixed-size because we keep pointers
890 * into the table in our stack frames.
892 * Most threads won't use jniMonitorRefTable, so we clear out the
893 * structure but don't call the init function (which allocs storage).
895 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
896 kJniLocalRefMax, kJniLocalRefMax))
898 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
899 kInternalRefDefault, kInternalRefMax))
902 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
908 * Remove a thread from the internal list.
909 * Clear out the links to make it obvious that the thread is
910 * no longer on the list. Caller must hold gDvm.threadListLock.
912 static void unlinkThread(Thread* thread)
914 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
915 if (thread == gDvm.threadList) {
916 assert(thread->prev == NULL);
917 gDvm.threadList = thread->next;
919 assert(thread->prev != NULL);
920 thread->prev->next = thread->next;
922 if (thread->next != NULL)
923 thread->next->prev = thread->prev;
924 thread->prev = thread->next = NULL;
928 * Free a Thread struct, and all the stuff allocated within.
930 static void freeThread(Thread* thread)
935 /* thread->threadId is zero at this point */
936 LOGVV("threadid=%d: freeing\n", thread->threadId);
938 if (thread->interpStackStart != NULL) {
939 u1* interpStackBottom;
941 interpStackBottom = thread->interpStackStart;
942 interpStackBottom -= thread->interpStackSize;
943 #ifdef MALLOC_INTERP_STACK
944 free(interpStackBottom);
946 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
947 LOGW("munmap(thread stack) failed\n");
951 dvmClearReferenceTable(&thread->jniLocalRefTable);
952 dvmClearReferenceTable(&thread->internalLocalRefTable);
953 if (&thread->jniMonitorRefTable.table != NULL)
954 dvmClearReferenceTable(&thread->jniMonitorRefTable);
960 * Like pthread_self(), but on a Thread*.
962 Thread* dvmThreadSelf(void)
964 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
968 * Explore our sense of self. Stuffs the thread pointer into TLS.
970 static void setThreadSelf(Thread* thread)
974 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
977 * Sometimes this fails under Bionic with EINVAL during shutdown.
978 * This can happen if the timing is just right, e.g. a thread
979 * fails to attach during shutdown, but the "fail" path calls
980 * here to ensure we clean up after ourselves.
982 if (thread != NULL) {
983 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
984 dvmAbort(); /* the world is fundamentally hosed */
990 * This is associated with the pthreadKeySelf key. It's called by the
991 * pthread library when a thread is exiting and the "self" pointer in TLS
992 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
993 * operation this should never be called.
995 * This is mainly of use to ensure that we don't leak resources if, for
996 * example, a thread attaches itself to us with AttachCurrentThread and
997 * then exits without notifying the VM.
999 static void threadExitCheck(void* arg)
1001 Thread* thread = (Thread*) arg;
1003 LOGI("In threadExitCheck %p\n", arg);
1004 assert(thread != NULL);
1006 if (thread->status != THREAD_ZOMBIE) {
1007 /* TODO: instead of failing, we could call dvmDetachCurrentThread() */
1008 LOGE("Native thread exited without telling us\n");
1015 * Assign the threadId. This needs to be a small integer so that our
1016 * "thin" locks fit in a small number of bits.
1018 * We reserve zero for use as an invalid ID.
1020 * This must be called with threadListLock held (unless we're still
1021 * initializing the system).
1023 static void assignThreadId(Thread* thread)
1025 /* Find a small unique integer. threadIdMap is a vector of
1026 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1027 * bit, meaning that it will always be < kMaxThreadId.
1029 * The thin locking magic requires that the low bit is always
1030 * set, so we do it once, here.
1032 int num = dvmAllocBit(gDvm.threadIdMap);
1034 LOGE("Ran out of thread IDs\n");
1035 dvmAbort(); // TODO: make this a non-fatal error result
1038 thread->threadId = ((num + 1) << 1) | 1;
1040 assert(thread->threadId != 0);
1041 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1045 * Give back the thread ID.
1047 static void releaseThreadId(Thread* thread)
1049 assert(thread->threadId > 0);
1050 dvmClearBit(gDvm.threadIdMap, (thread->threadId >> 1) - 1);
1051 thread->threadId = 0;
1056 * Add a stack frame that makes it look like the native code in the main
1057 * thread was originally invoked from interpreted code. This gives us a
1058 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1059 * VM begins by executing "main" in a class, so in a way this brings us
1060 * closer to the spec.
1062 static bool createFakeEntryFrame(Thread* thread)
1064 assert(thread->threadId == kMainThreadId); // main thread only
1066 /* find the method on first use */
1067 if (gDvm.methFakeNativeEntry == NULL) {
1068 ClassObject* nativeStart;
1071 nativeStart = dvmFindSystemClassNoInit(
1072 "Ldalvik/system/NativeStart;");
1073 if (nativeStart == NULL) {
1074 LOGE("Unable to find dalvik.system.NativeStart class\n");
1079 * Because we are creating a frame that represents application code, we
1080 * want to stuff the application class loader into the method's class
1081 * loader field, even though we're using the system class loader to
1082 * load it. This makes life easier over in JNI FindClass (though it
1083 * could bite us in other ways).
1085 * Unfortunately this is occurring too early in the initialization,
1086 * of necessity coming before JNI is initialized, and we're not quite
1087 * ready to set up the application class loader.
1089 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1090 * and check it in FindClass. The method is private so nobody else
1093 //nativeStart->classLoader = dvmGetSystemClassLoader();
1095 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1096 "main", "([Ljava/lang/String;)V");
1097 if (mainMeth == NULL) {
1098 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1102 gDvm.methFakeNativeEntry = mainMeth;
1105 return dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry);
1110 * Add a stack frame that makes it look like the native thread has been
1111 * executing interpreted code. This gives us a place to hang JNI local
1114 static bool createFakeRunFrame(Thread* thread)
1116 ClassObject* nativeStart;
1119 assert(thread->threadId != 1); // not for main thread
1122 dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
1123 if (nativeStart == NULL) {
1124 LOGE("Unable to find dalvik.system.NativeStart class\n");
1128 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1129 if (runMeth == NULL) {
1130 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1134 return dvmPushJNIFrame(thread, runMeth);
1138 * Helper function to set the name of the current thread
1140 static void setThreadName(const char *threadName)
1142 #if defined(HAVE_PRCTL)
1145 const char *s = threadName;
1147 if (*s == '.') hasDot = 1;
1148 else if (*s == '@') hasAt = 1;
1151 int len = s - threadName;
1152 if (len < 15 || hasAt || !hasDot) {
1155 s = threadName + len - 15;
1157 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
1162 * Create a thread as a result of java.lang.Thread.start().
1164 * We do have to worry about some concurrency problems, e.g. programs
1165 * that try to call Thread.start() on the same object from multiple threads.
1166 * (This will fail for all but one, but we have to make sure that it succeeds
1169 * Some of the complexity here arises from our desire to mimic the
1170 * Thread vs. VMThread class decomposition we inherited. We've been given
1171 * a Thread, and now we need to create a VMThread and then populate both
1172 * objects. We also need to create one of our internal Thread objects.
1174 * Pass in a stack size of 0 to get the default.
1176 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1178 pthread_attr_t threadAttr;
1179 pthread_t threadHandle;
1181 Thread* newThread = NULL;
1182 Object* vmThreadObj = NULL;
1185 assert(threadObj != NULL);
1188 dvmThrowException("Ljava/lang/IllegalStateException;",
1189 "No new threads in -Xzygote mode");
1194 self = dvmThreadSelf();
1195 if (reqStackSize == 0)
1196 stackSize = gDvm.stackSize;
1197 else if (reqStackSize < kMinStackSize)
1198 stackSize = kMinStackSize;
1199 else if (reqStackSize > kMaxStackSize)
1200 stackSize = kMaxStackSize;
1202 stackSize = reqStackSize;
1204 pthread_attr_init(&threadAttr);
1205 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1208 * To minimize the time spent in the critical section, we allocate the
1209 * vmThread object here.
1211 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1212 if (vmThreadObj == NULL)
1215 newThread = allocThread(stackSize);
1216 if (newThread == NULL)
1218 newThread->threadObj = threadObj;
1220 assert(newThread->status == THREAD_INITIALIZING);
1223 * We need to lock out other threads while we test and set the
1224 * "vmThread" field in java.lang.Thread, because we use that to determine
1225 * if this thread has been started before. We use the thread list lock
1226 * because it's handy and we're going to need to grab it again soon
1229 dvmLockThreadList(self);
1231 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1232 dvmUnlockThreadList();
1233 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1234 "thread has already been started");
1239 * There are actually three data structures: Thread (object), VMThread
1240 * (object), and Thread (C struct). All of them point to at least one
1243 * As soon as "VMThread.vmData" is assigned, other threads can start
1244 * making calls into us (e.g. setPriority).
1246 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1247 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1250 * Thread creation might take a while, so release the lock.
1252 dvmUnlockThreadList();
1255 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1256 cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1258 oldStatus = dvmChangeStatus(self, oldStatus);
1262 * Failure generally indicates that we have exceeded system
1263 * resource limits. VirtualMachineError is probably too severe,
1264 * so use OutOfMemoryError.
1266 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1268 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1270 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1271 "thread creation failed");
1276 * We need to wait for the thread to start. Otherwise, depending on
1277 * the whims of the OS scheduler, we could return and the code in our
1278 * thread could try to do operations on the new thread before it had
1279 * finished starting.
1281 * The new thread will lock the thread list, change its state to
1282 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1283 * on gDvm.threadStartCond (which uses the thread list lock). This
1284 * thread (the parent) will either see that the thread is already ready
1285 * after we grab the thread list lock, or will be awakened from the
1286 * condition variable on the broadcast.
1288 * We don't want to stall the rest of the VM while the new thread
1289 * starts, which can happen if the GC wakes up at the wrong moment.
1290 * So, we change our own status to VMWAIT, and self-suspend if
1291 * necessary after we finish adding the new thread.
1294 * We have to deal with an odd race with the GC/debugger suspension
1295 * mechanism when creating a new thread. The information about whether
1296 * or not a thread should be suspended is contained entirely within
1297 * the Thread struct; this is usually cleaner to deal with than having
1298 * one or more globally-visible suspension flags. The trouble is that
1299 * we could create the thread while the VM is trying to suspend all
1300 * threads. The suspend-count won't be nonzero for the new thread,
1301 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1303 * The easiest way to deal with this is to prevent the new thread from
1304 * running until the parent says it's okay. This results in the
1305 * following (correct) sequence of events for a "badly timed" GC
1306 * (where '-' is us, 'o' is the child, and '+' is some other thread):
1308 * - call pthread_create()
1309 * - lock thread list
1310 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1311 * - sleep on condition var (mutex = thread list lock) until child starts
1312 * + GC triggered by another thread
1313 * + thread list locked; suspend counts updated; thread list unlocked
1314 * + loop waiting for all runnable threads to suspend
1315 * + success, start GC
1316 * o child thread wakes, signals condition var to wake parent
1317 * o child waits for parent ack on condition variable
1318 * - we wake up, locking thread list
1319 * - add child to thread list
1320 * - unlock thread list
1321 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1322 * + GC finishes; all threads in thread list are resumed
1323 * - lock thread list
1324 * - set child to THREAD_VMWAIT, and signal it to start
1325 * - unlock thread list
1327 * o child changes state to THREAD_RUNNING
1329 * The above shows the GC starting up during thread creation, but if
1330 * it starts anywhere after VMThread.create() is called it will
1331 * produce the same series of events.
1333 * Once the child is in the thread list, it will be suspended and
1334 * resumed like any other thread. In the above scenario the resume-all
1335 * code will try to resume the new thread, which was never actually
1336 * suspended, and try to decrement the child's thread suspend count to -1.
1337 * We can catch this in the resume-all code.
1339 * Bouncing back and forth between threads like this adds a small amount
1340 * of scheduler overhead to thread startup.
1342 * One alternative to having the child wait for the parent would be
1343 * to have the child inherit the parents' suspension count. This
1344 * would work for a GC, since we can safely assume that the parent
1345 * thread didn't cause it, but we must only do so if the parent suspension
1346 * was caused by a suspend-all. If the parent was being asked to
1347 * suspend singly by the debugger, the child should not inherit the value.
1349 * We could also have a global "new thread suspend count" that gets
1350 * picked up by new threads before changing state to THREAD_RUNNING.
1351 * This would be protected by the thread list lock and set by a
1354 dvmLockThreadList(self);
1355 assert(self->status == THREAD_RUNNING);
1356 self->status = THREAD_VMWAIT;
1357 while (newThread->status != THREAD_STARTING)
1358 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1360 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1361 newThread->next = gDvm.threadList->next;
1362 if (newThread->next != NULL)
1363 newThread->next->prev = newThread;
1364 newThread->prev = gDvm.threadList;
1365 gDvm.threadList->next = newThread;
1367 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1368 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1370 dvmUnlockThreadList();
1372 /* change status back to RUNNING, self-suspending if necessary */
1373 dvmChangeStatus(self, THREAD_RUNNING);
1376 * Tell the new thread to start.
1378 * We must hold the thread list lock before messing with another thread.
1379 * In the general case we would also need to verify that newThread was
1380 * still in the thread list, but in our case the thread has not started
1381 * executing user code and therefore has not had a chance to exit.
1383 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1384 * comes with a suspend-pending check.
1386 dvmLockThreadList(self);
1388 assert(newThread->status == THREAD_STARTING);
1389 newThread->status = THREAD_VMWAIT;
1390 pthread_cond_broadcast(&gDvm.threadStartCond);
1392 dvmUnlockThreadList();
1394 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1398 freeThread(newThread);
1399 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1404 * pthread entry function for threads started from interpreted code.
1406 static void* interpThreadStart(void* arg)
1408 Thread* self = (Thread*) arg;
1410 char *threadName = dvmGetThreadName(self);
1411 setThreadName(threadName);
1415 * Finish initializing the Thread struct.
1417 prepareThread(self);
1419 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1422 * Change our status and wake our parent, who will add us to the
1423 * thread list and advance our state to VMWAIT.
1425 dvmLockThreadList(self);
1426 self->status = THREAD_STARTING;
1427 pthread_cond_broadcast(&gDvm.threadStartCond);
1430 * Wait until the parent says we can go. Assuming there wasn't a
1431 * suspend pending, this will happen immediately. When it completes,
1432 * we're full-fledged citizens of the VM.
1434 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1435 * because the pthread_cond_wait below needs to reacquire a lock that
1436 * suspend-all is also interested in. If we get unlucky, the parent could
1437 * change us to THREAD_RUNNING, then a GC could start before we get
1438 * signaled, and suspend-all will grab the thread list lock and then
1439 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1440 * trying to get the lock.
1442 while (self->status != THREAD_VMWAIT)
1443 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1445 dvmUnlockThreadList();
1448 * Add a JNI context.
1450 self->jniEnv = dvmCreateJNIEnv(self);
1453 * Change our state so the GC will wait for us from now on. If a GC is
1454 * in progress this call will suspend us.
1456 dvmChangeStatus(self, THREAD_RUNNING);
1459 * Notify the debugger & DDM. The debugger notification may cause
1460 * us to suspend ourselves (and others).
1462 if (gDvm.debuggerConnected)
1463 dvmDbgPostThreadStart(self);
1466 * Set the system thread priority according to the Thread object's
1467 * priority level. We don't usually need to do this, because both the
1468 * Thread object and system thread priorities inherit from parents. The
1469 * tricky case is when somebody creates a Thread object, calls
1470 * setPriority(), and then starts the thread. We could manage this with
1471 * a "needs priority update" flag to avoid the redundant call.
1473 int priority = dvmGetFieldBoolean(self->threadObj,
1474 gDvm.offJavaLangThread_priority);
1475 dvmChangeThreadPriority(self, priority);
1478 * Execute the "run" method.
1480 * At this point our stack is empty, so somebody who comes looking for
1481 * stack traces right now won't have much to look at. This is normal.
1483 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1486 LOGV("threadid=%d: calling run()\n", self->threadId);
1487 assert(strcmp(run->name, "run") == 0);
1488 dvmCallMethod(self, run, self->threadObj, &unused);
1489 LOGV("threadid=%d: exiting\n", self->threadId);
1492 * Remove the thread from various lists, report its death, and free
1495 dvmDetachCurrentThread();
1501 * The current thread is exiting with an uncaught exception. The
1502 * Java programming language allows the application to provide a
1503 * thread-exit-uncaught-exception handler for the VM, for a specific
1504 * Thread, and for all threads in a ThreadGroup.
1506 * Version 1.5 added the per-thread handler. We need to call
1507 * "uncaughtException" in the handler object, which is either the
1508 * ThreadGroup object or the Thread-specific handler.
1510 static void threadExitUncaughtException(Thread* self, Object* group)
1514 ClassObject* throwable;
1515 Method* uncaughtHandler = NULL;
1516 InstField* threadHandler;
1518 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1519 self->threadId, group);
1520 assert(group != NULL);
1523 * Get a pointer to the exception, then clear out the one in the
1524 * thread. We don't want to have it set when executing interpreted code.
1526 exception = dvmGetException(self);
1527 dvmAddTrackedAlloc(exception, self);
1528 dvmClearException(self);
1531 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1532 * else use "group" (which is an instance of UncaughtExceptionHandler).
1534 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1535 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1536 if (threadHandler == NULL) {
1537 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1540 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1541 if (handlerObj == NULL)
1545 * Find the "uncaughtHandler" field in this object.
1547 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1548 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1550 if (uncaughtHandler != NULL) {
1551 //LOGI("+++ calling %s.uncaughtException\n",
1552 // handlerObj->clazz->descriptor);
1554 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1555 self->threadObj, exception);
1557 /* restore it and dump a stack trace */
1558 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1559 handlerObj->clazz->descriptor);
1560 dvmSetException(self, exception);
1561 dvmLogExceptionStackTrace();
1565 dvmReleaseTrackedAlloc(exception, self);
1570 * Create an internal VM thread, for things like JDWP and finalizers.
1572 * The easiest way to do this is create a new thread and then use the
1573 * JNI AttachCurrentThread implementation.
1575 * This does not return until after the new thread has begun executing.
1577 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1578 InternalThreadStart func, void* funcArg)
1580 InternalStartArgs* pArgs;
1581 Object* systemGroup;
1582 pthread_attr_t threadAttr;
1583 volatile Thread* newThread = NULL;
1584 volatile int createStatus = 0;
1586 systemGroup = dvmGetSystemThreadGroup();
1587 if (systemGroup == NULL)
1590 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1592 pArgs->funcArg = funcArg;
1593 pArgs->name = strdup(name); // storage will be owned by new thread
1594 pArgs->group = systemGroup;
1595 pArgs->isDaemon = true;
1596 pArgs->pThread = &newThread;
1597 pArgs->pCreateStatus = &createStatus;
1599 pthread_attr_init(&threadAttr);
1600 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1602 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1605 LOGE("internal thread creation failed\n");
1612 * Wait for the child to start. This gives us an opportunity to make
1613 * sure that the thread started correctly, and allows our caller to
1614 * assume that the thread has started running.
1616 * Because we aren't holding a lock across the thread creation, it's
1617 * possible that the child will already have completed its
1618 * initialization. Because the child only adjusts "createStatus" while
1619 * holding the thread list lock, the initial condition on the "while"
1620 * loop will correctly avoid the wait if this occurs.
1622 * It's also possible that we'll have to wait for the thread to finish
1623 * being created, and as part of allocating a Thread object it might
1624 * need to initiate a GC. We switch to VMWAIT while we pause.
1626 Thread* self = dvmThreadSelf();
1627 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1628 dvmLockThreadList(self);
1629 while (createStatus == 0)
1630 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1632 if (newThread == NULL) {
1633 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1634 assert(createStatus < 0);
1635 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1636 dvmUnlockThreadList();
1637 dvmChangeStatus(self, oldStatus);
1641 /* thread could be in any state now (except early init states) */
1642 //assert(newThread->status == THREAD_RUNNING);
1644 dvmUnlockThreadList();
1645 dvmChangeStatus(self, oldStatus);
1651 * pthread entry function for internally-created threads.
1653 * We are expected to free "arg" and its contents. If we're a daemon
1654 * thread, and we get cancelled abruptly when the VM shuts down, the
1655 * storage won't be freed. If this becomes a concern we can make a copy
1658 static void* internalThreadStart(void* arg)
1660 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1661 JavaVMAttachArgs jniArgs;
1663 jniArgs.version = JNI_VERSION_1_2;
1664 jniArgs.name = pArgs->name;
1665 jniArgs.group = pArgs->group;
1667 setThreadName(pArgs->name);
1669 /* use local jniArgs as stack top */
1670 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1672 * Tell the parent of our success.
1674 * threadListLock is the mutex for threadStartCond.
1676 dvmLockThreadList(dvmThreadSelf());
1677 *pArgs->pCreateStatus = 1;
1678 *pArgs->pThread = dvmThreadSelf();
1679 pthread_cond_broadcast(&gDvm.threadStartCond);
1680 dvmUnlockThreadList();
1682 LOG_THREAD("threadid=%d: internal '%s'\n",
1683 dvmThreadSelf()->threadId, pArgs->name);
1686 (*pArgs->func)(pArgs->funcArg);
1688 /* detach ourselves */
1689 dvmDetachCurrentThread();
1692 * Tell the parent of our failure. We don't have a Thread struct,
1693 * so we can't be suspended, so we don't need to enter a critical
1696 dvmLockThreadList(dvmThreadSelf());
1697 *pArgs->pCreateStatus = -1;
1698 assert(*pArgs->pThread == NULL);
1699 pthread_cond_broadcast(&gDvm.threadStartCond);
1700 dvmUnlockThreadList();
1702 assert(*pArgs->pThread == NULL);
1711 * Attach the current thread to the VM.
1713 * Used for internally-created threads and JNI's AttachCurrentThread.
1715 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1717 Thread* self = NULL;
1718 Object* threadObj = NULL;
1719 Object* vmThreadObj = NULL;
1720 StringObject* threadNameStr = NULL;
1724 /* establish a basic sense of self */
1725 self = allocThread(gDvm.stackSize);
1728 setThreadSelf(self);
1731 * Create Thread and VMThread objects. We have to use ALLOC_NO_GC
1732 * because this thread is not yet visible to the VM. We could also
1733 * just grab the GC lock earlier, but that leaves us executing
1734 * interpreted code with the lock held, which is not prudent.
1736 * The alloc calls will block if a GC is in progress, so we don't need
1737 * to check for global suspension here.
1739 * It's also possible for the allocation calls to *cause* a GC.
1741 //BUG: deadlock if a GC happens here during HeapWorker creation
1742 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_NO_GC);
1743 if (threadObj == NULL)
1745 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_NO_GC);
1746 if (vmThreadObj == NULL)
1749 self->threadObj = threadObj;
1750 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1753 * Do some java.lang.Thread constructor prep before we lock stuff down.
1755 if (pArgs->name != NULL) {
1756 threadNameStr = dvmCreateStringFromCstr(pArgs->name, ALLOC_NO_GC);
1757 if (threadNameStr == NULL) {
1758 assert(dvmCheckException(dvmThreadSelf()));
1763 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1764 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1766 assert(dvmCheckException(dvmThreadSelf()));
1771 * Finish our thread prep. We need to do this before invoking any
1772 * interpreted code. prepareThread() requires that we hold the thread
1775 dvmLockThreadList(self);
1776 ok = prepareThread(self);
1777 dvmUnlockThreadList();
1781 self->jniEnv = dvmCreateJNIEnv(self);
1782 if (self->jniEnv == NULL)
1786 * Create a "fake" JNI frame at the top of the main thread interp stack.
1787 * It isn't really necessary for the internal threads, but it gives
1788 * the debugger something to show. It is essential for the JNI-attached
1791 if (!createFakeRunFrame(self))
1795 * The native side of the thread is ready; add it to the list.
1797 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1799 /* Start off in VMWAIT, because we may be about to block
1800 * on the heap lock, and we don't want any suspensions
1803 self->status = THREAD_VMWAIT;
1806 * Add ourselves to the thread list. Once we finish here we are
1807 * visible to the debugger and the GC.
1809 dvmLockThreadList(self);
1811 self->next = gDvm.threadList->next;
1812 if (self->next != NULL)
1813 self->next->prev = self;
1814 self->prev = gDvm.threadList;
1815 gDvm.threadList->next = self;
1817 gDvm.nonDaemonThreadCount++;
1819 dvmUnlockThreadList();
1822 * It's possible that a GC is currently running. Our thread
1823 * wasn't in the list when the GC started, so it's not properly
1824 * suspended in that case. Synchronize on the heap lock (held
1825 * when a GC is happening) to guarantee that any GCs from here
1826 * on will see this thread in the list.
1828 dvmLockMutex(&gDvm.gcHeapLock);
1829 dvmUnlockMutex(&gDvm.gcHeapLock);
1832 * Switch to the running state now that we're ready for
1833 * suspensions. This call may suspend.
1835 dvmChangeStatus(self, THREAD_RUNNING);
1838 * Now we're ready to run some interpreted code.
1840 * We need to construct the Thread object and set the VMThread field.
1841 * Setting VMThread tells interpreted code that we're alive.
1843 * Call the (group, name, priority, daemon) constructor on the Thread.
1844 * This sets the thread's name and adds it to the specified group, and
1845 * provides values for priority and daemon (which are normally inherited
1846 * from the current thread).
1849 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
1850 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
1851 if (dvmCheckException(self)) {
1852 LOGE("exception thrown while constructing attached thread object\n");
1856 // dvmSetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon, true);
1859 * Set the VMThread field, which tells interpreted code that we're alive.
1861 * The risk of a thread start collision here is very low; somebody
1862 * would have to be deliberately polling the ThreadGroup list and
1863 * trying to start threads against anything it sees, which would
1864 * generally cause problems for all thread creation. However, for
1865 * correctness we test "vmThread" before setting it.
1867 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1868 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1869 "thread has already been started");
1870 /* We don't want to free anything associated with the thread
1871 * because someone is obviously interested in it. Just let
1872 * it go and hope it will clean itself up when its finished.
1873 * This case should never happen anyway.
1875 * Since we're letting it live, we need to finish setting it up.
1876 * We just have to let the caller know that the intended operation
1879 * [ This seems strange -- stepping on the vmThread object that's
1880 * already present seems like a bad idea. TODO: figure this out. ]
1885 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1887 /* These are now reachable from the thread groups. */
1888 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
1889 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
1892 * The thread is ready to go; let the debugger see it.
1894 self->threadObj = threadObj;
1896 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
1897 self->threadId, pArgs->name);
1899 /* tell the debugger & DDM */
1900 if (gDvm.debuggerConnected)
1901 dvmDbgPostThreadStart(self);
1906 dvmLockThreadList(self);
1909 gDvm.nonDaemonThreadCount--;
1910 dvmUnlockThreadList();
1911 /* fall through to "fail" */
1913 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
1914 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
1916 if (self->jniEnv != NULL) {
1917 dvmDestroyJNIEnv(self->jniEnv);
1918 self->jniEnv = NULL;
1922 setThreadSelf(NULL);
1927 * Detach the thread from the various data structures, notify other threads
1928 * that are waiting to "join" it, and free up all heap-allocated storage.
1930 * Used for all threads.
1932 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
1933 * requires us to enforce this for the DetachCurrentThread call, probably
1934 * because it also says that DetachCurrentThread causes all monitors
1935 * associated with the thread to be released. (Because the stack is empty,
1936 * we only have to worry about explicit JNI calls to MonitorEnter.)
1939 * We might want to avoid freeing our internal Thread structure until the
1940 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
1941 * get to once the thread shuts down, but there is a small possibility of
1942 * an operation starting in another thread before this thread halts, and
1943 * finishing much later (perhaps the thread got stalled by a weird OS bug).
1944 * We don't want something like Thread.isInterrupted() crawling through
1945 * freed storage. Can do with a Thread finalizer, or by creating a
1946 * dedicated ThreadObject class for java/lang/Thread and moving all of our
1949 void dvmDetachCurrentThread(void)
1951 Thread* self = dvmThreadSelf();
1956 * Make sure we're not detaching a thread that's still running. (This
1957 * could happen with an explicit JNI detach call.)
1959 * A thread created by interpreted code will finish with a depth of
1960 * zero, while a JNI-attached thread will have the synthetic "stack
1961 * starter" native method at the top.
1963 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
1964 if (curDepth != 0) {
1965 bool topIsNative = false;
1967 if (curDepth == 1) {
1968 /* not expecting a lingering break frame; just look at curFrame */
1969 assert(!dvmIsBreakFrame(self->curFrame));
1970 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
1971 if (dvmIsNativeMethod(ssa->method))
1976 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
1978 dvmDumpThread(self, false);
1983 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
1984 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
1987 * Release any held monitors. Since there are no interpreted stack
1988 * frames, the only thing left are the monitors held by JNI MonitorEnter
1991 dvmReleaseJniMonitors(self);
1994 * Do some thread-exit uncaught exception processing if necessary.
1996 if (dvmCheckException(self))
1997 threadExitUncaughtException(self, group);
2000 * Remove the thread from the thread group.
2002 if (group != NULL) {
2003 Method* removeThread =
2004 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2006 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2010 * Clear the vmThread reference in the Thread object. Interpreted code
2011 * will now see that this Thread is not running. As this may be the
2012 * only reference to the VMThread object that the VM knows about, we
2013 * have to create an internal reference to it first.
2015 vmThread = dvmGetFieldObject(self->threadObj,
2016 gDvm.offJavaLangThread_vmThread);
2017 dvmAddTrackedAlloc(vmThread, self);
2018 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2020 /* clear out our struct Thread pointer, since it's going away */
2021 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2024 * Tell the debugger & DDM. This may cause the current thread or all
2025 * threads to suspend.
2027 * The JDWP spec is somewhat vague about when this happens, other than
2028 * that it's issued by the dying thread, which may still appear in
2029 * an "all threads" listing.
2031 if (gDvm.debuggerConnected)
2032 dvmDbgPostThreadDeath(self);
2035 * Thread.join() is implemented as an Object.wait() on the VMThread
2036 * object. Signal anyone who is waiting.
2038 dvmLockObject(self, vmThread);
2039 dvmObjectNotifyAll(self, vmThread);
2040 dvmUnlockObject(self, vmThread);
2042 dvmReleaseTrackedAlloc(vmThread, self);
2046 * We're done manipulating objects, so it's okay if the GC runs in
2047 * parallel with us from here out. It's important to do this if
2048 * profiling is enabled, since we can wait indefinitely.
2050 self->status = THREAD_VMWAIT;
2052 #ifdef WITH_PROFILER
2054 * If we're doing method trace profiling, we don't want threads to exit,
2055 * because if they do we'll end up reusing thread IDs. This complicates
2056 * analysis and makes it impossible to have reasonable output in the
2057 * "threads" section of the "key" file.
2059 * We need to do this after Thread.join() completes, or other threads
2060 * could get wedged. Since self->threadObj is still valid, the Thread
2061 * object will not get GCed even though we're no longer in the ThreadGroup
2062 * list (which is important since the profiling thread needs to get
2063 * the thread's name).
2065 MethodTraceState* traceState = &gDvm.methodTrace;
2067 dvmLockMutex(&traceState->startStopLock);
2068 if (traceState->traceEnabled) {
2069 LOGI("threadid=%d: waiting for method trace to finish\n",
2071 while (traceState->traceEnabled) {
2073 cc = pthread_cond_wait(&traceState->threadExitCond,
2074 &traceState->startStopLock);
2078 dvmUnlockMutex(&traceState->startStopLock);
2081 dvmLockThreadList(self);
2084 * Lose the JNI context.
2086 dvmDestroyJNIEnv(self->jniEnv);
2087 self->jniEnv = NULL;
2089 self->status = THREAD_ZOMBIE;
2092 * Remove ourselves from the internal thread list.
2097 * If we're the last one standing, signal anybody waiting in
2098 * DestroyJavaVM that it's okay to exit.
2100 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2101 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2103 if (gDvm.nonDaemonThreadCount == 0) {
2106 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2107 //dvmDumpAllThreads(false);
2108 // cond var guarded by threadListLock, which we already hold
2109 cc = pthread_cond_signal(&gDvm.vmExitCond);
2114 LOGV("threadid=%d: bye!\n", self->threadId);
2115 releaseThreadId(self);
2116 dvmUnlockThreadList();
2118 setThreadSelf(NULL);
2124 * Suspend a single thread. Do not use to suspend yourself.
2126 * This is used primarily for debugger/DDMS activity. Does not return
2127 * until the thread has suspended or is in a "safe" state (e.g. executing
2128 * native code outside the VM).
2130 * The thread list lock should be held before calling here -- it's not
2131 * entirely safe to hang on to a Thread* from another thread otherwise.
2132 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2134 void dvmSuspendThread(Thread* thread)
2136 assert(thread != NULL);
2137 assert(thread != dvmThreadSelf());
2138 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2140 lockThreadSuspendCount();
2141 thread->suspendCount++;
2142 thread->dbgSuspendCount++;
2144 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2145 thread->threadId, thread->suspendCount);
2146 unlockThreadSuspendCount();
2148 waitForThreadSuspend(dvmThreadSelf(), thread);
2152 * Reduce the suspend count of a thread. If it hits zero, tell it to
2155 * Used primarily for debugger/DDMS activity. The thread in question
2156 * might have been suspended singly or as part of a suspend-all operation.
2158 * The thread list lock should be held before calling here -- it's not
2159 * entirely safe to hang on to a Thread* from another thread otherwise.
2160 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2162 void dvmResumeThread(Thread* thread)
2164 assert(thread != NULL);
2165 assert(thread != dvmThreadSelf());
2166 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2168 lockThreadSuspendCount();
2169 if (thread->suspendCount > 0) {
2170 thread->suspendCount--;
2171 thread->dbgSuspendCount--;
2173 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2177 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2178 thread->threadId, thread->suspendCount);
2180 if (thread->suspendCount == 0) {
2181 int cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2185 unlockThreadSuspendCount();
2189 * Suspend yourself, as a result of debugger activity.
2191 void dvmSuspendSelf(bool jdwpActivity)
2193 Thread* self = dvmThreadSelf();
2195 /* debugger thread may not suspend itself due to debugger activity! */
2196 assert(gDvm.jdwpState != NULL);
2197 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2203 * Collisions with other suspends aren't really interesting. We want
2204 * to ensure that we're the only one fiddling with the suspend count
2207 lockThreadSuspendCount();
2208 self->suspendCount++;
2209 self->dbgSuspendCount++;
2212 * Suspend ourselves.
2214 assert(self->suspendCount > 0);
2215 self->isSuspended = true;
2216 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2219 * Tell JDWP that we've completed suspension. The JDWP thread can't
2220 * tell us to resume before we're fully asleep because we hold the
2221 * suspend count lock.
2223 * If we got here via waitForDebugger(), don't do this part.
2226 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2227 // self->threadId, (int) self->handle);
2228 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2231 while (self->suspendCount != 0) {
2233 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
2234 &gDvm.threadSuspendCountLock);
2236 if (self->suspendCount != 0) {
2238 * The condition was signaled but we're still suspended. This
2239 * can happen if the debugger lets go while a SIGQUIT thread
2240 * dump event is pending (assuming SignalCatcher was resumed for
2241 * just long enough to try to grab the thread-suspend lock).
2243 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
2244 self->threadId, self->suspendCount, self->dbgSuspendCount,
2245 self->isSuspended ? 'Y' : 'N');
2248 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2249 self->isSuspended = false;
2250 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2251 self->threadId, self->status);
2253 unlockThreadSuspendCount();
2258 # define NUM_FRAMES 20
2259 # include <execinfo.h>
2261 * glibc-only stack dump function. Requires link with "--export-dynamic".
2263 * TODO: move this into libs/cutils and make it work for all platforms.
2265 static void printBackTrace(void)
2267 void* array[NUM_FRAMES];
2272 size = backtrace(array, NUM_FRAMES);
2273 strings = backtrace_symbols(array, size);
2275 LOGW("Obtained %zd stack frames.\n", size);
2277 for (i = 0; i < size; i++)
2278 LOGW("%s\n", strings[i]);
2283 static void printBackTrace(void) {}
2287 * Dump the state of the current thread and that of another thread that
2288 * we think is wedged.
2290 static void dumpWedgedThread(Thread* thread)
2295 * The "executablepath" function in libutils is host-side only.
2297 strcpy(exePath, "-");
2301 sprintf(proc, "/proc/%d/exe", getpid());
2304 len = readlink(proc, exePath, sizeof(exePath)-1);
2305 exePath[len] = '\0';
2309 LOGW("dumping state: process %s %d\n", exePath, getpid());
2310 dvmDumpThread(dvmThreadSelf(), false);
2313 // dumping a running thread is risky, but could be useful
2314 dvmDumpThread(thread, true);
2317 // stop now and get a core dump
2323 * Wait for another thread to see the pending suspension and stop running.
2324 * It can either suspend itself or go into a non-running state such as
2325 * VMWAIT or NATIVE in which it cannot interact with the GC.
2327 * If we're running at a higher priority, sched_yield() may not do anything,
2328 * so we need to sleep for "long enough" to guarantee that the other
2329 * thread has a chance to finish what it's doing. Sleeping for too short
2330 * a period (e.g. less than the resolution of the sleep clock) might cause
2331 * the scheduler to return immediately, so we want to start with a
2332 * "reasonable" value and expand.
2334 * This does not return until the other thread has stopped running.
2335 * Eventually we time out and the VM aborts.
2337 * This does not try to detect the situation where two threads are
2338 * waiting for each other to suspend. In normal use this is part of a
2339 * suspend-all, which implies that the suspend-all lock is held, or as
2340 * part of a debugger action in which the JDWP thread is always the one
2341 * doing the suspending. (We may need to re-evaluate this now that
2342 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2344 * TODO: track basic stats about time required to suspend VM.
2346 static void waitForThreadSuspend(Thread* self, Thread* thread)
2348 const int kMaxRetries = 10;
2349 const int kSpinSleepTime = 750*1000; /* 0.75s */
2350 bool complained = false;
2354 u8 startWhen = 0; // init req'd to placate gcc
2356 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
2357 if (sleepIter == 0) // get current time on first iteration
2358 startWhen = dvmGetRelativeTimeUsec();
2360 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
2361 LOGW("threadid=%d (h=%d): spin on suspend threadid=%d (handle=%d)\n",
2362 self->threadId, (int)self->handle,
2363 thread->threadId, (int)thread->handle);
2364 dumpWedgedThread(thread);
2367 // keep going; could be slow due to valgrind
2370 if (retryCount++ == kMaxRetries) {
2371 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2372 self->threadId, thread->threadId);
2373 dvmDumpAllThreads(false);
2380 LOGW("threadid=%d: spin on suspend resolved\n", self->threadId);
2381 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2386 * Suspend all threads except the current one. This is used by the GC,
2387 * the debugger, and by any thread that hits a "suspend all threads"
2388 * debugger event (e.g. breakpoint or exception).
2390 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2391 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2392 * create objects and even execute arbitrary code. The "why" argument
2393 * allows the caller to say why the suspension is taking place.
2395 * This can be called when a global suspend has already happened, due to
2396 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2399 * DO NOT grab any locks before calling here. We grab & release the thread
2400 * lock and suspend lock here (and we're not using recursive threads), and
2401 * we might have to self-suspend if somebody else beats us here.
2403 * The current thread may not be attached to the VM. This can happen if
2404 * we happen to GC as the result of an allocation of a Thread object.
2406 void dvmSuspendAllThreads(SuspendCause why)
2408 Thread* self = dvmThreadSelf();
2414 * Start by grabbing the thread suspend lock. If we can't get it, most
2415 * likely somebody else is in the process of performing a suspend or
2416 * resume, so lockThreadSuspend() will cause us to self-suspend.
2418 * We keep the lock until all other threads are suspended.
2420 lockThreadSuspend("susp-all", why);
2422 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2425 * This is possible if the current thread was in VMWAIT mode when a
2426 * suspend-all happened, and then decided to do its own suspend-all.
2427 * This can happen when a couple of threads have simultaneous events
2428 * of interest to the debugger.
2430 //assert(self->suspendCount == 0);
2433 * Increment everybody's suspend count (except our own).
2435 dvmLockThreadList(self);
2437 lockThreadSuspendCount();
2438 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2442 /* debugger events don't suspend JDWP thread */
2443 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2444 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2447 thread->suspendCount++;
2448 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2449 thread->dbgSuspendCount++;
2451 unlockThreadSuspendCount();
2454 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2455 * indicate the code is either running natively or sleeping quietly.
2456 * Any attempt to transition back to THREAD_RUNNING will cause a check
2457 * for suspension, so it should be impossible for anything to execute
2458 * interpreted code or modify objects (assuming native code plays nicely).
2460 * It's also okay if the thread transitions to a non-RUNNING state.
2462 * Note we released the threadSuspendCountLock before getting here,
2463 * so if another thread is fiddling with its suspend count (perhaps
2464 * self-suspending for the debugger) it won't block while we're waiting
2467 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2471 /* debugger events don't suspend JDWP thread */
2472 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2473 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2476 /* wait for the other thread to see the pending suspend */
2477 waitForThreadSuspend(self, thread);
2479 LOG_THREAD("threadid=%d: threadid=%d status=%d c=%d dc=%d isSusp=%d\n",
2481 thread->threadId, thread->status, thread->suspendCount,
2482 thread->dbgSuspendCount, thread->isSuspended);
2485 dvmUnlockThreadList();
2486 unlockThreadSuspend();
2488 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2492 * Resume all threads that are currently suspended.
2494 * The "why" must match with the previous suspend.
2496 void dvmResumeAllThreads(SuspendCause why)
2498 Thread* self = dvmThreadSelf();
2502 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2503 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2506 * Decrement the suspend counts for all threads. No need for atomic
2507 * writes, since nobody should be moving until we decrement the count.
2508 * We do need to hold the thread list because of JNI attaches.
2510 dvmLockThreadList(self);
2511 lockThreadSuspendCount();
2512 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2516 /* debugger events don't suspend JDWP thread */
2517 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2518 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2523 if (thread->suspendCount > 0) {
2524 thread->suspendCount--;
2525 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2526 thread->dbgSuspendCount--;
2528 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2532 unlockThreadSuspendCount();
2533 dvmUnlockThreadList();
2536 * In some ways it makes sense to continue to hold the thread-suspend
2537 * lock while we issue the wakeup broadcast. It allows us to complete
2538 * one operation before moving on to the next, which simplifies the
2539 * thread activity debug traces.
2541 * This approach caused us some difficulty under Linux, because the
2542 * condition variable broadcast not only made the threads runnable,
2543 * but actually caused them to execute, and it was a while before
2544 * the thread performing the wakeup had an opportunity to release the
2545 * thread-suspend lock.
2547 * This is a problem because, when a thread tries to acquire that
2548 * lock, it times out after 3 seconds. If at some point the thread
2549 * is told to suspend, the clock resets; but since the VM is still
2550 * theoretically mid-resume, there's no suspend pending. If, for
2551 * example, the GC was waking threads up while the SIGQUIT handler
2552 * was trying to acquire the lock, we would occasionally time out on
2553 * a busy system and SignalCatcher would abort.
2555 * We now perform the unlock before the wakeup broadcast. The next
2556 * suspend can't actually start until the broadcast completes and
2557 * returns, because we're holding the thread-suspend-count lock, but the
2558 * suspending thread is now able to make progress and we avoid the abort.
2560 * (Technically there is a narrow window between when we release
2561 * the thread-suspend lock and grab the thread-suspend-count lock.
2562 * This could cause us to send a broadcast to threads with nonzero
2563 * suspend counts, but this is expected and they'll all just fall
2564 * right back to sleep. It's probably safe to grab the suspend-count
2565 * lock before releasing thread-suspend, since we're still following
2566 * the correct order of acquisition, but it feels weird.)
2569 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2570 unlockThreadSuspend();
2573 * Broadcast a notification to all suspended threads, some or all of
2574 * which may choose to wake up. No need to wait for them.
2576 lockThreadSuspendCount();
2577 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2579 unlockThreadSuspendCount();
2581 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2585 * Undo any debugger suspensions. This is called when the debugger
2588 void dvmUndoDebuggerSuspensions(void)
2590 Thread* self = dvmThreadSelf();
2594 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2595 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2598 * Decrement the suspend counts for all threads. No need for atomic
2599 * writes, since nobody should be moving until we decrement the count.
2600 * We do need to hold the thread list because of JNI attaches.
2602 dvmLockThreadList(self);
2603 lockThreadSuspendCount();
2604 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2608 /* debugger events don't suspend JDWP thread */
2609 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2610 assert(thread->dbgSuspendCount == 0);
2614 assert(thread->suspendCount >= thread->dbgSuspendCount);
2615 thread->suspendCount -= thread->dbgSuspendCount;
2616 thread->dbgSuspendCount = 0;
2618 unlockThreadSuspendCount();
2619 dvmUnlockThreadList();
2622 * Broadcast a notification to all suspended threads, some or all of
2623 * which may choose to wake up. No need to wait for them.
2625 lockThreadSuspendCount();
2626 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2628 unlockThreadSuspendCount();
2630 unlockThreadSuspend();
2632 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2636 * Determine if a thread is suspended.
2638 * As with all operations on foreign threads, the caller should hold
2639 * the thread list lock before calling.
2641 bool dvmIsSuspended(Thread* thread)
2644 * The thread could be:
2645 * (1) Running happily. status is RUNNING, isSuspended is false,
2646 * suspendCount is zero. Return "false".
2647 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2648 * suspendCount is nonzero. Return "false".
2649 * (3) Suspended. suspendCount is nonzero, and either (status is
2650 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2652 * (4) Waking up. suspendCount is zero, status is RUNNING and
2653 * isSuspended is true. Return "false" (since it could change
2654 * out from under us, unless we hold suspendCountLock).
2657 return (thread->suspendCount != 0 &&
2658 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2659 (thread->status != THREAD_RUNNING)));
2663 * Wait until another thread self-suspends. This is specifically for
2664 * synchronization between the JDWP thread and a thread that has decided
2665 * to suspend itself after sending an event to the debugger.
2667 * Threads that encounter "suspend all" events work as well -- the thread
2668 * in question suspends everybody else and then itself.
2670 * We can't hold a thread lock here or in the caller, because we could
2671 * get here just before the to-be-waited-for-thread issues a "suspend all".
2672 * There's an opportunity for badness if the thread we're waiting for exits
2673 * and gets cleaned up, but since the thread in question is processing a
2674 * debugger event, that's not really a possibility. (To avoid deadlock,
2675 * it's important that we not be in THREAD_RUNNING while we wait.)
2677 void dvmWaitForSuspend(Thread* thread)
2679 Thread* self = dvmThreadSelf();
2681 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
2682 self->threadId, thread->threadId);
2684 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2685 assert(thread != self);
2686 assert(self->status != THREAD_RUNNING);
2688 waitForThreadSuspend(self, thread);
2690 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
2691 self->threadId, thread->threadId);
2695 * Check to see if we need to suspend ourselves. If so, go to sleep on
2696 * a condition variable.
2698 * Takes "self" as an argument as an optimization. Pass in NULL to have
2701 * Returns "true" if we suspended ourselves.
2703 bool dvmCheckSuspendPending(Thread* self)
2708 self = dvmThreadSelf();
2710 /* fast path: if count is zero, bail immediately */
2711 if (self->suspendCount == 0)
2714 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
2716 assert(self->suspendCount >= 0); /* XXX: valid? useful? */
2718 didSuspend = (self->suspendCount != 0);
2719 self->isSuspended = true;
2720 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
2721 while (self->suspendCount != 0) {
2722 /* wait for wakeup signal; releases lock */
2724 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
2725 &gDvm.threadSuspendCountLock);
2728 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2729 self->isSuspended = false;
2730 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
2731 self->threadId, self->status);
2733 unlockThreadSuspendCount();
2739 * Update our status.
2741 * The "self" argument, which may be NULL, is accepted as an optimization.
2743 * Returns the old status.
2745 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
2747 ThreadStatus oldStatus;
2750 self = dvmThreadSelf();
2752 LOGVV("threadid=%d: (status %d -> %d)\n",
2753 self->threadId, self->status, newStatus);
2755 oldStatus = self->status;
2757 if (newStatus == THREAD_RUNNING) {
2759 * Change our status to THREAD_RUNNING. The transition requires
2760 * that we check for pending suspension, because the VM considers
2761 * us to be "asleep" in all other states.
2763 * We need to do the "suspend pending" check FIRST, because it grabs
2764 * a lock that could be held by something that wants us to suspend.
2765 * If we're in RUNNING it will wait for us, and we'll be waiting
2766 * for the lock it holds.
2768 assert(self->status != THREAD_RUNNING);
2770 dvmCheckSuspendPending(self);
2771 self->status = THREAD_RUNNING;
2774 * Change from one state to another, neither of which is
2775 * THREAD_RUNNING. This is most common during system or thread
2778 self->status = newStatus;
2785 * Get a statically defined thread group from a field in the ThreadGroup
2786 * Class object. Expected arguments are "mMain" and "mSystem".
2788 static Object* getStaticThreadGroup(const char* fieldName)
2790 StaticField* groupField;
2793 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
2794 fieldName, "Ljava/lang/ThreadGroup;");
2795 if (groupField == NULL) {
2796 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
2797 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
2800 groupObj = dvmGetStaticFieldObject(groupField);
2801 if (groupObj == NULL) {
2802 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
2803 dvmThrowException("Ljava/lang/InternalError;", NULL);
2809 Object* dvmGetSystemThreadGroup(void)
2811 return getStaticThreadGroup("mSystem");
2813 Object* dvmGetMainThreadGroup(void)
2815 return getStaticThreadGroup("mMain");
2819 * Given a VMThread object, return the associated Thread*.
2821 * NOTE: if the thread detaches, the struct Thread will disappear, and
2822 * we will be touching invalid data. For safety, lock the thread list
2823 * before calling this.
2825 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
2829 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
2830 return (Thread*) vmData;
2835 * Conversion map for "nice" values.
2837 * We use Android thread priority constants to be consistent with the rest
2838 * of the system. In some cases adjacent entries may overlap.
2840 static const int kNiceValues[10] = {
2841 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
2842 ANDROID_PRIORITY_BACKGROUND + 6,
2843 ANDROID_PRIORITY_BACKGROUND + 3,
2844 ANDROID_PRIORITY_BACKGROUND,
2845 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
2846 ANDROID_PRIORITY_NORMAL - 2,
2847 ANDROID_PRIORITY_NORMAL - 4,
2848 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
2849 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
2850 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
2854 * Change the scheduler cgroup of a pid
2856 int dvmChangeThreadSchedulerGroup(const char *cgroup)
2858 #ifdef HAVE_ANDROID_OS
2863 sprintf(path, "/dev/cpuctl/%s/tasks", (cgroup ? cgroup : ""));
2865 if (!(fp = fopen(path, "w"))) {
2866 #if ENABLE_CGROUP_ERR_LOGGING
2867 LOGW("Unable to open %s (%s)\n", path, strerror(errno));
2872 rc = fprintf(fp, "0");
2876 #if ENABLE_CGROUP_ERR_LOGGING
2877 LOGW("Unable to move pid %d to cgroup %s (%s)\n", getpid(),
2878 (cgroup ? cgroup : "<default>"), strerror(errno));
2882 return (rc < 0) ? errno : 0;
2883 #else // HAVE_ANDROID_OS
2889 * Change the priority of a system thread to match that of the Thread object.
2891 * We map a priority value from 1-10 to Linux "nice" values, where lower
2892 * numbers indicate higher priority.
2894 void dvmChangeThreadPriority(Thread* thread, int newPriority)
2896 pid_t pid = thread->systemTid;
2899 if (newPriority < 1 || newPriority > 10) {
2900 LOGW("bad priority %d\n", newPriority);
2903 newNice = kNiceValues[newPriority-1];
2905 if (newPriority >= ANDROID_PRIORITY_BACKGROUND) {
2906 dvmChangeThreadSchedulerGroup("bg_non_interactive");
2907 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
2908 dvmChangeThreadSchedulerGroup(NULL);
2911 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
2912 char* str = dvmGetThreadName(thread);
2913 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
2914 pid, str, newPriority, newNice, strerror(errno));
2917 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
2918 pid, newPriority, newNice);
2923 * Get the thread priority for the current thread by querying the system.
2924 * This is useful when attaching a thread through JNI.
2926 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
2928 static int getThreadPriorityFromSystem(void)
2930 int i, sysprio, jprio;
2933 sysprio = getpriority(PRIO_PROCESS, 0);
2934 if (sysprio == -1 && errno != 0) {
2935 LOGW("getpriority() failed: %s\n", strerror(errno));
2936 return THREAD_NORM_PRIORITY;
2939 jprio = THREAD_MIN_PRIORITY;
2940 for (i = 0; i < NELEM(kNiceValues); i++) {
2941 if (sysprio >= kNiceValues[i])
2945 if (jprio > THREAD_MAX_PRIORITY)
2946 jprio = THREAD_MAX_PRIORITY;
2953 * Return true if the thread is on gDvm.threadList.
2954 * Caller should not hold gDvm.threadListLock.
2956 bool dvmIsOnThreadList(const Thread* thread)
2960 dvmLockThreadList(NULL);
2961 if (thread == gDvm.threadList) {
2964 ret = thread->prev != NULL || thread->next != NULL;
2966 dvmUnlockThreadList();
2972 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
2975 void dvmDumpThread(Thread* thread, bool isRunning)
2977 DebugOutputTarget target;
2979 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
2980 dvmDumpThreadEx(&target, thread, isRunning);
2984 * Print information about the specified thread.
2986 * Works best when the thread in question is "self" or has been suspended.
2987 * When dumping a separate thread that's still running, set "isRunning" to
2988 * use a more cautious thread dump function.
2990 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
2993 /* tied to ThreadStatus enum */
2994 static const char* kStatusNames[] = {
2995 "ZOMBIE", "RUNNABLE", "TIMED_WAIT", "MONITOR", "WAIT",
2996 "INITIALIZING", "STARTING", "NATIVE", "VMWAIT"
3000 StringObject* nameStr;
3001 char* threadName = NULL;
3002 char* groupName = NULL;
3004 int priority; // java.lang.Thread priority
3005 int policy; // pthread policy
3006 struct sched_param sp; // pthread scheduling parameters
3008 threadObj = thread->threadObj;
3009 if (threadObj == NULL) {
3010 LOGW("Can't dump thread %d: threadObj not set\n", thread->threadId);
3013 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3014 gDvm.offJavaLangThread_name);
3015 threadName = dvmCreateCstrFromString(nameStr);
3017 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3018 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3020 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3021 LOGW("Warning: pthread_getschedparam failed\n");
3023 sp.sched_priority = -1;
3026 /* a null value for group is not expected, but deal with it anyway */
3027 groupObj = (Object*) dvmGetFieldObject(threadObj,
3028 gDvm.offJavaLangThread_group);
3029 if (groupObj != NULL) {
3030 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3031 "name", "Ljava/lang/String;");
3033 LOGW("Unable to find 'name' field in ThreadGroup\n");
3035 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3036 groupName = dvmCreateCstrFromString(nameStr);
3039 if (groupName == NULL)
3040 groupName = strdup("(BOGUS GROUP)");
3042 assert(thread->status < NELEM(kStatusNames));
3043 dvmPrintDebugMessage(target,
3044 "\"%s\"%s prio=%d tid=%d %s\n",
3045 threadName, isDaemon ? " daemon" : "",
3046 priority, thread->threadId, kStatusNames[thread->status]);
3047 dvmPrintDebugMessage(target,
3048 " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
3049 groupName, thread->suspendCount, thread->dbgSuspendCount,
3050 thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
3051 dvmPrintDebugMessage(target,
3052 " | sysTid=%d nice=%d sched=%d/%d handle=%d\n",
3053 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
3054 policy, sp.sched_priority, (int)thread->handle);
3056 #ifdef WITH_MONITOR_TRACKING
3058 LockedObjectData* lod = thread->pLockedObjects;
3060 dvmPrintDebugMessage(target, " | monitors held:\n");
3062 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3063 while (lod != NULL) {
3064 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3065 lod->obj, lod->recursionCount, lod->obj->clazz->descriptor);
3072 dvmDumpRunningThreadStack(target, thread);
3074 dvmDumpThreadStack(target, thread);
3082 * Get the name of a thread.
3084 * For correctness, the caller should hold the thread list lock to ensure
3085 * that the thread doesn't go away mid-call.
3087 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3089 char* dvmGetThreadName(Thread* thread)
3091 StringObject* nameObj;
3093 if (thread->threadObj == NULL) {
3094 LOGW("threadObj is NULL, name not available\n");
3095 return strdup("-unknown-");
3098 nameObj = (StringObject*)
3099 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3100 return dvmCreateCstrFromString(nameObj);
3104 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3107 void dvmDumpAllThreads(bool grabLock)
3109 DebugOutputTarget target;
3111 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3112 dvmDumpAllThreadsEx(&target, grabLock);
3116 * Print information about all known threads. Assumes they have been
3117 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3119 * If "grabLock" is true, we grab the thread lock list. This is important
3120 * to do unless the caller already holds the lock.
3122 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3126 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3129 dvmLockThreadList(dvmThreadSelf());
3131 thread = gDvm.threadList;
3132 while (thread != NULL) {
3133 dvmDumpThreadEx(target, thread, false);
3136 assert(thread->next == NULL || thread->next->prev == thread);
3138 thread = thread->next;
3142 dvmUnlockThreadList();
3145 #ifdef WITH_MONITOR_TRACKING
3147 * Count up the #of locked objects in the current thread.
3149 static int getThreadObjectCount(const Thread* self)
3151 LockedObjectData* lod;
3154 lod = self->pLockedObjects;
3155 while (lod != NULL) {
3163 * Add the object to the thread's locked object list if it doesn't already
3164 * exist. The most recently added object is the most likely to be released
3165 * next, so we insert at the head of the list.
3167 * If it already exists, we increase the recursive lock count.
3169 * The object's lock may be thin or fat.
3171 void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3173 LockedObjectData* newLod;
3174 LockedObjectData* lod;
3178 lod = self->pLockedObjects;
3179 while (lod != NULL) {
3180 if (lod->obj == obj) {
3181 lod->recursionCount++;
3182 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3188 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3189 if (newLod == NULL) {
3190 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3194 newLod->recursionCount = 0;
3197 trace = dvmFillInStackTraceRaw(self, &depth);
3198 newLod->rawStackTrace = trace;
3199 newLod->stackDepth = depth;
3202 newLod->next = self->pLockedObjects;
3203 self->pLockedObjects = newLod;
3205 LOGV("+++ threadid=%d: added %p, now %d\n",
3206 self->threadId, newLod, getThreadObjectCount(self));
3210 * Remove the object from the thread's locked object list. If the entry
3211 * has a nonzero recursion count, we just decrement the count instead.
3213 void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3215 LockedObjectData* lod;
3216 LockedObjectData* prevLod;
3218 lod = self->pLockedObjects;
3220 while (lod != NULL) {
3221 if (lod->obj == obj) {
3222 if (lod->recursionCount > 0) {
3223 lod->recursionCount--;
3224 LOGV("+++ -recursive lock %p -> %d\n",
3225 obj, lod->recursionCount);
3236 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3239 if (prevLod == NULL) {
3240 /* first item in list */
3241 assert(self->pLockedObjects == lod);
3242 self->pLockedObjects = lod->next;
3244 /* middle/end of list */
3245 prevLod->next = lod->next;
3248 LOGV("+++ threadid=%d: removed %p, now %d\n",
3249 self->threadId, lod, getThreadObjectCount(self));
3250 free(lod->rawStackTrace);
3255 * If the specified object is already in the thread's locked object list,
3256 * return the LockedObjectData struct. Otherwise return NULL.
3258 LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3260 LockedObjectData* lod;
3262 lod = self->pLockedObjects;
3263 while (lod != NULL) {
3264 if (lod->obj == obj)
3270 #endif /*WITH_MONITOR_TRACKING*/
3274 * GC helper functions
3277 static void gcScanInterpStackReferences(Thread *thread)
3281 framePtr = (const u4 *)thread->curFrame;
3282 while (framePtr != NULL) {
3283 const StackSaveArea *saveArea;
3284 const Method *method;
3286 saveArea = SAVEAREA_FROM_FP(framePtr);
3287 method = saveArea->method;
3288 if (method != NULL) {
3289 #ifdef COUNT_PRECISE_METHODS
3290 /* the GC is running, so no lock required */
3291 if (!dvmIsNativeMethod(method)) {
3292 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3293 LOGI("Added %s.%s %p\n",
3294 method->clazz->descriptor, method->name, method);
3298 for (i = method->registersSize - 1; i >= 0; i--) {
3299 u4 rval = *framePtr++;
3300 //TODO: wrap markifobject in a macro that does pointer checks
3301 if (rval != 0 && (rval & 0x3) == 0) {
3302 dvmMarkIfObject((Object *)rval);
3306 /* else this is a break frame; nothing to mark.
3309 /* Don't fall into an infinite loop if things get corrupted.
3311 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
3312 saveArea->prevFrame == NULL);
3313 framePtr = saveArea->prevFrame;
3317 static void gcScanReferenceTable(ReferenceTable *refTable)
3321 //TODO: these asserts are overkill; turn them off when things stablize.
3322 assert(refTable != NULL);
3323 assert(refTable->table != NULL);
3324 assert(refTable->nextEntry != NULL);
3325 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
3326 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
3328 op = refTable->table;
3329 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
3330 dvmMarkObjectNonNull(*(op++));
3335 * Scan a Thread and mark any objects it references.
3337 static void gcScanThread(Thread *thread)
3339 assert(thread != NULL);
3342 * The target thread must be suspended or in a state where it can't do
3343 * any harm (e.g. in Object.wait()). The only exception is the current
3344 * thread, which will still be active and in the "running" state.
3346 * (Newly-created threads shouldn't be able to shift themselves to
3347 * RUNNING without a suspend-pending check, so this shouldn't cause
3348 * a false-positive.)
3350 assert(thread->status != THREAD_RUNNING || thread->isSuspended ||
3351 thread == dvmThreadSelf());
3353 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
3355 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
3357 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
3359 dvmMarkObject(thread->exception); // usually NULL
3360 gcScanReferenceTable(&thread->internalLocalRefTable);
3362 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
3364 gcScanReferenceTable(&thread->jniLocalRefTable);
3366 if (thread->jniMonitorRefTable.table != NULL) {
3367 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
3369 gcScanReferenceTable(&thread->jniMonitorRefTable);
3372 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
3374 gcScanInterpStackReferences(thread);
3376 HPROF_CLEAR_GC_SCAN_STATE();
3379 static void gcScanAllThreads()
3383 /* Lock the thread list so we can safely use the
3384 * next/prev pointers.
3386 dvmLockThreadList(dvmThreadSelf());
3388 for (thread = gDvm.threadList; thread != NULL;
3389 thread = thread->next)
3391 /* We need to scan our own stack, so don't special-case
3392 * the current thread.
3394 gcScanThread(thread);
3397 dvmUnlockThreadList();
3400 void dvmGcScanRootThreadGroups()
3402 /* We scan the VM's list of threads instead of going
3403 * through the actual ThreadGroups, but it should be
3406 * This assumes that the ThreadGroup class object is in
3407 * the root set, which should always be true; it's
3408 * loaded by the built-in class loader, which is part