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.
26 #include <sys/types.h>
27 #include <sys/resource.h>
33 #if defined(HAVE_PRCTL)
34 #include <sys/prctl.h>
37 #if defined(WITH_SELF_VERIFICATION)
38 #include "interp/Jit.h" // need for self verification
42 /* desktop Linux needs a little help with gettid() */
43 #if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
45 # include <linux/unistd.h>
47 _syscall0(pid_t,gettid)
49 pid_t gettid() { return syscall(__NR_gettid);}
54 // Change this to enable logging on cgroup errors
55 #define ENABLE_CGROUP_ERR_LOGGING 0
57 // change this to LOGV/LOGD to debug thread activity
58 #define LOG_THREAD LOGVV
63 All threads are native pthreads. All threads, except the JDWP debugger
64 thread, are visible to code running in the VM and to the debugger. (We
65 don't want the debugger to try to manipulate the thread that listens for
66 instructions from the debugger.) Internal VM threads are in the "system"
67 ThreadGroup, all others are in the "main" ThreadGroup, per convention.
69 The GC only runs when all threads have been suspended. Threads are
70 expected to suspend themselves, using a "safe point" mechanism. We check
71 for a suspend request at certain points in the main interpreter loop,
72 and on requests coming in from native code (e.g. all JNI functions).
73 Certain debugger events may inspire threads to self-suspend.
75 Native methods must use JNI calls to modify object references to avoid
76 clashes with the GC. JNI doesn't provide a way for native code to access
77 arrays of objects as such -- code must always get/set individual entries --
78 so it should be possible to fully control access through JNI.
80 Internal native VM threads, such as the finalizer thread, must explicitly
81 check for suspension periodically. In most cases they will be sound
82 asleep on a condition variable, and won't notice the suspension anyway.
84 Threads may be suspended by the GC, debugger, or the SIGQUIT listener
85 thread. The debugger may suspend or resume individual threads, while the
86 GC always suspends all threads. Each thread has a "suspend count" that
87 is incremented on suspend requests and decremented on resume requests.
88 When the count is zero, the thread is runnable. This allows us to fulfill
89 a debugger requirement: if the debugger suspends a thread, the thread is
90 not allowed to run again until the debugger resumes it (or disconnects,
91 in which case we must resume all debugger-suspended threads).
93 Paused threads sleep on a condition variable, and are awoken en masse.
94 Certain "slow" VM operations, such as starting up a new thread, will be
95 done in a separate "VMWAIT" state, so that the rest of the VM doesn't
96 freeze up waiting for the operation to finish. Threads must check for
97 pending suspension when leaving VMWAIT.
99 Because threads suspend themselves while interpreting code or when native
100 code makes JNI calls, there is no risk of suspending while holding internal
101 VM locks. All threads can enter a suspended (or native-code-only) state.
102 Also, we don't have to worry about object references existing solely
103 in hardware registers.
105 We do, however, have to worry about objects that were allocated internally
106 and aren't yet visible to anything else in the VM. If we allocate an
107 object, and then go to sleep on a mutex after changing to a non-RUNNING
108 state (e.g. while trying to allocate a second object), the first object
109 could be garbage-collected out from under us while we sleep. To manage
110 this, we automatically add all allocated objects to an internal object
111 tracking list, and only remove them when we know we won't be suspended
112 before the object appears in the GC root set.
114 The debugger may choose to suspend or resume a single thread, which can
115 lead to application-level deadlocks; this is expected behavior. The VM
116 will only check for suspension of single threads when the debugger is
117 active (the java.lang.Thread calls for this are deprecated and hence are
118 not supported). Resumption of a single thread is handled by decrementing
119 the thread's suspend count and sending a broadcast signal to the condition
120 variable. (This will cause all threads to wake up and immediately go back
121 to sleep, which isn't tremendously efficient, but neither is having the
124 The debugger is not allowed to resume threads suspended by the GC. This
125 is trivially enforced by ignoring debugger requests while the GC is running
126 (the JDWP thread is suspended during GC).
128 The VM maintains a Thread struct for every pthread known to the VM. There
129 is a java/lang/Thread object associated with every Thread. At present,
130 there is no safe way to go from a Thread object to a Thread struct except by
131 locking and scanning the list; this is necessary because the lifetimes of
132 the two are not closely coupled. We may want to change this behavior,
133 though at present the only performance impact is on the debugger (see
134 threadObjToThread()). See also notes about dvmDetachCurrentThread().
137 Alternate implementation (signal-based):
139 Threads run without safe points -- zero overhead. The VM uses a signal
140 (e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
142 The trouble with using signals to suspend threads is that it means a thread
143 can be in the middle of an operation when garbage collection starts.
144 To prevent some sticky situations, we have to introduce critical sections
147 Critical sections temporarily block suspension for a given thread.
148 The thread must move to a non-blocked state (and self-suspend) after
149 finishing its current task. If the thread blocks on a resource held
150 by a suspended thread, we're hosed.
152 One approach is to require that no blocking operations, notably
153 acquisition of mutexes, can be performed within a critical section.
154 This is too limiting. For example, if thread A gets suspended while
155 holding the thread list lock, it will prevent the GC or debugger from
156 being able to safely access the thread list. We need to wrap the critical
157 section around the entire operation (enter critical, get lock, do stuff,
158 release lock, exit critical).
160 A better approach is to declare that certain resources can only be held
161 within critical sections. A thread that enters a critical section and
162 then gets blocked on the thread list lock knows that the thread it is
163 waiting for is also in a critical section, and will release the lock
164 before suspending itself. Eventually all threads will complete their
165 operations and self-suspend. For this to work, the VM must:
167 (1) Determine the set of resources that may be accessed from the GC or
168 debugger threads. The mutexes guarding those go into the "critical
170 (2) Ensure that no resource in the CRS can be acquired outside of a
171 critical section. This can be verified with an assert().
172 (3) Ensure that only resources in the CRS can be held while in a critical
173 section. This is harder to enforce.
175 If any of these conditions are not met, deadlock can ensue when grabbing
176 resources in the GC or debugger (#1) or waiting for threads to suspend
177 (#2,#3). (You won't actually deadlock in the GC, because if the semantics
178 above are followed you don't need to lock anything in the GC. The risk is
179 rather that the GC will access data structures in an intermediate state.)
181 This approach requires more care and awareness in the VM than
182 safe-pointing. Because the GC and debugger are fairly intrusive, there
183 really aren't any internal VM resources that aren't shared. Thus, the
184 enter/exit critical calls can be added to internal mutex wrappers, which
185 makes it easy to get #1 and #2 right.
187 An ordering should be established for all locks to avoid deadlocks.
189 Monitor locks, which are also implemented with pthread calls, should not
190 cause any problems here. Threads fighting over such locks will not be in
191 critical sections and can be suspended freely.
193 This can get tricky if we ever need exclusive access to VM and non-VM
194 resources at the same time. It's not clear if this is a real concern.
196 There are (at least) two ways to handle the incoming signals:
198 (a) Always accept signals. If we're in a critical section, the signal
199 handler just returns without doing anything (the "suspend level"
200 should have been incremented before the signal was sent). Otherwise,
201 if the "suspend level" is nonzero, we go to sleep.
202 (b) Block signals in critical sections. This ensures that we can't be
203 interrupted in a critical section, but requires pthread_sigmask()
204 calls on entry and exit.
206 This is a choice between blocking the message and blocking the messenger.
207 Because UNIX signals are unreliable (you can only know that you have been
208 signaled, not whether you were signaled once or 10 times), the choice is
209 not significant for correctness. The choice depends on the efficiency
210 of pthread_sigmask() and the desire to actually block signals. Either way,
211 it is best to ensure that there is only one indication of "blocked";
212 having two (i.e. block signals and set a flag, then only send a signal
213 if the flag isn't set) can lead to race conditions.
215 The signal handler must take care to copy registers onto the stack (via
216 setjmp), so that stack scans find all references. Because we have to scan
217 native stacks, "exact" GC is not possible with this approach.
219 Some other concerns with flinging signals around:
220 - Odd interactions with some debuggers (e.g. gdb on the Mac)
221 - Restrictions on some standard library calls during GC (e.g. don't
222 use printf on stdout to print GC debug messages)
225 #define kMaxThreadId ((1 << 16) - 1)
226 #define kMainThreadId 1
229 static Thread* allocThread(int interpStackSize);
230 static bool prepareThread(Thread* thread);
231 static void setThreadSelf(Thread* thread);
232 static void unlinkThread(Thread* thread);
233 static void freeThread(Thread* thread);
234 static void assignThreadId(Thread* thread);
235 static bool createFakeEntryFrame(Thread* thread);
236 static bool createFakeRunFrame(Thread* thread);
237 static void* interpThreadStart(void* arg);
238 static void* internalThreadStart(void* arg);
239 static void threadExitUncaughtException(Thread* thread, Object* group);
240 static void threadExitCheck(void* arg);
241 static void waitForThreadSuspend(Thread* self, Thread* thread);
244 * Initialize thread list and main thread's environment. We need to set
245 * up some basic stuff so that dvmThreadSelf() will work when we start
246 * loading classes (e.g. to check for exceptions).
248 bool dvmThreadStartup()
252 /* allocate a TLS slot */
253 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
254 LOGE("ERROR: pthread_key_create failed");
258 /* test our pthread lib */
259 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
260 LOGW("WARNING: newly-created pthread TLS slot is not NULL");
262 /* prep thread-related locks and conditions */
263 dvmInitMutex(&gDvm.threadListLock);
264 pthread_cond_init(&gDvm.threadStartCond, NULL);
265 pthread_cond_init(&gDvm.vmExitCond, NULL);
266 dvmInitMutex(&gDvm._threadSuspendLock);
267 dvmInitMutex(&gDvm.threadSuspendCountLock);
268 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
271 * Dedicated monitor for Thread.sleep().
272 * TODO: change this to an Object* so we don't have to expose this
273 * call, and we interact better with JDWP monitor calls. Requires
274 * deferring the object creation to much later (e.g. final "main"
275 * thread prep) or until first use.
277 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
279 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
281 thread = allocThread(gDvm.stackSize);
285 /* switch mode for when we run initializers */
286 thread->status = THREAD_RUNNING;
289 * We need to assign the threadId early so we can lock/notify
290 * object monitors. We'll set the "threadObj" field later.
292 prepareThread(thread);
293 gDvm.threadList = thread;
295 #ifdef COUNT_PRECISE_METHODS
296 gDvm.preciseMethods = dvmPointerSetAlloc(200);
303 * All threads should be stopped by now. Clean up some thread globals.
305 void dvmThreadShutdown()
307 if (gDvm.threadList != NULL) {
309 * If we walk through the thread list and try to free the
310 * lingering thread structures (which should only be for daemon
311 * threads), the daemon threads may crash if they execute before
312 * the process dies. Let them leak.
314 freeThread(gDvm.threadList);
315 gDvm.threadList = NULL;
318 dvmFreeBitVector(gDvm.threadIdMap);
320 dvmFreeMonitorList();
322 pthread_key_delete(gDvm.pthreadKeySelf);
327 * Grab the suspend count global lock.
329 static inline void lockThreadSuspendCount()
332 * Don't try to change to VMWAIT here. When we change back to RUNNING
333 * we have to check for a pending suspend, which results in grabbing
334 * this lock recursively. Doesn't work with "fast" pthread mutexes.
336 * This lock is always held for very brief periods, so as long as
337 * mutex ordering is respected we shouldn't stall.
339 dvmLockMutex(&gDvm.threadSuspendCountLock);
343 * Release the suspend count global lock.
345 static inline void unlockThreadSuspendCount()
347 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
351 * Grab the thread list global lock.
353 * This is held while "suspend all" is trying to make everybody stop. If
354 * the shutdown is in progress, and somebody tries to grab the lock, they'll
355 * have to wait for the GC to finish. Therefore it's important that the
356 * thread not be in RUNNING mode.
358 * We don't have to check to see if we should be suspended once we have
359 * the lock. Nobody can suspend all threads without holding the thread list
360 * lock while they do it, so by definition there isn't a GC in progress.
362 * This function deliberately avoids the use of dvmChangeStatus(),
363 * which could grab threadSuspendCountLock. To avoid deadlock, threads
364 * are required to grab the thread list lock before the thread suspend
365 * count lock. (See comment in DvmGlobals.)
367 * TODO: consider checking for suspend after acquiring the lock, and
368 * backing off if set. As stated above, it can't happen during normal
369 * execution, but it *can* happen during shutdown when daemon threads
370 * are being suspended.
372 void dvmLockThreadList(Thread* self)
374 ThreadStatus oldStatus;
376 if (self == NULL) /* try to get it from TLS */
377 self = dvmThreadSelf();
380 oldStatus = self->status;
381 self->status = THREAD_VMWAIT;
383 /* happens during VM shutdown */
384 oldStatus = THREAD_UNDEFINED; // shut up gcc
387 dvmLockMutex(&gDvm.threadListLock);
390 self->status = oldStatus;
394 * Try to lock the thread list.
396 * Returns "true" if we locked it. This is a "fast" mutex, so if the
397 * current thread holds the lock this will fail.
399 bool dvmTryLockThreadList()
401 return (dvmTryLockMutex(&gDvm.threadListLock) == 0);
405 * Release the thread list global lock.
407 void dvmUnlockThreadList()
409 dvmUnlockMutex(&gDvm.threadListLock);
413 * Convert SuspendCause to a string.
415 static const char* getSuspendCauseStr(SuspendCause why)
418 case SUSPEND_NOT: return "NOT?";
419 case SUSPEND_FOR_GC: return "gc";
420 case SUSPEND_FOR_DEBUG: return "debug";
421 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
422 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
423 case SUSPEND_FOR_VERIFY: return "verify";
424 case SUSPEND_FOR_HPROF: return "hprof";
425 #if defined(WITH_JIT)
426 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
427 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
428 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
429 case SUSPEND_FOR_REFRESH: return "refresh jit status";
431 default: return "UNKNOWN";
436 * Grab the "thread suspend" lock. This is required to prevent the
437 * GC and the debugger from simultaneously suspending all threads.
439 * If we fail to get the lock, somebody else is trying to suspend all
440 * threads -- including us. If we go to sleep on the lock we'll deadlock
441 * the VM. Loop until we get it or somebody puts us to sleep.
443 static void lockThreadSuspend(const char* who, SuspendCause why)
445 const int kSpinSleepTime = 3*1000*1000; /* 3s */
446 u8 startWhen = 0; // init req'd to placate gcc
451 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
453 Thread* self = dvmThreadSelf();
455 if (!dvmCheckSuspendPending(self)) {
457 * Could be that a resume-all is in progress, and something
458 * grabbed the CPU when the wakeup was broadcast. The thread
459 * performing the resume hasn't had a chance to release the
460 * thread suspend lock. (We release before the broadcast,
461 * so this should be a narrow window.)
463 * Could be we hit the window as a suspend was started,
464 * and the lock has been grabbed but the suspend counts
465 * haven't been incremented yet.
467 * Could be an unusual JNI thread-attach thing.
469 * Could be the debugger telling us to resume at roughly
470 * the same time we're posting an event.
472 * Could be two app threads both want to patch predicted
473 * chaining cells around the same time.
475 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
476 " it's held, no suspend pending",
477 self->threadId, who, getSuspendCauseStr(why));
479 /* we suspended; reset timeout */
483 /* give the lock-holder a chance to do some work */
485 startWhen = dvmGetRelativeTimeUsec();
486 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
487 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
489 self->threadId, who, getSuspendCauseStr(why));
490 /* threads are not suspended, thread dump could crash */
491 dvmDumpAllThreads(false);
500 * Release the "thread suspend" lock.
502 static inline void unlockThreadSuspend()
504 dvmUnlockMutex(&gDvm._threadSuspendLock);
509 * Kill any daemon threads that still exist. All of ours should be
510 * stopped, so these should be Thread objects or JNI-attached threads
511 * started by the application. Actively-running threads are likely
512 * to crash the process if they continue to execute while the VM
513 * shuts down, so we really need to kill or suspend them. (If we want
514 * the VM to restart within this process, we need to kill them, but that
515 * leaves open the possibility of orphaned resources.)
517 * Waiting for the thread to suspend may be unwise at this point, but
518 * if one of these is wedged in a critical section then we probably
519 * would've locked up on the last GC attempt.
521 * It's possible for this function to get called after a failed
522 * initialization, so be careful with assumptions about the environment.
524 * This will be called from whatever thread calls DestroyJavaVM, usually
525 * but not necessarily the main thread. It's likely, but not guaranteed,
526 * that the current thread has already been cleaned up.
528 void dvmSlayDaemons()
530 Thread* self = dvmThreadSelf(); // may be null
535 dvmLockThreadList(self);
538 threadId = self->threadId;
540 target = gDvm.threadList;
541 while (target != NULL) {
542 if (target == self) {
543 target = target->next;
547 if (!dvmGetFieldBoolean(target->threadObj,
548 gDvm.offJavaLangThread_daemon))
550 /* should never happen; suspend it with the rest */
551 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!",
552 threadId, target->threadId);
555 std::string threadName(dvmGetThreadName(target));
556 LOGV("threadid=%d: suspending daemon id=%d name='%s'",
557 threadId, target->threadId, threadName.c_str());
559 /* mark as suspended */
560 lockThreadSuspendCount();
561 dvmAddToSuspendCounts(target, 1, 0);
562 unlockThreadSuspendCount();
565 target = target->next;
568 //dvmDumpAllThreads(false);
571 * Unlock the thread list, relocking it later if necessary. It's
572 * possible a thread is in VMWAIT after calling dvmLockThreadList,
573 * and that function *doesn't* check for pending suspend after
574 * acquiring the lock. We want to let them finish their business
575 * and see the pending suspend before we continue here.
577 * There's no guarantee of mutex fairness, so this might not work.
578 * (The alternative is to have dvmLockThreadList check for suspend
579 * after acquiring the lock and back off, something we should consider.)
581 dvmUnlockThreadList();
584 bool complained = false;
588 dvmLockThreadList(self);
591 * Sleep for a bit until the threads have suspended. We're trying
592 * to exit, so don't wait for too long.
595 for (i = 0; i < 10; i++) {
596 bool allSuspended = true;
598 target = gDvm.threadList;
599 while (target != NULL) {
600 if (target == self) {
601 target = target->next;
605 if (target->status == THREAD_RUNNING) {
607 LOGD("threadid=%d not ready yet", target->threadId);
608 allSuspended = false;
609 /* keep going so we log each running daemon once */
612 target = target->next;
616 LOGV("threadid=%d: all daemons have suspended", threadId);
621 LOGD("threadid=%d: waiting briefly for daemon suspension",
628 dvmUnlockThreadList();
631 #if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
633 * Abandon the threads and recover their resources.
635 target = gDvm.threadList;
636 while (target != NULL) {
637 Thread* nextTarget = target->next;
638 unlinkThread(target);
644 //dvmDumpAllThreads(true);
649 * Finish preparing the parts of the Thread struct required to support
652 bool dvmPrepMainForJni(JNIEnv* pEnv)
656 /* main thread is always first in list at this point */
657 self = gDvm.threadList;
658 assert(self->threadId == kMainThreadId);
660 /* create a "fake" JNI frame at the top of the main thread interp stack */
661 if (!createFakeEntryFrame(self))
664 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
665 dvmSetJniEnvThreadId(pEnv, self);
666 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
673 * Finish preparing the main thread, allocating some objects to represent
674 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
675 * This will execute some interpreted code (e.g. class initializers).
677 bool dvmPrepMainThread()
683 StringObject* threadNameStr;
687 LOGV("+++ finishing prep on main VM thread");
689 /* main thread is always first in list at this point */
690 thread = gDvm.threadList;
691 assert(thread->threadId == kMainThreadId);
694 * Make sure the classes are initialized. We have to do this before
695 * we create an instance of them.
697 if (!dvmInitClass(gDvm.classJavaLangClass)) {
698 LOGE("'Class' class failed to initialize");
701 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
702 !dvmInitClass(gDvm.classJavaLangThread) ||
703 !dvmInitClass(gDvm.classJavaLangVMThread))
705 LOGE("thread classes failed to initialize");
709 groupObj = dvmGetMainThreadGroup();
710 if (groupObj == NULL)
714 * Allocate and construct a Thread with the internal-creation
717 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
718 if (threadObj == NULL) {
719 LOGE("unable to allocate main thread object");
722 dvmReleaseTrackedAlloc(threadObj, NULL);
724 threadNameStr = dvmCreateStringFromCstr("main");
725 if (threadNameStr == NULL)
727 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
729 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
730 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
731 assert(init != NULL);
732 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
733 THREAD_NORM_PRIORITY, false);
734 if (dvmCheckException(thread)) {
735 LOGE("exception thrown while constructing main thread object");
740 * Allocate and construct a VMThread.
742 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
743 if (vmThreadObj == NULL) {
744 LOGE("unable to allocate main vmthread object");
747 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
749 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
750 "(Ljava/lang/Thread;)V");
751 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
752 if (dvmCheckException(thread)) {
753 LOGE("exception thrown while constructing main vmthread object");
757 /* set the VMThread.vmData field to our Thread struct */
758 assert(gDvm.offJavaLangVMThread_vmData != 0);
759 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
762 * Stuff the VMThread back into the Thread. From this point on, other
763 * Threads will see that this Thread is running (at least, they would,
764 * if there were any).
766 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
769 thread->threadObj = threadObj;
772 * Set the "context class loader" field in the system class loader.
774 * Retrieving the system class loader will cause invocation of
775 * ClassLoader.getSystemClassLoader(), which could conceivably call
776 * Thread.currentThread(), so we want the Thread to be fully configured
779 Object* systemLoader = dvmGetSystemClassLoader();
780 if (systemLoader == NULL) {
781 LOGW("WARNING: system class loader is NULL (setting main ctxt)");
784 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_contextClassLoader,
786 dvmReleaseTrackedAlloc(systemLoader, NULL);
789 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
790 gDvm.nonDaemonThreadCount++;
797 * Alloc and initialize a Thread struct.
799 * Does not create any objects, just stuff on the system (malloc) heap.
801 static Thread* allocThread(int interpStackSize)
806 thread = (Thread*) calloc(1, sizeof(Thread));
810 /* Check sizes and alignment */
811 assert((((uintptr_t)&thread->interpBreak.all) & 0x7) == 0);
812 assert(sizeof(thread->interpBreak) == sizeof(thread->interpBreak.all));
815 #if defined(WITH_SELF_VERIFICATION)
816 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
820 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
822 thread->status = THREAD_INITIALIZING;
825 * Allocate and initialize the interpreted code stack. We essentially
826 * "lose" the alloc pointer, which points at the bottom of the stack,
827 * but we can get it back later because we know how big the stack is.
829 * The stack must be aligned on a 4-byte boundary.
831 #ifdef MALLOC_INTERP_STACK
832 stackBottom = (u1*) malloc(interpStackSize);
833 if (stackBottom == NULL) {
834 #if defined(WITH_SELF_VERIFICATION)
835 dvmSelfVerificationShadowSpaceFree(thread);
840 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
842 stackBottom = (u1*) mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
843 MAP_PRIVATE | MAP_ANON, -1, 0);
844 if (stackBottom == MAP_FAILED) {
845 #if defined(WITH_SELF_VERIFICATION)
846 dvmSelfVerificationShadowSpaceFree(thread);
853 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
854 thread->interpStackSize = interpStackSize;
855 thread->interpStackStart = stackBottom + interpStackSize;
856 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
858 #ifndef DVM_NO_ASM_INTERP
859 thread->mainHandlerTable = dvmAsmInstructionStart;
860 thread->altHandlerTable = dvmAsmAltInstructionStart;
861 thread->interpBreak.ctl.curHandlerTable = thread->mainHandlerTable;
864 /* give the thread code a chance to set things up */
865 dvmInitInterpStack(thread, interpStackSize);
867 /* One-time setup for interpreter/JIT state */
868 dvmInitInterpreterState(thread);
874 * Get a meaningful thread ID. At present this only has meaning under Linux,
875 * where getpid() and gettid() sometimes agree and sometimes don't depending
876 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
878 pid_t dvmGetSysThreadId()
888 * Finish initialization of a Thread struct.
890 * This must be called while executing in the new thread, but before the
891 * thread is added to the thread list.
893 * NOTE: The threadListLock must be held by the caller (needed for
896 static bool prepareThread(Thread* thread)
898 assignThreadId(thread);
899 thread->handle = pthread_self();
900 thread->systemTid = dvmGetSysThreadId();
902 //LOGI("SYSTEM TID IS %d (pid is %d)", (int) thread->systemTid,
905 * If we were called by dvmAttachCurrentThread, the self value is
906 * already correctly established as "thread".
908 setThreadSelf(thread);
910 LOGV("threadid=%d: interp stack at %p",
911 thread->threadId, thread->interpStackStart - thread->interpStackSize);
914 * Initialize invokeReq.
916 dvmInitMutex(&thread->invokeReq.lock);
917 pthread_cond_init(&thread->invokeReq.cv, NULL);
920 * Initialize our reference tracking tables.
922 * Most threads won't use jniMonitorRefTable, so we clear out the
923 * structure but don't call the init function (which allocs storage).
925 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
926 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
928 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
929 kInternalRefDefault, kInternalRefMax))
932 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
934 pthread_cond_init(&thread->waitCond, NULL);
935 dvmInitMutex(&thread->waitMutex);
937 /* Initialize safepoint callback mechanism */
938 dvmInitMutex(&thread->callbackMutex);
944 * Remove a thread from the internal list.
945 * Clear out the links to make it obvious that the thread is
946 * no longer on the list. Caller must hold gDvm.threadListLock.
948 static void unlinkThread(Thread* thread)
950 LOG_THREAD("threadid=%d: removing from list", thread->threadId);
951 if (thread == gDvm.threadList) {
952 assert(thread->prev == NULL);
953 gDvm.threadList = thread->next;
955 assert(thread->prev != NULL);
956 thread->prev->next = thread->next;
958 if (thread->next != NULL)
959 thread->next->prev = thread->prev;
960 thread->prev = thread->next = NULL;
964 * Free a Thread struct, and all the stuff allocated within.
966 static void freeThread(Thread* thread)
971 /* thread->threadId is zero at this point */
972 LOGVV("threadid=%d: freeing", thread->threadId);
974 if (thread->interpStackStart != NULL) {
975 u1* interpStackBottom;
977 interpStackBottom = thread->interpStackStart;
978 interpStackBottom -= thread->interpStackSize;
979 #ifdef MALLOC_INTERP_STACK
980 free(interpStackBottom);
982 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
983 LOGW("munmap(thread stack) failed");
987 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
988 dvmClearReferenceTable(&thread->internalLocalRefTable);
989 if (&thread->jniMonitorRefTable.table != NULL)
990 dvmClearReferenceTable(&thread->jniMonitorRefTable);
992 #if defined(WITH_SELF_VERIFICATION)
993 dvmSelfVerificationShadowSpaceFree(thread);
999 * Like pthread_self(), but on a Thread*.
1001 Thread* dvmThreadSelf()
1003 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1007 * Explore our sense of self. Stuffs the thread pointer into TLS.
1009 static void setThreadSelf(Thread* thread)
1013 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1016 * Sometimes this fails under Bionic with EINVAL during shutdown.
1017 * This can happen if the timing is just right, e.g. a thread
1018 * fails to attach during shutdown, but the "fail" path calls
1019 * here to ensure we clean up after ourselves.
1021 if (thread != NULL) {
1022 LOGE("pthread_setspecific(%p) failed, err=%d", thread, cc);
1023 dvmAbort(); /* the world is fundamentally hosed */
1029 * This is associated with the pthreadKeySelf key. It's called by the
1030 * pthread library when a thread is exiting and the "self" pointer in TLS
1031 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
1032 * operation this will not be called.
1034 * This is mainly of use to ensure that we don't leak resources if, for
1035 * example, a thread attaches itself to us with AttachCurrentThread and
1036 * then exits without notifying the VM.
1038 * We could do the detach here instead of aborting, but this will lead to
1039 * portability problems. Other implementations do not do this check and
1040 * will simply be unaware that the thread has exited, leading to resource
1041 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1042 * VM tries to shut down).
1044 * Because some implementations may want to use the pthread destructor
1045 * to initiate the detach, and the ordering of destructors is not defined,
1046 * we want to iterate a couple of times to give those a chance to run.
1048 static void threadExitCheck(void* arg)
1050 const int kMaxCount = 2;
1052 Thread* self = (Thread*) arg;
1053 assert(self != NULL);
1055 LOGV("threadid=%d: threadExitCheck(%p) count=%d",
1056 self->threadId, arg, self->threadExitCheckCount);
1058 if (self->status == THREAD_ZOMBIE) {
1059 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck",
1064 if (self->threadExitCheckCount < kMaxCount) {
1066 * Spin a couple of times to let other destructors fire.
1068 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)",
1069 self->threadId, self->threadExitCheckCount);
1070 self->threadExitCheckCount++;
1071 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1073 LOGE("threadid=%d: unable to re-add thread to TLS",
1078 LOGE("threadid=%d: native thread exited without detaching",
1086 * Assign the threadId. This needs to be a small integer so that our
1087 * "thin" locks fit in a small number of bits.
1089 * We reserve zero for use as an invalid ID.
1091 * This must be called with threadListLock held.
1093 static void assignThreadId(Thread* thread)
1096 * Find a small unique integer. threadIdMap is a vector of
1097 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1098 * bit, meaning that it will always be < kMaxThreadId.
1100 int num = dvmAllocBit(gDvm.threadIdMap);
1102 LOGE("Ran out of thread IDs");
1103 dvmAbort(); // TODO: make this a non-fatal error result
1106 thread->threadId = num + 1;
1108 assert(thread->threadId != 0);
1112 * Give back the thread ID.
1114 static void releaseThreadId(Thread* thread)
1116 assert(thread->threadId > 0);
1117 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
1118 thread->threadId = 0;
1123 * Add a stack frame that makes it look like the native code in the main
1124 * thread was originally invoked from interpreted code. This gives us a
1125 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1126 * VM begins by executing "main" in a class, so in a way this brings us
1127 * closer to the spec.
1129 static bool createFakeEntryFrame(Thread* thread)
1132 * Because we are creating a frame that represents application code, we
1133 * want to stuff the application class loader into the method's class
1134 * loader field, even though we're using the system class loader to
1135 * load it. This makes life easier over in JNI FindClass (though it
1136 * could bite us in other ways).
1138 * Unfortunately this is occurring too early in the initialization,
1139 * of necessity coming before JNI is initialized, and we're not quite
1140 * ready to set up the application class loader. Also, overwriting
1141 * the class' defining classloader pointer seems unwise.
1143 * Instead, we save a pointer to the method and explicitly check for
1144 * it in FindClass. The method is private so nobody else can call it.
1147 assert(thread->threadId == kMainThreadId); /* main thread only */
1149 if (!dvmPushJNIFrame(thread, gDvm.methDalvikSystemNativeStart_main))
1153 * Null out the "String[] args" argument.
1155 assert(gDvm.methDalvikSystemNativeStart_main->registersSize == 1);
1156 u4* framePtr = (u4*) thread->interpSave.curFrame;
1164 * Add a stack frame that makes it look like the native thread has been
1165 * executing interpreted code. This gives us a place to hang JNI local
1168 static bool createFakeRunFrame(Thread* thread)
1170 return dvmPushJNIFrame(thread, gDvm.methDalvikSystemNativeStart_run);
1174 * Helper function to set the name of the current thread
1176 static void setThreadName(const char *threadName)
1180 const char *s = threadName;
1182 if (*s == '.') hasDot = 1;
1183 else if (*s == '@') hasAt = 1;
1186 int len = s - threadName;
1187 if (len < 15 || hasAt || !hasDot) {
1190 s = threadName + len - 15;
1192 #if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
1193 /* pthread_setname_np fails rather than truncating long strings */
1194 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1195 strncpy(buf, s, sizeof(buf)-1);
1196 buf[sizeof(buf)-1] = '\0';
1197 int err = pthread_setname_np(pthread_self(), buf);
1199 LOGW("Unable to set the name of current thread to '%s': %s",
1200 buf, strerror(err));
1202 #elif defined(HAVE_PRCTL)
1203 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
1205 LOGD("No way to set current thread's name (%s)", s);
1210 * Create a thread as a result of java.lang.Thread.start().
1212 * We do have to worry about some concurrency problems, e.g. programs
1213 * that try to call Thread.start() on the same object from multiple threads.
1214 * (This will fail for all but one, but we have to make sure that it succeeds
1217 * Some of the complexity here arises from our desire to mimic the
1218 * Thread vs. VMThread class decomposition we inherited. We've been given
1219 * a Thread, and now we need to create a VMThread and then populate both
1220 * objects. We also need to create one of our internal Thread objects.
1222 * Pass in a stack size of 0 to get the default.
1224 * The "threadObj" reference must be pinned by the caller to prevent the GC
1225 * from moving it around (e.g. added to the tracked allocation list).
1227 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1229 assert(threadObj != NULL);
1231 Thread* self = dvmThreadSelf();
1233 if (reqStackSize == 0)
1234 stackSize = gDvm.stackSize;
1235 else if (reqStackSize < kMinStackSize)
1236 stackSize = kMinStackSize;
1237 else if (reqStackSize > kMaxStackSize)
1238 stackSize = kMaxStackSize;
1240 stackSize = reqStackSize;
1242 pthread_attr_t threadAttr;
1243 pthread_attr_init(&threadAttr);
1244 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1247 * To minimize the time spent in the critical section, we allocate the
1248 * vmThread object here.
1250 Object* vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1251 if (vmThreadObj == NULL)
1254 Thread* newThread = allocThread(stackSize);
1255 if (newThread == NULL) {
1256 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1260 newThread->threadObj = threadObj;
1262 assert(newThread->status == THREAD_INITIALIZING);
1265 * We need to lock out other threads while we test and set the
1266 * "vmThread" field in java.lang.Thread, because we use that to determine
1267 * if this thread has been started before. We use the thread list lock
1268 * because it's handy and we're going to need to grab it again soon
1271 dvmLockThreadList(self);
1273 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1274 dvmUnlockThreadList();
1275 dvmThrowIllegalThreadStateException(
1276 "thread has already been started");
1277 freeThread(newThread);
1278 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1282 * There are actually three data structures: Thread (object), VMThread
1283 * (object), and Thread (C struct). All of them point to at least one
1286 * As soon as "VMThread.vmData" is assigned, other threads can start
1287 * making calls into us (e.g. setPriority).
1289 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1290 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1293 * Thread creation might take a while, so release the lock.
1295 dvmUnlockThreadList();
1297 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1298 pthread_t threadHandle;
1299 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1301 dvmChangeStatus(self, oldStatus);
1305 * Failure generally indicates that we have exceeded system
1306 * resource limits. VirtualMachineError is probably too severe,
1307 * so use OutOfMemoryError.
1309 LOGE("Thread creation failed (err=%s)", strerror(errno));
1311 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1313 dvmThrowOutOfMemoryError("thread creation failed");
1318 * We need to wait for the thread to start. Otherwise, depending on
1319 * the whims of the OS scheduler, we could return and the code in our
1320 * thread could try to do operations on the new thread before it had
1321 * finished starting.
1323 * The new thread will lock the thread list, change its state to
1324 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1325 * on gDvm.threadStartCond (which uses the thread list lock). This
1326 * thread (the parent) will either see that the thread is already ready
1327 * after we grab the thread list lock, or will be awakened from the
1328 * condition variable on the broadcast.
1330 * We don't want to stall the rest of the VM while the new thread
1331 * starts, which can happen if the GC wakes up at the wrong moment.
1332 * So, we change our own status to VMWAIT, and self-suspend if
1333 * necessary after we finish adding the new thread.
1336 * We have to deal with an odd race with the GC/debugger suspension
1337 * mechanism when creating a new thread. The information about whether
1338 * or not a thread should be suspended is contained entirely within
1339 * the Thread struct; this is usually cleaner to deal with than having
1340 * one or more globally-visible suspension flags. The trouble is that
1341 * we could create the thread while the VM is trying to suspend all
1342 * threads. The suspend-count won't be nonzero for the new thread,
1343 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1345 * The easiest way to deal with this is to prevent the new thread from
1346 * running until the parent says it's okay. This results in the
1347 * following (correct) sequence of events for a "badly timed" GC
1348 * (where '-' is us, 'o' is the child, and '+' is some other thread):
1350 * - call pthread_create()
1351 * - lock thread list
1352 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1353 * - sleep on condition var (mutex = thread list lock) until child starts
1354 * + GC triggered by another thread
1355 * + thread list locked; suspend counts updated; thread list unlocked
1356 * + loop waiting for all runnable threads to suspend
1357 * + success, start GC
1358 * o child thread wakes, signals condition var to wake parent
1359 * o child waits for parent ack on condition variable
1360 * - we wake up, locking thread list
1361 * - add child to thread list
1362 * - unlock thread list
1363 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1364 * + GC finishes; all threads in thread list are resumed
1365 * - lock thread list
1366 * - set child to THREAD_VMWAIT, and signal it to start
1367 * - unlock thread list
1369 * o child changes state to THREAD_RUNNING
1371 * The above shows the GC starting up during thread creation, but if
1372 * it starts anywhere after VMThread.create() is called it will
1373 * produce the same series of events.
1375 * Once the child is in the thread list, it will be suspended and
1376 * resumed like any other thread. In the above scenario the resume-all
1377 * code will try to resume the new thread, which was never actually
1378 * suspended, and try to decrement the child's thread suspend count to -1.
1379 * We can catch this in the resume-all code.
1381 * Bouncing back and forth between threads like this adds a small amount
1382 * of scheduler overhead to thread startup.
1384 * One alternative to having the child wait for the parent would be
1385 * to have the child inherit the parents' suspension count. This
1386 * would work for a GC, since we can safely assume that the parent
1387 * thread didn't cause it, but we must only do so if the parent suspension
1388 * was caused by a suspend-all. If the parent was being asked to
1389 * suspend singly by the debugger, the child should not inherit the value.
1391 * We could also have a global "new thread suspend count" that gets
1392 * picked up by new threads before changing state to THREAD_RUNNING.
1393 * This would be protected by the thread list lock and set by a
1396 dvmLockThreadList(self);
1397 assert(self->status == THREAD_RUNNING);
1398 self->status = THREAD_VMWAIT;
1399 while (newThread->status != THREAD_STARTING)
1400 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1402 LOG_THREAD("threadid=%d: adding to list", newThread->threadId);
1403 newThread->next = gDvm.threadList->next;
1404 if (newThread->next != NULL)
1405 newThread->next->prev = newThread;
1406 newThread->prev = gDvm.threadList;
1407 gDvm.threadList->next = newThread;
1409 /* Add any existing global modes to the interpBreak control */
1410 dvmInitializeInterpBreak(newThread);
1412 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1413 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1415 dvmUnlockThreadList();
1417 /* change status back to RUNNING, self-suspending if necessary */
1418 dvmChangeStatus(self, THREAD_RUNNING);
1421 * Tell the new thread to start.
1423 * We must hold the thread list lock before messing with another thread.
1424 * In the general case we would also need to verify that newThread was
1425 * still in the thread list, but in our case the thread has not started
1426 * executing user code and therefore has not had a chance to exit.
1428 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1429 * comes with a suspend-pending check.
1431 dvmLockThreadList(self);
1433 assert(newThread->status == THREAD_STARTING);
1434 newThread->status = THREAD_VMWAIT;
1435 pthread_cond_broadcast(&gDvm.threadStartCond);
1437 dvmUnlockThreadList();
1439 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1443 freeThread(newThread);
1444 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1449 * pthread entry function for threads started from interpreted code.
1451 static void* interpThreadStart(void* arg)
1453 Thread* self = (Thread*) arg;
1455 std::string threadName(dvmGetThreadName(self));
1456 setThreadName(threadName.c_str());
1459 * Finish initializing the Thread struct.
1461 dvmLockThreadList(self);
1462 prepareThread(self);
1464 LOG_THREAD("threadid=%d: created from interp", self->threadId);
1467 * Change our status and wake our parent, who will add us to the
1468 * thread list and advance our state to VMWAIT.
1470 self->status = THREAD_STARTING;
1471 pthread_cond_broadcast(&gDvm.threadStartCond);
1474 * Wait until the parent says we can go. Assuming there wasn't a
1475 * suspend pending, this will happen immediately. When it completes,
1476 * we're full-fledged citizens of the VM.
1478 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1479 * because the pthread_cond_wait below needs to reacquire a lock that
1480 * suspend-all is also interested in. If we get unlucky, the parent could
1481 * change us to THREAD_RUNNING, then a GC could start before we get
1482 * signaled, and suspend-all will grab the thread list lock and then
1483 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1484 * trying to get the lock.
1486 while (self->status != THREAD_VMWAIT)
1487 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1489 dvmUnlockThreadList();
1492 * Add a JNI context.
1494 self->jniEnv = dvmCreateJNIEnv(self);
1497 * Change our state so the GC will wait for us from now on. If a GC is
1498 * in progress this call will suspend us.
1500 dvmChangeStatus(self, THREAD_RUNNING);
1503 * Notify the debugger & DDM. The debugger notification may cause
1504 * us to suspend ourselves (and others). The thread state may change
1505 * to VMWAIT briefly if network packets are sent.
1507 if (gDvm.debuggerConnected)
1508 dvmDbgPostThreadStart(self);
1511 * Set the system thread priority according to the Thread object's
1512 * priority level. We don't usually need to do this, because both the
1513 * Thread object and system thread priorities inherit from parents. The
1514 * tricky case is when somebody creates a Thread object, calls
1515 * setPriority(), and then starts the thread. We could manage this with
1516 * a "needs priority update" flag to avoid the redundant call.
1518 int priority = dvmGetFieldInt(self->threadObj,
1519 gDvm.offJavaLangThread_priority);
1520 dvmChangeThreadPriority(self, priority);
1523 * Execute the "run" method.
1525 * At this point our stack is empty, so somebody who comes looking for
1526 * stack traces right now won't have much to look at. This is normal.
1528 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1531 LOGV("threadid=%d: calling run()", self->threadId);
1532 assert(strcmp(run->name, "run") == 0);
1533 dvmCallMethod(self, run, self->threadObj, &unused);
1534 LOGV("threadid=%d: exiting", self->threadId);
1537 * Remove the thread from various lists, report its death, and free
1540 dvmDetachCurrentThread();
1546 * The current thread is exiting with an uncaught exception. The
1547 * Java programming language allows the application to provide a
1548 * thread-exit-uncaught-exception handler for the VM, for a specific
1549 * Thread, and for all threads in a ThreadGroup.
1551 * Version 1.5 added the per-thread handler. We need to call
1552 * "uncaughtException" in the handler object, which is either the
1553 * ThreadGroup object or the Thread-specific handler.
1555 * This should only be called when an exception is pending. Before
1556 * returning, the exception will be cleared.
1558 static void threadExitUncaughtException(Thread* self, Object* group)
1562 Method* uncaughtHandler;
1564 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)",
1565 self->threadId, group);
1566 assert(group != NULL);
1569 * Get a pointer to the exception, then clear out the one in the
1570 * thread. We don't want to have it set when executing interpreted code.
1572 exception = dvmGetException(self);
1573 assert(exception != NULL);
1574 dvmAddTrackedAlloc(exception, self);
1575 dvmClearException(self);
1578 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1579 * else use "group" (which is an instance of UncaughtExceptionHandler).
1580 * The ThreadGroup will handle it directly or call the default
1581 * uncaught exception handler.
1583 handlerObj = dvmGetFieldObject(self->threadObj,
1584 gDvm.offJavaLangThread_uncaughtHandler);
1585 if (handlerObj == NULL)
1589 * Find the "uncaughtException" method in this object. The method
1590 * was declared in the Thread.UncaughtExceptionHandler interface.
1592 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1593 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1595 if (uncaughtHandler != NULL) {
1596 //LOGI("+++ calling %s.uncaughtException",
1597 // handlerObj->clazz->descriptor);
1599 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1600 self->threadObj, exception);
1602 /* should be impossible, but handle it anyway */
1603 LOGW("WARNING: no 'uncaughtException' method in class %s",
1604 handlerObj->clazz->descriptor);
1605 dvmSetException(self, exception);
1606 dvmLogExceptionStackTrace();
1609 /* if the uncaught handler threw, clear it */
1610 dvmClearException(self);
1612 dvmReleaseTrackedAlloc(exception, self);
1614 /* Remove this thread's suspendCount from global suspendCount sum */
1615 lockThreadSuspendCount();
1616 dvmAddToSuspendCounts(self, -self->suspendCount, 0);
1617 unlockThreadSuspendCount();
1622 * Create an internal VM thread, for things like JDWP and finalizers.
1624 * The easiest way to do this is create a new thread and then use the
1625 * JNI AttachCurrentThread implementation.
1627 * This does not return until after the new thread has begun executing.
1629 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1630 InternalThreadStart func, void* funcArg)
1632 InternalStartArgs* pArgs;
1633 Object* systemGroup;
1634 pthread_attr_t threadAttr;
1635 volatile Thread* newThread = NULL;
1636 volatile int createStatus = 0;
1638 systemGroup = dvmGetSystemThreadGroup();
1639 if (systemGroup == NULL)
1642 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1644 pArgs->funcArg = funcArg;
1645 pArgs->name = strdup(name); // storage will be owned by new thread
1646 pArgs->group = systemGroup;
1647 pArgs->isDaemon = true;
1648 pArgs->pThread = &newThread;
1649 pArgs->pCreateStatus = &createStatus;
1651 pthread_attr_init(&threadAttr);
1652 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1654 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1657 LOGE("internal thread creation failed");
1664 * Wait for the child to start. This gives us an opportunity to make
1665 * sure that the thread started correctly, and allows our caller to
1666 * assume that the thread has started running.
1668 * Because we aren't holding a lock across the thread creation, it's
1669 * possible that the child will already have completed its
1670 * initialization. Because the child only adjusts "createStatus" while
1671 * holding the thread list lock, the initial condition on the "while"
1672 * loop will correctly avoid the wait if this occurs.
1674 * It's also possible that we'll have to wait for the thread to finish
1675 * being created, and as part of allocating a Thread object it might
1676 * need to initiate a GC. We switch to VMWAIT while we pause.
1678 Thread* self = dvmThreadSelf();
1679 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1680 dvmLockThreadList(self);
1681 while (createStatus == 0)
1682 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1684 if (newThread == NULL) {
1685 LOGW("internal thread create failed (createStatus=%d)", createStatus);
1686 assert(createStatus < 0);
1687 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1688 dvmUnlockThreadList();
1689 dvmChangeStatus(self, oldStatus);
1693 /* thread could be in any state now (except early init states) */
1694 //assert(newThread->status == THREAD_RUNNING);
1696 dvmUnlockThreadList();
1697 dvmChangeStatus(self, oldStatus);
1703 * pthread entry function for internally-created threads.
1705 * We are expected to free "arg" and its contents. If we're a daemon
1706 * thread, and we get cancelled abruptly when the VM shuts down, the
1707 * storage won't be freed. If this becomes a concern we can make a copy
1710 static void* internalThreadStart(void* arg)
1712 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1713 JavaVMAttachArgs jniArgs;
1715 jniArgs.version = JNI_VERSION_1_2;
1716 jniArgs.name = pArgs->name;
1717 jniArgs.group = reinterpret_cast<jobject>(pArgs->group);
1719 setThreadName(pArgs->name);
1721 /* use local jniArgs as stack top */
1722 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1724 * Tell the parent of our success.
1726 * threadListLock is the mutex for threadStartCond.
1728 dvmLockThreadList(dvmThreadSelf());
1729 *pArgs->pCreateStatus = 1;
1730 *pArgs->pThread = dvmThreadSelf();
1731 pthread_cond_broadcast(&gDvm.threadStartCond);
1732 dvmUnlockThreadList();
1734 LOG_THREAD("threadid=%d: internal '%s'",
1735 dvmThreadSelf()->threadId, pArgs->name);
1738 (*pArgs->func)(pArgs->funcArg);
1740 /* detach ourselves */
1741 dvmDetachCurrentThread();
1744 * Tell the parent of our failure. We don't have a Thread struct,
1745 * so we can't be suspended, so we don't need to enter a critical
1748 dvmLockThreadList(dvmThreadSelf());
1749 *pArgs->pCreateStatus = -1;
1750 assert(*pArgs->pThread == NULL);
1751 pthread_cond_broadcast(&gDvm.threadStartCond);
1752 dvmUnlockThreadList();
1754 assert(*pArgs->pThread == NULL);
1763 * Attach the current thread to the VM.
1765 * Used for internally-created threads and JNI's AttachCurrentThread.
1767 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1769 Thread* self = NULL;
1770 Object* threadObj = NULL;
1771 Object* vmThreadObj = NULL;
1772 StringObject* threadNameStr = NULL;
1776 /* allocate thread struct, and establish a basic sense of self */
1777 self = allocThread(gDvm.stackSize);
1780 setThreadSelf(self);
1783 * Finish our thread prep. We need to do this before adding ourselves
1784 * to the thread list or invoking any interpreted code. prepareThread()
1785 * requires that we hold the thread list lock.
1787 dvmLockThreadList(self);
1788 ok = prepareThread(self);
1789 dvmUnlockThreadList();
1793 self->jniEnv = dvmCreateJNIEnv(self);
1794 if (self->jniEnv == NULL)
1798 * Create a "fake" JNI frame at the top of the main thread interp stack.
1799 * It isn't really necessary for the internal threads, but it gives
1800 * the debugger something to show. It is essential for the JNI-attached
1803 if (!createFakeRunFrame(self))
1807 * The native side of the thread is ready; add it to the list. Once
1808 * it's on the list the thread is visible to the JDWP code and the GC.
1810 LOG_THREAD("threadid=%d: adding to list (attached)", self->threadId);
1812 dvmLockThreadList(self);
1814 self->next = gDvm.threadList->next;
1815 if (self->next != NULL)
1816 self->next->prev = self;
1817 self->prev = gDvm.threadList;
1818 gDvm.threadList->next = self;
1820 gDvm.nonDaemonThreadCount++;
1822 dvmUnlockThreadList();
1825 * Switch state from initializing to running.
1827 * It's possible that a GC began right before we added ourselves
1828 * to the thread list, and is still going. That means our thread
1829 * suspend count won't reflect the fact that we should be suspended.
1830 * To deal with this, we transition to VMWAIT, pulse the heap lock,
1831 * and then advance to RUNNING. That will ensure that we stall until
1834 * Once we're in RUNNING, we're like any other thread in the VM (except
1835 * for the lack of an initialized threadObj). We're then free to
1836 * allocate and initialize objects.
1838 assert(self->status == THREAD_INITIALIZING);
1839 dvmChangeStatus(self, THREAD_VMWAIT);
1840 dvmLockMutex(&gDvm.gcHeapLock);
1841 dvmUnlockMutex(&gDvm.gcHeapLock);
1842 dvmChangeStatus(self, THREAD_RUNNING);
1845 * Create Thread and VMThread objects.
1847 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
1848 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1849 if (threadObj == NULL || vmThreadObj == NULL)
1853 * This makes threadObj visible to the GC. We still have it in the
1854 * tracked allocation table, so it can't move around on us.
1856 self->threadObj = threadObj;
1857 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1860 * Create a string for the thread name.
1862 if (pArgs->name != NULL) {
1863 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
1864 if (threadNameStr == NULL) {
1865 assert(dvmCheckException(dvmThreadSelf()));
1870 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1871 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1873 assert(dvmCheckException(self));
1878 * Now we're ready to run some interpreted code.
1880 * We need to construct the Thread object and set the VMThread field.
1881 * Setting VMThread tells interpreted code that we're alive.
1883 * Call the (group, name, priority, daemon) constructor on the Thread.
1884 * This sets the thread's name and adds it to the specified group, and
1885 * provides values for priority and daemon (which are normally inherited
1886 * from the current thread).
1889 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
1890 threadNameStr, os_getThreadPriorityFromSystem(), isDaemon);
1891 if (dvmCheckException(self)) {
1892 LOGE("exception thrown while constructing attached thread object");
1897 * Set the VMThread field, which tells interpreted code that we're alive.
1899 * The risk of a thread start collision here is very low; somebody
1900 * would have to be deliberately polling the ThreadGroup list and
1901 * trying to start threads against anything it sees, which would
1902 * generally cause problems for all thread creation. However, for
1903 * correctness we test "vmThread" before setting it.
1905 * TODO: this still has a race, it's just smaller. Not sure this is
1906 * worth putting effort into fixing. Need to hold a lock while
1907 * fiddling with the field, or maybe initialize the Thread object in a
1908 * way that ensures another thread can't call start() on it.
1910 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1911 LOGW("WOW: thread start hijack");
1912 dvmThrowIllegalThreadStateException(
1913 "thread has already been started");
1914 /* We don't want to free anything associated with the thread
1915 * because someone is obviously interested in it. Just let
1916 * it go and hope it will clean itself up when its finished.
1917 * This case should never happen anyway.
1919 * Since we're letting it live, we need to finish setting it up.
1920 * We just have to let the caller know that the intended operation
1923 * [ This seems strange -- stepping on the vmThread object that's
1924 * already present seems like a bad idea. TODO: figure this out. ]
1930 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1932 /* we can now safely un-pin these */
1933 dvmReleaseTrackedAlloc(threadObj, self);
1934 dvmReleaseTrackedAlloc(vmThreadObj, self);
1935 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
1937 LOG_THREAD("threadid=%d: attached from native, name=%s",
1938 self->threadId, pArgs->name);
1940 /* tell the debugger & DDM */
1941 if (gDvm.debuggerConnected)
1942 dvmDbgPostThreadStart(self);
1947 dvmLockThreadList(self);
1950 gDvm.nonDaemonThreadCount--;
1951 dvmUnlockThreadList();
1952 /* fall through to "fail" */
1954 dvmReleaseTrackedAlloc(threadObj, self);
1955 dvmReleaseTrackedAlloc(vmThreadObj, self);
1956 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
1958 if (self->jniEnv != NULL) {
1959 dvmDestroyJNIEnv(self->jniEnv);
1960 self->jniEnv = NULL;
1964 setThreadSelf(NULL);
1969 * Detach the thread from the various data structures, notify other threads
1970 * that are waiting to "join" it, and free up all heap-allocated storage.
1972 * Used for all threads.
1974 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
1975 * requires us to enforce this for the DetachCurrentThread call, probably
1976 * because it also says that DetachCurrentThread causes all monitors
1977 * associated with the thread to be released. (Because the stack is empty,
1978 * we only have to worry about explicit JNI calls to MonitorEnter.)
1981 * We might want to avoid freeing our internal Thread structure until the
1982 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
1983 * get to once the thread shuts down, but there is a small possibility of
1984 * an operation starting in another thread before this thread halts, and
1985 * finishing much later (perhaps the thread got stalled by a weird OS bug).
1986 * We don't want something like Thread.isInterrupted() crawling through
1987 * freed storage. Can do with a Thread finalizer, or by creating a
1988 * dedicated ThreadObject class for java/lang/Thread and moving all of our
1991 void dvmDetachCurrentThread()
1993 Thread* self = dvmThreadSelf();
1998 * Make sure we're not detaching a thread that's still running. (This
1999 * could happen with an explicit JNI detach call.)
2001 * A thread created by interpreted code will finish with a depth of
2002 * zero, while a JNI-attached thread will have the synthetic "stack
2003 * starter" native method at the top.
2005 int curDepth = dvmComputeExactFrameDepth(self->interpSave.curFrame);
2006 if (curDepth != 0) {
2007 bool topIsNative = false;
2009 if (curDepth == 1) {
2010 /* not expecting a lingering break frame; just look at curFrame */
2011 assert(!dvmIsBreakFrame((u4*)self->interpSave.curFrame));
2012 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->interpSave.curFrame);
2013 if (dvmIsNativeMethod(ssa->method))
2018 LOGE("ERROR: detaching thread with interp frames (count=%d)",
2020 dvmDumpThread(self, false);
2025 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2026 LOG_THREAD("threadid=%d: detach (group=%p)", self->threadId, group);
2029 * Release any held monitors. Since there are no interpreted stack
2030 * frames, the only thing left are the monitors held by JNI MonitorEnter
2033 dvmReleaseJniMonitors(self);
2036 * Do some thread-exit uncaught exception processing if necessary.
2038 if (dvmCheckException(self))
2039 threadExitUncaughtException(self, group);
2042 * Remove the thread from the thread group.
2044 if (group != NULL) {
2045 Method* removeThread =
2046 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2048 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2052 * Clear the vmThread reference in the Thread object. Interpreted code
2053 * will now see that this Thread is not running. As this may be the
2054 * only reference to the VMThread object that the VM knows about, we
2055 * have to create an internal reference to it first.
2057 vmThread = dvmGetFieldObject(self->threadObj,
2058 gDvm.offJavaLangThread_vmThread);
2059 dvmAddTrackedAlloc(vmThread, self);
2060 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2062 /* clear out our struct Thread pointer, since it's going away */
2063 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2066 * Tell the debugger & DDM. This may cause the current thread or all
2067 * threads to suspend.
2069 * The JDWP spec is somewhat vague about when this happens, other than
2070 * that it's issued by the dying thread, which may still appear in
2071 * an "all threads" listing.
2073 if (gDvm.debuggerConnected)
2074 dvmDbgPostThreadDeath(self);
2077 * Thread.join() is implemented as an Object.wait() on the VMThread
2078 * object. Signal anyone who is waiting.
2080 dvmLockObject(self, vmThread);
2081 dvmObjectNotifyAll(self, vmThread);
2082 dvmUnlockObject(self, vmThread);
2084 dvmReleaseTrackedAlloc(vmThread, self);
2088 * We're done manipulating objects, so it's okay if the GC runs in
2089 * parallel with us from here out. It's important to do this if
2090 * profiling is enabled, since we can wait indefinitely.
2092 volatile void* raw = reinterpret_cast<volatile void*>(&self->status);
2093 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
2094 android_atomic_release_store(THREAD_VMWAIT, addr);
2097 * If we're doing method trace profiling, we don't want threads to exit,
2098 * because if they do we'll end up reusing thread IDs. This complicates
2099 * analysis and makes it impossible to have reasonable output in the
2100 * "threads" section of the "key" file.
2102 * We need to do this after Thread.join() completes, or other threads
2103 * could get wedged. Since self->threadObj is still valid, the Thread
2104 * object will not get GCed even though we're no longer in the ThreadGroup
2105 * list (which is important since the profiling thread needs to get
2106 * the thread's name).
2108 MethodTraceState* traceState = &gDvm.methodTrace;
2110 dvmLockMutex(&traceState->startStopLock);
2111 if (traceState->traceEnabled) {
2112 LOGI("threadid=%d: waiting for method trace to finish",
2114 while (traceState->traceEnabled) {
2115 dvmWaitCond(&traceState->threadExitCond,
2116 &traceState->startStopLock);
2119 dvmUnlockMutex(&traceState->startStopLock);
2121 dvmLockThreadList(self);
2124 * Lose the JNI context.
2126 dvmDestroyJNIEnv(self->jniEnv);
2127 self->jniEnv = NULL;
2129 self->status = THREAD_ZOMBIE;
2132 * Remove ourselves from the internal thread list.
2137 * If we're the last one standing, signal anybody waiting in
2138 * DestroyJavaVM that it's okay to exit.
2140 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2141 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2143 if (gDvm.nonDaemonThreadCount == 0) {
2146 LOGV("threadid=%d: last non-daemon thread", self->threadId);
2147 //dvmDumpAllThreads(false);
2148 // cond var guarded by threadListLock, which we already hold
2149 cc = pthread_cond_signal(&gDvm.vmExitCond);
2154 LOGV("threadid=%d: bye!", self->threadId);
2155 releaseThreadId(self);
2156 dvmUnlockThreadList();
2158 setThreadSelf(NULL);
2165 * Suspend a single thread. Do not use to suspend yourself.
2167 * This is used primarily for debugger/DDMS activity. Does not return
2168 * until the thread has suspended or is in a "safe" state (e.g. executing
2169 * native code outside the VM).
2171 * The thread list lock should be held before calling here -- it's not
2172 * entirely safe to hang on to a Thread* from another thread otherwise.
2173 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2175 void dvmSuspendThread(Thread* thread)
2177 assert(thread != NULL);
2178 assert(thread != dvmThreadSelf());
2179 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2181 lockThreadSuspendCount();
2182 dvmAddToSuspendCounts(thread, 1, 1);
2184 LOG_THREAD("threadid=%d: suspend++, now=%d",
2185 thread->threadId, thread->suspendCount);
2186 unlockThreadSuspendCount();
2188 waitForThreadSuspend(dvmThreadSelf(), thread);
2192 * Reduce the suspend count of a thread. If it hits zero, tell it to
2195 * Used primarily for debugger/DDMS activity. The thread in question
2196 * might have been suspended singly or as part of a suspend-all operation.
2198 * The thread list lock should be held before calling here -- it's not
2199 * entirely safe to hang on to a Thread* from another thread otherwise.
2200 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2202 void dvmResumeThread(Thread* thread)
2204 assert(thread != NULL);
2205 assert(thread != dvmThreadSelf());
2206 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2208 lockThreadSuspendCount();
2209 if (thread->suspendCount > 0) {
2210 dvmAddToSuspendCounts(thread, -1, -1);
2212 LOG_THREAD("threadid=%d: suspendCount already zero",
2216 LOG_THREAD("threadid=%d: suspend--, now=%d",
2217 thread->threadId, thread->suspendCount);
2219 if (thread->suspendCount == 0) {
2220 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
2223 unlockThreadSuspendCount();
2227 * Suspend yourself, as a result of debugger activity.
2229 void dvmSuspendSelf(bool jdwpActivity)
2231 Thread* self = dvmThreadSelf();
2233 /* debugger thread must not suspend itself due to debugger activity! */
2234 assert(gDvm.jdwpState != NULL);
2235 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2241 * Collisions with other suspends aren't really interesting. We want
2242 * to ensure that we're the only one fiddling with the suspend count
2245 lockThreadSuspendCount();
2246 dvmAddToSuspendCounts(self, 1, 1);
2249 * Suspend ourselves.
2251 assert(self->suspendCount > 0);
2252 self->status = THREAD_SUSPENDED;
2253 LOG_THREAD("threadid=%d: self-suspending (dbg)", self->threadId);
2256 * Tell JDWP that we've completed suspension. The JDWP thread can't
2257 * tell us to resume before we're fully asleep because we hold the
2258 * suspend count lock.
2260 * If we got here via waitForDebugger(), don't do this part.
2263 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)",
2264 // self->threadId, (int) self->handle);
2265 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2268 while (self->suspendCount != 0) {
2269 dvmWaitCond(&gDvm.threadSuspendCountCond,
2270 &gDvm.threadSuspendCountLock);
2271 if (self->suspendCount != 0) {
2273 * The condition was signaled but we're still suspended. This
2274 * can happen if the debugger lets go while a SIGQUIT thread
2275 * dump event is pending (assuming SignalCatcher was resumed for
2276 * just long enough to try to grab the thread-suspend lock).
2278 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)",
2279 self->threadId, self->suspendCount, self->dbgSuspendCount);
2282 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2283 self->status = THREAD_RUNNING;
2284 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d",
2285 self->threadId, self->status);
2287 unlockThreadSuspendCount();
2291 * Dump the state of the current thread and that of another thread that
2292 * we think is wedged.
2294 static void dumpWedgedThread(Thread* thread)
2296 dvmDumpThread(dvmThreadSelf(), false);
2297 dvmPrintNativeBackTrace();
2299 // dumping a running thread is risky, but could be useful
2300 dvmDumpThread(thread, true);
2302 // stop now and get a core dump
2307 * If the thread is running at below-normal priority, temporarily elevate
2310 * Returns zero if no changes were made. Otherwise, returns bit flags
2311 * indicating what was changed, storing the previous values in the
2312 * provided locations.
2314 int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
2315 SchedPolicy* pSavedThreadPolicy)
2318 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2320 LOGW("Unable to get priority for threadid=%d sysTid=%d",
2321 thread->threadId, thread->systemTid);
2324 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2325 LOGW("Unable to get policy for threadid=%d sysTid=%d",
2326 thread->threadId, thread->systemTid);
2330 int changeFlags = 0;
2333 * Change the priority if we're in the background group.
2335 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2336 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2337 LOGW("Couldn't set fg policy on tid %d", thread->systemTid);
2339 changeFlags |= kChangedPolicy;
2340 LOGD("Temporarily moving tid %d to fg (was %d)",
2341 thread->systemTid, *pSavedThreadPolicy);
2346 * getpriority() returns the "nice" value, so larger numbers indicate
2347 * lower priority, with 0 being normal.
2349 if (*pSavedThreadPrio > 0) {
2350 const int kHigher = 0;
2351 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2352 LOGW("Couldn't raise priority on tid %d to %d",
2353 thread->systemTid, kHigher);
2355 changeFlags |= kChangedPriority;
2356 LOGD("Temporarily raised priority on tid %d (%d -> %d)",
2357 thread->systemTid, *pSavedThreadPrio, kHigher);
2365 * Reset the priority values for the thread in question.
2367 void dvmResetThreadPriority(Thread* thread, int changeFlags,
2368 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2370 if ((changeFlags & kChangedPolicy) != 0) {
2371 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2372 LOGW("NOTE: couldn't reset tid %d to (%d)",
2373 thread->systemTid, savedThreadPolicy);
2375 LOGD("Restored policy of %d to %d",
2376 thread->systemTid, savedThreadPolicy);
2380 if ((changeFlags & kChangedPriority) != 0) {
2381 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2383 LOGW("NOTE: couldn't reset priority on thread %d to %d",
2384 thread->systemTid, savedThreadPrio);
2386 LOGD("Restored priority on %d to %d",
2387 thread->systemTid, savedThreadPrio);
2393 * Wait for another thread to see the pending suspension and stop running.
2394 * It can either suspend itself or go into a non-running state such as
2395 * VMWAIT or NATIVE in which it cannot interact with the GC.
2397 * If we're running at a higher priority, sched_yield() may not do anything,
2398 * so we need to sleep for "long enough" to guarantee that the other
2399 * thread has a chance to finish what it's doing. Sleeping for too short
2400 * a period (e.g. less than the resolution of the sleep clock) might cause
2401 * the scheduler to return immediately, so we want to start with a
2402 * "reasonable" value and expand.
2404 * This does not return until the other thread has stopped running.
2405 * Eventually we time out and the VM aborts.
2407 * This does not try to detect the situation where two threads are
2408 * waiting for each other to suspend. In normal use this is part of a
2409 * suspend-all, which implies that the suspend-all lock is held, or as
2410 * part of a debugger action in which the JDWP thread is always the one
2411 * doing the suspending. (We may need to re-evaluate this now that
2412 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2414 * TODO: track basic stats about time required to suspend VM.
2416 #define FIRST_SLEEP (250*1000) /* 0.25s */
2417 #define MORE_SLEEP (750*1000) /* 0.75s */
2418 static void waitForThreadSuspend(Thread* self, Thread* thread)
2420 const int kMaxRetries = 10;
2421 int spinSleepTime = FIRST_SLEEP;
2422 bool complained = false;
2423 int priChangeFlags = 0;
2424 int savedThreadPrio = -500;
2425 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
2429 u8 startWhen = 0; // init req'd to placate gcc
2430 u8 firstStartWhen = 0;
2432 while (thread->status == THREAD_RUNNING) {
2433 if (sleepIter == 0) { // get current time on first iteration
2434 startWhen = dvmGetRelativeTimeUsec();
2435 if (firstStartWhen == 0) // first iteration of first attempt
2436 firstStartWhen = startWhen;
2439 * After waiting for a bit, check to see if the target thread is
2440 * running at a reduced priority. If so, bump it up temporarily
2441 * to give it more CPU time.
2443 if (retryCount == 2) {
2444 assert(thread->systemTid != 0);
2445 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
2446 &savedThreadPrio, &savedThreadPolicy);
2450 #if defined (WITH_JIT)
2452 * If we're still waiting after the first timeout, unchain all
2454 * 1) There are new chains formed since the last unchain
2455 * 2) The top VM frame of the running thread is running JIT'ed code
2457 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2458 gDvmJit.hasNewChain && thread->inJitCodeCache) {
2459 LOGD("JIT unchain all for threadid=%d", thread->threadId);
2465 * Sleep briefly. The iterative sleep call returns false if we've
2466 * exceeded the total time limit for this round of sleeping.
2468 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
2469 if (spinSleepTime != FIRST_SLEEP) {
2470 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)",
2471 self->threadId, retryCount,
2472 thread->threadId, priChangeFlags);
2473 if (retryCount > 1) {
2474 /* stack trace logging is slow; skip on first iter */
2475 dumpWedgedThread(thread);
2480 // keep going; could be slow due to valgrind
2482 spinSleepTime = MORE_SLEEP;
2484 if (retryCount++ == kMaxRetries) {
2485 LOGE("Fatal spin-on-suspend, dumping threads");
2486 dvmDumpAllThreads(false);
2488 /* log this after -- long traces will scroll off log */
2489 LOGE("threadid=%d: stuck on threadid=%d, giving up",
2490 self->threadId, thread->threadId);
2492 /* try to get a debuggerd dump from the spinning thread */
2493 dvmNukeThread(thread);
2501 LOGW("threadid=%d: spin on suspend resolved in %lld msec",
2503 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
2504 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2506 if (priChangeFlags != 0) {
2507 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
2513 * Suspend all threads except the current one. This is used by the GC,
2514 * the debugger, and by any thread that hits a "suspend all threads"
2515 * debugger event (e.g. breakpoint or exception).
2517 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2518 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2519 * create objects and even execute arbitrary code. The "why" argument
2520 * allows the caller to say why the suspension is taking place.
2522 * This can be called when a global suspend has already happened, due to
2523 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2526 * DO NOT grab any locks before calling here. We grab & release the thread
2527 * lock and suspend lock here (and we're not using recursive threads), and
2528 * we might have to self-suspend if somebody else beats us here.
2530 * We know the current thread is in the thread list, because we attach the
2531 * thread before doing anything that could cause VM suspension (like object
2534 void dvmSuspendAllThreads(SuspendCause why)
2536 Thread* self = dvmThreadSelf();
2542 * Start by grabbing the thread suspend lock. If we can't get it, most
2543 * likely somebody else is in the process of performing a suspend or
2544 * resume, so lockThreadSuspend() will cause us to self-suspend.
2546 * We keep the lock until all other threads are suspended.
2548 lockThreadSuspend("susp-all", why);
2550 LOG_THREAD("threadid=%d: SuspendAll starting", self->threadId);
2553 * This is possible if the current thread was in VMWAIT mode when a
2554 * suspend-all happened, and then decided to do its own suspend-all.
2555 * This can happen when a couple of threads have simultaneous events
2556 * of interest to the debugger.
2558 //assert(self->suspendCount == 0);
2561 * Increment everybody's suspend count (except our own).
2563 dvmLockThreadList(self);
2565 lockThreadSuspendCount();
2566 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2570 /* debugger events don't suspend JDWP thread */
2571 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2572 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2575 dvmAddToSuspendCounts(thread, 1,
2576 (why == SUSPEND_FOR_DEBUG ||
2577 why == SUSPEND_FOR_DEBUG_EVENT)
2580 unlockThreadSuspendCount();
2583 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2584 * indicate the code is either running natively or sleeping quietly.
2585 * Any attempt to transition back to THREAD_RUNNING will cause a check
2586 * for suspension, so it should be impossible for anything to execute
2587 * interpreted code or modify objects (assuming native code plays nicely).
2589 * It's also okay if the thread transitions to a non-RUNNING state.
2591 * Note we released the threadSuspendCountLock before getting here,
2592 * so if another thread is fiddling with its suspend count (perhaps
2593 * self-suspending for the debugger) it won't block while we're waiting
2596 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2600 /* debugger events don't suspend JDWP thread */
2601 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2602 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2605 /* wait for the other thread to see the pending suspend */
2606 waitForThreadSuspend(self, thread);
2608 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d",
2609 self->threadId, thread->threadId, thread->status,
2610 thread->suspendCount, thread->dbgSuspendCount);
2613 dvmUnlockThreadList();
2614 unlockThreadSuspend();
2616 LOG_THREAD("threadid=%d: SuspendAll complete", self->threadId);
2620 * Resume all threads that are currently suspended.
2622 * The "why" must match with the previous suspend.
2624 void dvmResumeAllThreads(SuspendCause why)
2626 Thread* self = dvmThreadSelf();
2630 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2631 LOG_THREAD("threadid=%d: ResumeAll starting", self->threadId);
2634 * Decrement the suspend counts for all threads. No need for atomic
2635 * writes, since nobody should be moving until we decrement the count.
2636 * We do need to hold the thread list because of JNI attaches.
2638 dvmLockThreadList(self);
2639 lockThreadSuspendCount();
2640 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2644 /* debugger events don't suspend JDWP thread */
2645 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2646 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2651 if (thread->suspendCount > 0) {
2652 dvmAddToSuspendCounts(thread, -1,
2653 (why == SUSPEND_FOR_DEBUG ||
2654 why == SUSPEND_FOR_DEBUG_EVENT)
2657 LOG_THREAD("threadid=%d: suspendCount already zero",
2661 unlockThreadSuspendCount();
2662 dvmUnlockThreadList();
2665 * In some ways it makes sense to continue to hold the thread-suspend
2666 * lock while we issue the wakeup broadcast. It allows us to complete
2667 * one operation before moving on to the next, which simplifies the
2668 * thread activity debug traces.
2670 * This approach caused us some difficulty under Linux, because the
2671 * condition variable broadcast not only made the threads runnable,
2672 * but actually caused them to execute, and it was a while before
2673 * the thread performing the wakeup had an opportunity to release the
2674 * thread-suspend lock.
2676 * This is a problem because, when a thread tries to acquire that
2677 * lock, it times out after 3 seconds. If at some point the thread
2678 * is told to suspend, the clock resets; but since the VM is still
2679 * theoretically mid-resume, there's no suspend pending. If, for
2680 * example, the GC was waking threads up while the SIGQUIT handler
2681 * was trying to acquire the lock, we would occasionally time out on
2682 * a busy system and SignalCatcher would abort.
2684 * We now perform the unlock before the wakeup broadcast. The next
2685 * suspend can't actually start until the broadcast completes and
2686 * returns, because we're holding the thread-suspend-count lock, but the
2687 * suspending thread is now able to make progress and we avoid the abort.
2689 * (Technically there is a narrow window between when we release
2690 * the thread-suspend lock and grab the thread-suspend-count lock.
2691 * This could cause us to send a broadcast to threads with nonzero
2692 * suspend counts, but this is expected and they'll all just fall
2693 * right back to sleep. It's probably safe to grab the suspend-count
2694 * lock before releasing thread-suspend, since we're still following
2695 * the correct order of acquisition, but it feels weird.)
2698 LOG_THREAD("threadid=%d: ResumeAll waking others", self->threadId);
2699 unlockThreadSuspend();
2702 * Broadcast a notification to all suspended threads, some or all of
2703 * which may choose to wake up. No need to wait for them.
2705 lockThreadSuspendCount();
2706 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2708 unlockThreadSuspendCount();
2710 LOG_THREAD("threadid=%d: ResumeAll complete", self->threadId);
2714 * Undo any debugger suspensions. This is called when the debugger
2717 void dvmUndoDebuggerSuspensions()
2719 Thread* self = dvmThreadSelf();
2723 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2724 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting", self->threadId);
2727 * Decrement the suspend counts for all threads. No need for atomic
2728 * writes, since nobody should be moving until we decrement the count.
2729 * We do need to hold the thread list because of JNI attaches.
2731 dvmLockThreadList(self);
2732 lockThreadSuspendCount();
2733 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2737 /* debugger events don't suspend JDWP thread */
2738 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2739 assert(thread->dbgSuspendCount == 0);
2743 assert(thread->suspendCount >= thread->dbgSuspendCount);
2744 dvmAddToSuspendCounts(thread, -thread->dbgSuspendCount,
2745 -thread->dbgSuspendCount);
2747 unlockThreadSuspendCount();
2748 dvmUnlockThreadList();
2751 * Broadcast a notification to all suspended threads, some or all of
2752 * which may choose to wake up. No need to wait for them.
2754 lockThreadSuspendCount();
2755 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2757 unlockThreadSuspendCount();
2759 unlockThreadSuspend();
2761 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete", self->threadId);
2765 * Determine if a thread is suspended.
2767 * As with all operations on foreign threads, the caller should hold
2768 * the thread list lock before calling.
2770 * If the thread is suspending or waking, these fields could be changing
2771 * out from under us (or the thread could change state right after we
2772 * examine it), making this generally unreliable. This is chiefly
2773 * intended for use by the debugger.
2775 bool dvmIsSuspended(const Thread* thread)
2778 * The thread could be:
2779 * (1) Running happily. status is RUNNING, suspendCount is zero.
2781 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
2783 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
2785 * (4) Waking up. suspendCount is zero, status is SUSPENDED
2786 * Return "false" (since it could change out from under us, unless
2787 * we hold suspendCountLock).
2790 return (thread->suspendCount != 0 &&
2791 thread->status != THREAD_RUNNING);
2795 * Wait until another thread self-suspends. This is specifically for
2796 * synchronization between the JDWP thread and a thread that has decided
2797 * to suspend itself after sending an event to the debugger.
2799 * Threads that encounter "suspend all" events work as well -- the thread
2800 * in question suspends everybody else and then itself.
2802 * We can't hold a thread lock here or in the caller, because we could
2803 * get here just before the to-be-waited-for-thread issues a "suspend all".
2804 * There's an opportunity for badness if the thread we're waiting for exits
2805 * and gets cleaned up, but since the thread in question is processing a
2806 * debugger event, that's not really a possibility. (To avoid deadlock,
2807 * it's important that we not be in THREAD_RUNNING while we wait.)
2809 void dvmWaitForSuspend(Thread* thread)
2811 Thread* self = dvmThreadSelf();
2813 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep",
2814 self->threadId, thread->threadId);
2816 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2817 assert(thread != self);
2818 assert(self->status != THREAD_RUNNING);
2820 waitForThreadSuspend(self, thread);
2822 LOG_THREAD("threadid=%d: threadid=%d is now asleep",
2823 self->threadId, thread->threadId);
2827 * Check to see if we need to suspend ourselves. If so, go to sleep on
2828 * a condition variable.
2830 * Returns "true" if we suspended ourselves.
2832 static bool fullSuspendCheck(Thread* self)
2834 assert(self != NULL);
2835 assert(self->suspendCount >= 0);
2838 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
2839 * access to self->suspendCount.
2841 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
2843 bool needSuspend = (self->suspendCount != 0);
2845 LOG_THREAD("threadid=%d: self-suspending", self->threadId);
2846 ThreadStatus oldStatus = self->status; /* should be RUNNING */
2847 self->status = THREAD_SUSPENDED;
2849 while (self->suspendCount != 0) {
2851 * Wait for wakeup signal, releasing lock. The act of releasing
2852 * and re-acquiring the lock provides the memory barriers we
2853 * need for correct behavior on SMP.
2855 dvmWaitCond(&gDvm.threadSuspendCountCond,
2856 &gDvm.threadSuspendCountLock);
2858 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2859 self->status = oldStatus;
2860 LOG_THREAD("threadid=%d: self-reviving, status=%d",
2861 self->threadId, self->status);
2864 unlockThreadSuspendCount();
2870 * Check to see if a suspend is pending. If so, suspend the current
2871 * thread, and return "true" after we have been resumed.
2873 bool dvmCheckSuspendPending(Thread* self)
2875 assert(self != NULL);
2876 if (self->suspendCount == 0) {
2879 return fullSuspendCheck(self);
2884 * Update our status.
2886 * The "self" argument, which may be NULL, is accepted as an optimization.
2888 * Returns the old status.
2890 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
2892 ThreadStatus oldStatus;
2895 self = dvmThreadSelf();
2897 LOGVV("threadid=%d: (status %d -> %d)",
2898 self->threadId, self->status, newStatus);
2900 oldStatus = self->status;
2901 if (oldStatus == newStatus)
2904 if (newStatus == THREAD_RUNNING) {
2906 * Change our status to THREAD_RUNNING. The transition requires
2907 * that we check for pending suspension, because the VM considers
2908 * us to be "asleep" in all other states, and another thread could
2909 * be performing a GC now.
2911 * The order of operations is very significant here. One way to
2914 * GCing thread Our thread (in NATIVE)
2915 * ------------ ----------------------
2916 * check suspend count (== 0)
2917 * dvmSuspendAllThreads()
2918 * grab suspend-count lock
2919 * increment all suspend counts
2920 * release suspend-count lock
2921 * check thread state (== NATIVE)
2922 * all are suspended, begin GC
2923 * set state to RUNNING
2924 * (continue executing)
2926 * We can correct this by grabbing the suspend-count lock and
2927 * performing both of our operations (check suspend count, set
2928 * state) while holding it, now we need to grab a mutex on every
2929 * transition to RUNNING.
2931 * What we do instead is change the order of operations so that
2932 * the transition to RUNNING happens first. If we then detect
2933 * that the suspend count is nonzero, we switch to SUSPENDED.
2935 * Appropriate compiler and memory barriers are required to ensure
2936 * that the operations are observed in the expected order.
2938 * This does create a small window of opportunity where a GC in
2939 * progress could observe what appears to be a running thread (if
2940 * it happens to look between when we set to RUNNING and when we
2941 * switch to SUSPENDED). At worst this only affects assertions
2942 * and thread logging. (We could work around it with some sort
2943 * of intermediate "pre-running" state that is generally treated
2944 * as equivalent to running, but that doesn't seem worthwhile.)
2946 * We can also solve this by combining the "status" and "suspend
2947 * count" fields into a single 32-bit value. This trades the
2948 * store/load barrier on transition to RUNNING for an atomic RMW
2949 * op on all transitions and all suspend count updates (also, all
2950 * accesses to status or the thread count require bit-fiddling).
2951 * It also eliminates the brief transition through RUNNING when
2952 * the thread is supposed to be suspended. This is possibly faster
2953 * on SMP and slightly more correct, but less convenient.
2955 volatile void* raw = reinterpret_cast<volatile void*>(&self->status);
2956 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
2957 android_atomic_acquire_store(newStatus, addr);
2958 if (self->suspendCount != 0) {
2959 fullSuspendCheck(self);
2963 * Not changing to THREAD_RUNNING. No additional work required.
2965 * We use a releasing store to ensure that, if we were RUNNING,
2966 * any updates we previously made to objects on the managed heap
2967 * will be observed before the state change.
2969 assert(newStatus != THREAD_SUSPENDED);
2970 volatile void* raw = reinterpret_cast<volatile void*>(&self->status);
2971 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
2972 android_atomic_release_store(newStatus, addr);
2979 * Get a statically defined thread group from a field in the ThreadGroup
2980 * Class object. Expected arguments are "mMain" and "mSystem".
2982 static Object* getStaticThreadGroup(const char* fieldName)
2984 StaticField* groupField;
2987 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
2988 fieldName, "Ljava/lang/ThreadGroup;");
2989 if (groupField == NULL) {
2990 LOGE("java.lang.ThreadGroup does not have an '%s' field", fieldName);
2991 dvmThrowInternalError("bad definition for ThreadGroup");
2994 groupObj = dvmGetStaticFieldObject(groupField);
2995 if (groupObj == NULL) {
2996 LOGE("java.lang.ThreadGroup.%s not initialized", fieldName);
2997 dvmThrowInternalError(NULL);
3003 Object* dvmGetSystemThreadGroup()
3005 return getStaticThreadGroup("mSystem");
3007 Object* dvmGetMainThreadGroup()
3009 return getStaticThreadGroup("mMain");
3013 * Given a VMThread object, return the associated Thread*.
3015 * NOTE: if the thread detaches, the struct Thread will disappear, and
3016 * we will be touching invalid data. For safety, lock the thread list
3017 * before calling this.
3019 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3023 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
3026 Thread* thread = gDvm.threadList;
3027 while (thread != NULL) {
3028 if ((Thread*)vmData == thread)
3031 thread = thread->next;
3034 if (thread == NULL) {
3035 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list",
3036 vmThreadObj, (Thread*)vmData);
3041 return (Thread*) vmData;
3045 * Given a pthread handle, return the associated Thread*.
3046 * Caller must hold the thread list lock.
3048 * Returns NULL if the thread was not found.
3050 Thread* dvmGetThreadByHandle(pthread_t handle)
3053 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3054 if (thread->handle == handle)
3061 * Given a threadId, return the associated Thread*.
3062 * Caller must hold the thread list lock.
3064 * Returns NULL if the thread was not found.
3066 Thread* dvmGetThreadByThreadId(u4 threadId)
3069 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3070 if (thread->threadId == threadId)
3076 void dvmChangeThreadPriority(Thread* thread, int newPriority)
3078 os_changeThreadPriority(thread, newPriority);
3082 * Return true if the thread is on gDvm.threadList.
3083 * Caller should not hold gDvm.threadListLock.
3085 bool dvmIsOnThreadList(const Thread* thread)
3089 dvmLockThreadList(NULL);
3090 if (thread == gDvm.threadList) {
3093 ret = thread->prev != NULL || thread->next != NULL;
3095 dvmUnlockThreadList();
3101 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3104 void dvmDumpThread(Thread* thread, bool isRunning)
3106 DebugOutputTarget target;
3108 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3109 dvmDumpThreadEx(&target, thread, isRunning);
3113 * Try to get the scheduler group.
3115 * The data from /proc/<pid>/cgroup looks (something) like:
3116 * 2:cpu:/bg_non_interactive
3119 * We return the part on the "cpu" line after the '/', which will be an
3120 * empty string for the default cgroup. If the string is longer than
3121 * "bufLen", the string will be truncated.
3123 * On error, -1 is returned, and an error description will be stored in
3126 static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
3128 #ifdef HAVE_ANDROID_OS
3133 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
3134 if ((fp = fopen(pathBuf, "r")) == NULL) {
3135 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
3139 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3144 /* Junk the first field */
3145 subsys = strchr(lineBuf, ':');
3146 if (subsys == NULL) {
3150 if (strncmp(subsys, ":cpu:", 5) != 0) {
3151 /* Not the subsys we're looking for */
3155 grp = strchr(subsys, '/');
3159 grp++; /* Drop the leading '/' */
3162 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3164 if (bufLen <= len) {
3167 strncpy(buf, grp, len);
3173 snprintf(buf, bufLen, "[no-cpu-subsys]");
3178 LOGE("Bad cgroup data {%s}", lineBuf);
3179 snprintf(buf, bufLen, "[data-parse-failed]");
3184 snprintf(buf, bufLen, "[n/a]");
3190 * Convert ThreadStatus to a string.
3192 const char* dvmGetThreadStatusStr(ThreadStatus status)
3195 case THREAD_ZOMBIE: return "ZOMBIE";
3196 case THREAD_RUNNING: return "RUNNABLE";
3197 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3198 case THREAD_MONITOR: return "MONITOR";
3199 case THREAD_WAIT: return "WAIT";
3200 case THREAD_INITIALIZING: return "INITIALIZING";
3201 case THREAD_STARTING: return "STARTING";
3202 case THREAD_NATIVE: return "NATIVE";
3203 case THREAD_VMWAIT: return "VMWAIT";
3204 case THREAD_SUSPENDED: return "SUSPENDED";
3205 default: return "UNKNOWN";
3210 * Print information about the specified thread.
3212 * Works best when the thread in question is "self" or has been suspended.
3213 * When dumping a separate thread that's still running, set "isRunning" to
3214 * use a more cautious thread dump function.
3216 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3221 StringObject* nameStr;
3222 char* threadName = NULL;
3223 char* groupName = NULL;
3224 char schedulerGroupBuf[32];
3226 int priority; // java.lang.Thread priority
3227 int policy; // pthread policy
3228 struct sched_param sp; // pthread scheduling parameters
3229 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
3232 * Get the java.lang.Thread object. This function gets called from
3233 * some weird debug contexts, so it's possible that there's a GC in
3234 * progress on some other thread. To decrease the chances of the
3235 * thread object being moved out from under us, we add the reference
3236 * to the tracked allocation list, which pins it in place.
3238 * If threadObj is NULL, the thread is still in the process of being
3239 * attached to the VM, and there's really nothing interesting to
3242 threadObj = thread->threadObj;
3243 if (threadObj == NULL) {
3244 LOGI("Can't dump thread %d: threadObj not set", thread->threadId);
3247 dvmAddTrackedAlloc(threadObj, NULL);
3249 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3250 gDvm.offJavaLangThread_name);
3251 threadName = dvmCreateCstrFromString(nameStr);
3253 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3254 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3256 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3257 LOGW("Warning: pthread_getschedparam failed");
3259 sp.sched_priority = -1;
3261 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
3262 sizeof(schedulerGroupBuf)) == 0 &&
3263 schedulerGroupBuf[0] == '\0') {
3264 strcpy(schedulerGroupBuf, "default");
3267 /* a null value for group is not expected, but deal with it anyway */
3268 groupObj = (Object*) dvmGetFieldObject(threadObj,
3269 gDvm.offJavaLangThread_group);
3270 if (groupObj != NULL) {
3271 nameStr = (StringObject*)
3272 dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
3273 groupName = dvmCreateCstrFromString(nameStr);
3275 if (groupName == NULL)
3276 groupName = strdup("(null; initializing?)");
3278 dvmPrintDebugMessage(target,
3279 "\"%s\"%s prio=%d tid=%d %s%s\n",
3280 threadName, isDaemon ? " daemon" : "",
3281 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3282 #if defined(WITH_JIT)
3283 thread->inJitCodeCache ? " JIT" : ""
3288 dvmPrintDebugMessage(target,
3289 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
3290 groupName, thread->suspendCount, thread->dbgSuspendCount,
3291 thread->threadObj, thread);
3292 dvmPrintDebugMessage(target,
3293 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
3294 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
3295 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
3297 /* get some bits from /proc/self/stat */
3298 ProcStatData procStatData;
3299 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3300 /* failed, use zeroed values */
3301 memset(&procStatData, 0, sizeof(procStatData));
3304 /* grab the scheduler stats for this thread */
3305 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3307 int schedstatFd = open(schedstatBuf, O_RDONLY);
3308 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
3309 if (schedstatFd >= 0) {
3311 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3314 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
3318 /* show what we got */
3319 dvmPrintDebugMessage(target,
3320 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3321 schedstatBuf, procStatData.utime, procStatData.stime,
3322 procStatData.processor);
3325 dvmDumpRunningThreadStack(target, thread);
3327 dvmDumpThreadStack(target, thread);
3329 dvmReleaseTrackedAlloc(threadObj, NULL);
3334 std::string dvmGetThreadName(Thread* thread) {
3335 if (thread->threadObj == NULL) {
3336 LOGW("threadObj is NULL, name not available");
3340 StringObject* nameObj = (StringObject*)
3341 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3342 return dvmCreateCstrFromString(nameObj);
3346 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3349 void dvmDumpAllThreads(bool grabLock)
3351 DebugOutputTarget target;
3353 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3354 dvmDumpAllThreadsEx(&target, grabLock);
3358 * Print information about all known threads. Assumes they have been
3359 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3361 * If "grabLock" is true, we grab the thread lock list. This is important
3362 * to do unless the caller already holds the lock.
3364 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3368 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3370 #ifdef HAVE_ANDROID_OS
3371 dvmPrintDebugMessage(target,
3372 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x)\n",
3373 gDvm.threadListLock.value,
3374 gDvm._threadSuspendLock.value,
3375 gDvm.threadSuspendCountLock.value,
3376 gDvm.gcHeapLock.value);
3380 dvmLockThreadList(dvmThreadSelf());
3382 thread = gDvm.threadList;
3383 while (thread != NULL) {
3384 dvmDumpThreadEx(target, thread, false);
3387 assert(thread->next == NULL || thread->next->prev == thread);
3389 thread = thread->next;
3393 dvmUnlockThreadList();
3397 * Nuke the target thread from orbit.
3399 * The idea is to send a "crash" signal to the target thread so that
3400 * debuggerd will take notice and dump an appropriate stack trace.
3401 * Because of the way debuggerd works, we have to throw the same signal
3404 * This does not necessarily cause the entire process to stop, but once a
3405 * thread has been nuked the rest of the system is likely to be unstable.
3406 * This returns so that some limited set of additional operations may be
3407 * performed, but it's advisable (and expected) to call dvmAbort soon.
3408 * (This is NOT a way to simply cancel a thread.)
3410 void dvmNukeThread(Thread* thread)
3414 /* suppress the heapworker watchdog to assist anyone using a debugger */
3415 gDvm.nativeDebuggerActive = true;
3418 * Send the signals, separated by a brief interval to allow debuggerd
3419 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3420 * can be used instead of SIGSEGV to avoid making it look like the
3421 * code actually crashed at the current point of execution.
3423 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3424 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3425 * you don't get the second stack trace; possibly something in the
3426 * kernel decides that a signal has already been sent and it's time
3427 * to just kill the process. The position in the current thread is
3428 * generally known, so the second dump is not useful.)
3430 * The target thread can continue to execute between the two signals.
3431 * (The first just causes debuggerd to attach to it.)
3433 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3434 " cause debuggerd dump",
3435 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
3436 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3437 if (killResult != 0) {
3438 LOGD("NOTE: pthread_kill #1 failed: %s", strerror(killResult));
3440 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
3441 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3442 if (killResult != 0) {
3443 LOGD("NOTE: pthread_kill #2 failed: %s", strerror(killResult));
3445 LOGD("Sent, pausing to let debuggerd run");
3446 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
3448 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3449 signal(SIGSEGV, SIG_IGN);