2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
21 #include "utils/threads.h" // need Android thread priorities
26 #include <sys/resource.h>
30 #if defined(HAVE_PRCTL)
31 #include <sys/prctl.h>
34 /* desktop Linux needs a little help with gettid() */
35 #if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
37 # include <linux/unistd.h>
39 _syscall0(pid_t,gettid)
41 pid_t gettid() { return syscall(__NR_gettid);}
46 // Change this to enable logging on cgroup errors
47 #define ENABLE_CGROUP_ERR_LOGGING 0
49 // change this to LOGV/LOGD to debug thread activity
50 #define LOG_THREAD LOGVV
55 All threads are native pthreads. All threads, except the JDWP debugger
56 thread, are visible to code running in the VM and to the debugger. (We
57 don't want the debugger to try to manipulate the thread that listens for
58 instructions from the debugger.) Internal VM threads are in the "system"
59 ThreadGroup, all others are in the "main" ThreadGroup, per convention.
61 The GC only runs when all threads have been suspended. Threads are
62 expected to suspend themselves, using a "safe point" mechanism. We check
63 for a suspend request at certain points in the main interpreter loop,
64 and on requests coming in from native code (e.g. all JNI functions).
65 Certain debugger events may inspire threads to self-suspend.
67 Native methods must use JNI calls to modify object references to avoid
68 clashes with the GC. JNI doesn't provide a way for native code to access
69 arrays of objects as such -- code must always get/set individual entries --
70 so it should be possible to fully control access through JNI.
72 Internal native VM threads, such as the finalizer thread, must explicitly
73 check for suspension periodically. In most cases they will be sound
74 asleep on a condition variable, and won't notice the suspension anyway.
76 Threads may be suspended by the GC, debugger, or the SIGQUIT listener
77 thread. The debugger may suspend or resume individual threads, while the
78 GC always suspends all threads. Each thread has a "suspend count" that
79 is incremented on suspend requests and decremented on resume requests.
80 When the count is zero, the thread is runnable. This allows us to fulfill
81 a debugger requirement: if the debugger suspends a thread, the thread is
82 not allowed to run again until the debugger resumes it (or disconnects,
83 in which case we must resume all debugger-suspended threads).
85 Paused threads sleep on a condition variable, and are awoken en masse.
86 Certain "slow" VM operations, such as starting up a new thread, will be
87 done in a separate "VMWAIT" state, so that the rest of the VM doesn't
88 freeze up waiting for the operation to finish. Threads must check for
89 pending suspension when leaving VMWAIT.
91 Because threads suspend themselves while interpreting code or when native
92 code makes JNI calls, there is no risk of suspending while holding internal
93 VM locks. All threads can enter a suspended (or native-code-only) state.
94 Also, we don't have to worry about object references existing solely
95 in hardware registers.
97 We do, however, have to worry about objects that were allocated internally
98 and aren't yet visible to anything else in the VM. If we allocate an
99 object, and then go to sleep on a mutex after changing to a non-RUNNING
100 state (e.g. while trying to allocate a second object), the first object
101 could be garbage-collected out from under us while we sleep. To manage
102 this, we automatically add all allocated objects to an internal object
103 tracking list, and only remove them when we know we won't be suspended
104 before the object appears in the GC root set.
106 The debugger may choose to suspend or resume a single thread, which can
107 lead to application-level deadlocks; this is expected behavior. The VM
108 will only check for suspension of single threads when the debugger is
109 active (the java.lang.Thread calls for this are deprecated and hence are
110 not supported). Resumption of a single thread is handled by decrementing
111 the thread's suspend count and sending a broadcast signal to the condition
112 variable. (This will cause all threads to wake up and immediately go back
113 to sleep, which isn't tremendously efficient, but neither is having the
116 The debugger is not allowed to resume threads suspended by the GC. This
117 is trivially enforced by ignoring debugger requests while the GC is running
118 (the JDWP thread is suspended during GC).
120 The VM maintains a Thread struct for every pthread known to the VM. There
121 is a java/lang/Thread object associated with every Thread. At present,
122 there is no safe way to go from a Thread object to a Thread struct except by
123 locking and scanning the list; this is necessary because the lifetimes of
124 the two are not closely coupled. We may want to change this behavior,
125 though at present the only performance impact is on the debugger (see
126 threadObjToThread()). See also notes about dvmDetachCurrentThread().
129 Alternate implementation (signal-based):
131 Threads run without safe points -- zero overhead. The VM uses a signal
132 (e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
134 The trouble with using signals to suspend threads is that it means a thread
135 can be in the middle of an operation when garbage collection starts.
136 To prevent some sticky situations, we have to introduce critical sections
139 Critical sections temporarily block suspension for a given thread.
140 The thread must move to a non-blocked state (and self-suspend) after
141 finishing its current task. If the thread blocks on a resource held
142 by a suspended thread, we're hosed.
144 One approach is to require that no blocking operations, notably
145 acquisition of mutexes, can be performed within a critical section.
146 This is too limiting. For example, if thread A gets suspended while
147 holding the thread list lock, it will prevent the GC or debugger from
148 being able to safely access the thread list. We need to wrap the critical
149 section around the entire operation (enter critical, get lock, do stuff,
150 release lock, exit critical).
152 A better approach is to declare that certain resources can only be held
153 within critical sections. A thread that enters a critical section and
154 then gets blocked on the thread list lock knows that the thread it is
155 waiting for is also in a critical section, and will release the lock
156 before suspending itself. Eventually all threads will complete their
157 operations and self-suspend. For this to work, the VM must:
159 (1) Determine the set of resources that may be accessed from the GC or
160 debugger threads. The mutexes guarding those go into the "critical
162 (2) Ensure that no resource in the CRS can be acquired outside of a
163 critical section. This can be verified with an assert().
164 (3) Ensure that only resources in the CRS can be held while in a critical
165 section. This is harder to enforce.
167 If any of these conditions are not met, deadlock can ensue when grabbing
168 resources in the GC or debugger (#1) or waiting for threads to suspend
169 (#2,#3). (You won't actually deadlock in the GC, because if the semantics
170 above are followed you don't need to lock anything in the GC. The risk is
171 rather that the GC will access data structures in an intermediate state.)
173 This approach requires more care and awareness in the VM than
174 safe-pointing. Because the GC and debugger are fairly intrusive, there
175 really aren't any internal VM resources that aren't shared. Thus, the
176 enter/exit critical calls can be added to internal mutex wrappers, which
177 makes it easy to get #1 and #2 right.
179 An ordering should be established for all locks to avoid deadlocks.
181 Monitor locks, which are also implemented with pthread calls, should not
182 cause any problems here. Threads fighting over such locks will not be in
183 critical sections and can be suspended freely.
185 This can get tricky if we ever need exclusive access to VM and non-VM
186 resources at the same time. It's not clear if this is a real concern.
188 There are (at least) two ways to handle the incoming signals:
190 (a) Always accept signals. If we're in a critical section, the signal
191 handler just returns without doing anything (the "suspend level"
192 should have been incremented before the signal was sent). Otherwise,
193 if the "suspend level" is nonzero, we go to sleep.
194 (b) Block signals in critical sections. This ensures that we can't be
195 interrupted in a critical section, but requires pthread_sigmask()
196 calls on entry and exit.
198 This is a choice between blocking the message and blocking the messenger.
199 Because UNIX signals are unreliable (you can only know that you have been
200 signaled, not whether you were signaled once or 10 times), the choice is
201 not significant for correctness. The choice depends on the efficiency
202 of pthread_sigmask() and the desire to actually block signals. Either way,
203 it is best to ensure that there is only one indication of "blocked";
204 having two (i.e. block signals and set a flag, then only send a signal
205 if the flag isn't set) can lead to race conditions.
207 The signal handler must take care to copy registers onto the stack (via
208 setjmp), so that stack scans find all references. Because we have to scan
209 native stacks, "exact" GC is not possible with this approach.
211 Some other concerns with flinging signals around:
212 - Odd interactions with some debuggers (e.g. gdb on the Mac)
213 - Restrictions on some standard library calls during GC (e.g. don't
214 use printf on stdout to print GC debug messages)
217 #define kMaxThreadId ((1<<15) - 1)
218 #define kMainThreadId ((1<<1) | 1)
221 static Thread* allocThread(int interpStackSize);
222 static bool prepareThread(Thread* thread);
223 static void setThreadSelf(Thread* thread);
224 static void unlinkThread(Thread* thread);
225 static void freeThread(Thread* thread);
226 static void assignThreadId(Thread* thread);
227 static bool createFakeEntryFrame(Thread* thread);
228 static bool createFakeRunFrame(Thread* thread);
229 static void* interpThreadStart(void* arg);
230 static void* internalThreadStart(void* arg);
231 static void threadExitUncaughtException(Thread* thread, Object* group);
232 static void threadExitCheck(void* arg);
233 static void waitForThreadSuspend(Thread* self, Thread* thread);
234 static int getThreadPriorityFromSystem(void);
238 * Initialize thread list and main thread's environment. We need to set
239 * up some basic stuff so that dvmThreadSelf() will work when we start
240 * loading classes (e.g. to check for exceptions).
242 bool dvmThreadStartup(void)
246 /* allocate a TLS slot */
247 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
248 LOGE("ERROR: pthread_key_create failed\n");
252 /* test our pthread lib */
253 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
254 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
256 /* prep thread-related locks and conditions */
257 dvmInitMutex(&gDvm.threadListLock);
258 pthread_cond_init(&gDvm.threadStartCond, NULL);
259 //dvmInitMutex(&gDvm.vmExitLock);
260 pthread_cond_init(&gDvm.vmExitCond, NULL);
261 dvmInitMutex(&gDvm._threadSuspendLock);
262 dvmInitMutex(&gDvm.threadSuspendCountLock);
263 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
264 #ifdef WITH_DEADLOCK_PREDICTION
265 dvmInitMutex(&gDvm.deadlockHistoryLock);
269 * Dedicated monitor for Thread.sleep().
270 * TODO: change this to an Object* so we don't have to expose this
271 * call, and we interact better with JDWP monitor calls. Requires
272 * deferring the object creation to much later (e.g. final "main"
273 * thread prep) or until first use.
275 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
277 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
279 thread = allocThread(gDvm.stackSize);
283 /* switch mode for when we run initializers */
284 thread->status = THREAD_RUNNING;
287 * We need to assign the threadId early so we can lock/notify
288 * object monitors. We'll set the "threadObj" field later.
290 prepareThread(thread);
291 gDvm.threadList = thread;
293 #ifdef COUNT_PRECISE_METHODS
294 gDvm.preciseMethods = dvmPointerSetAlloc(200);
301 * We're a little farther up now, and can load some basic classes.
303 * We're far enough along that we can poke at java.lang.Thread and friends,
304 * but should not assume that static initializers have run (or cause them
305 * to do so). That means no object allocations yet.
307 bool dvmThreadObjStartup(void)
310 * Cache the locations of these classes. It's likely that we're the
311 * first to reference them, so they're being loaded now.
313 gDvm.classJavaLangThread =
314 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
315 gDvm.classJavaLangVMThread =
316 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
317 gDvm.classJavaLangThreadGroup =
318 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
319 if (gDvm.classJavaLangThread == NULL ||
320 gDvm.classJavaLangThreadGroup == NULL ||
321 gDvm.classJavaLangThreadGroup == NULL)
323 LOGE("Could not find one or more essential thread classes\n");
328 * Cache field offsets. This makes things a little faster, at the
329 * expense of hard-coding non-public field names into the VM.
331 gDvm.offJavaLangThread_vmThread =
332 dvmFindFieldOffset(gDvm.classJavaLangThread,
333 "vmThread", "Ljava/lang/VMThread;");
334 gDvm.offJavaLangThread_group =
335 dvmFindFieldOffset(gDvm.classJavaLangThread,
336 "group", "Ljava/lang/ThreadGroup;");
337 gDvm.offJavaLangThread_daemon =
338 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
339 gDvm.offJavaLangThread_name =
340 dvmFindFieldOffset(gDvm.classJavaLangThread,
341 "name", "Ljava/lang/String;");
342 gDvm.offJavaLangThread_priority =
343 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
345 if (gDvm.offJavaLangThread_vmThread < 0 ||
346 gDvm.offJavaLangThread_group < 0 ||
347 gDvm.offJavaLangThread_daemon < 0 ||
348 gDvm.offJavaLangThread_name < 0 ||
349 gDvm.offJavaLangThread_priority < 0)
351 LOGE("Unable to find all fields in java.lang.Thread\n");
355 gDvm.offJavaLangVMThread_thread =
356 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
357 "thread", "Ljava/lang/Thread;");
358 gDvm.offJavaLangVMThread_vmData =
359 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
360 if (gDvm.offJavaLangVMThread_thread < 0 ||
361 gDvm.offJavaLangVMThread_vmData < 0)
363 LOGE("Unable to find all fields in java.lang.VMThread\n");
368 * Cache the vtable offset for "run()".
370 * We don't want to keep the Method* because then we won't find see
371 * methods defined in subclasses.
374 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
376 LOGE("Unable to find run() in java.lang.Thread\n");
379 gDvm.voffJavaLangThread_run = meth->methodIndex;
382 * Cache vtable offsets for ThreadGroup methods.
384 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
385 "removeThread", "(Ljava/lang/Thread;)V");
387 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
390 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
396 * All threads should be stopped by now. Clean up some thread globals.
398 void dvmThreadShutdown(void)
400 if (gDvm.threadList != NULL) {
401 assert(gDvm.threadList->next == NULL);
402 assert(gDvm.threadList->prev == NULL);
403 freeThread(gDvm.threadList);
404 gDvm.threadList = NULL;
407 dvmFreeBitVector(gDvm.threadIdMap);
409 dvmFreeMonitorList();
411 pthread_key_delete(gDvm.pthreadKeySelf);
416 * Grab the suspend count global lock.
418 static inline void lockThreadSuspendCount(void)
421 * Don't try to change to VMWAIT here. When we change back to RUNNING
422 * we have to check for a pending suspend, which results in grabbing
423 * this lock recursively. Doesn't work with "fast" pthread mutexes.
425 * This lock is always held for very brief periods, so as long as
426 * mutex ordering is respected we shouldn't stall.
428 int cc = pthread_mutex_lock(&gDvm.threadSuspendCountLock);
433 * Release the suspend count global lock.
435 static inline void unlockThreadSuspendCount(void)
437 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
441 * Grab the thread list global lock.
443 * This is held while "suspend all" is trying to make everybody stop. If
444 * the shutdown is in progress, and somebody tries to grab the lock, they'll
445 * have to wait for the GC to finish. Therefore it's important that the
446 * thread not be in RUNNING mode.
448 * We don't have to check to see if we should be suspended once we have
449 * the lock. Nobody can suspend all threads without holding the thread list
450 * lock while they do it, so by definition there isn't a GC in progress.
452 void dvmLockThreadList(Thread* self)
454 ThreadStatus oldStatus;
456 if (self == NULL) /* try to get it from TLS */
457 self = dvmThreadSelf();
460 oldStatus = self->status;
461 self->status = THREAD_VMWAIT;
463 /* happens for JNI AttachCurrentThread [not anymore?] */
464 //LOGW("NULL self in dvmLockThreadList\n");
465 oldStatus = -1; // shut up gcc
468 int cc = pthread_mutex_lock(&gDvm.threadListLock);
472 self->status = oldStatus;
476 * Release the thread list global lock.
478 void dvmUnlockThreadList(void)
480 int cc = pthread_mutex_unlock(&gDvm.threadListLock);
486 * Grab the "thread suspend" lock. This is required to prevent the
487 * GC and the debugger from simultaneously suspending all threads.
489 * If we fail to get the lock, somebody else is trying to suspend all
490 * threads -- including us. If we go to sleep on the lock we'll deadlock
491 * the VM. Loop until we get it or somebody puts us to sleep.
493 static void lockThreadSuspend(const char* who, SuspendCause why)
495 const int kMaxRetries = 10;
496 const int kSpinSleepTime = 3*1000*1000; /* 3s */
497 u8 startWhen = 0; // init req'd to placate gcc
502 cc = pthread_mutex_trylock(&gDvm._threadSuspendLock);
504 if (!dvmCheckSuspendPending(NULL)) {
506 * Could be unusual JNI-attach thing, could be we hit
507 * the window as the suspend or resume was started. Could
508 * also be the debugger telling us to resume at roughly
509 * the same time we're posting an event.
511 LOGI("threadid=%d ODD: thread-suspend lock held (%s:%d)"
512 " but suspend not pending\n",
513 dvmThreadSelf()->threadId, who, why);
516 /* give the lock-holder a chance to do some work */
518 startWhen = dvmGetRelativeTimeUsec();
519 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
520 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%d),"
522 dvmThreadSelf()->threadId, who, why);
523 dvmDumpAllThreads(false);
532 * Release the "thread suspend" lock.
534 static inline void unlockThreadSuspend(void)
536 int cc = pthread_mutex_unlock(&gDvm._threadSuspendLock);
542 * Kill any daemon threads that still exist. All of ours should be
543 * stopped, so these should be Thread objects or JNI-attached threads
544 * started by the application. Actively-running threads are likely
545 * to crash the process if they continue to execute while the VM
546 * shuts down, so we really need to kill or suspend them. (If we want
547 * the VM to restart within this process, we need to kill them, but that
548 * leaves open the possibility of orphaned resources.)
550 * Waiting for the thread to suspend may be unwise at this point, but
551 * if one of these is wedged in a critical section then we probably
552 * would've locked up on the last GC attempt.
554 * It's possible for this function to get called after a failed
555 * initialization, so be careful with assumptions about the environment.
557 void dvmSlayDaemons(void)
559 Thread* self = dvmThreadSelf();
566 //dvmEnterCritical(self);
567 dvmLockThreadList(self);
569 target = gDvm.threadList;
570 while (target != NULL) {
571 if (target == self) {
572 target = target->next;
576 if (!dvmGetFieldBoolean(target->threadObj,
577 gDvm.offJavaLangThread_daemon))
579 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
580 self->threadId, target->threadId);
581 target = target->next;
585 LOGI("threadid=%d: killing leftover daemon threadid=%d [TODO]\n",
586 self->threadId, target->threadId);
587 // TODO: suspend and/or kill the thread
588 // (at the very least, we can "rescind their JNI privileges")
590 /* remove from list */
591 nextTarget = target->next;
592 unlinkThread(target);
598 dvmUnlockThreadList();
599 //dvmExitCritical(self);
604 * Finish preparing the parts of the Thread struct required to support
607 bool dvmPrepMainForJni(JNIEnv* pEnv)
611 /* main thread is always first in list at this point */
612 self = gDvm.threadList;
613 assert(self->threadId == kMainThreadId);
615 /* create a "fake" JNI frame at the top of the main thread interp stack */
616 if (!createFakeEntryFrame(self))
619 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
620 dvmSetJniEnvThreadId(pEnv, self);
621 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
628 * Finish preparing the main thread, allocating some objects to represent
629 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
631 bool dvmPrepMainThread(void)
637 StringObject* threadNameStr;
641 LOGV("+++ finishing prep on main VM thread\n");
643 /* main thread is always first in list at this point */
644 thread = gDvm.threadList;
645 assert(thread->threadId == kMainThreadId);
648 * Make sure the classes are initialized. We have to do this before
649 * we create an instance of them.
651 if (!dvmInitClass(gDvm.classJavaLangClass)) {
652 LOGE("'Class' class failed to initialize\n");
655 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
656 !dvmInitClass(gDvm.classJavaLangThread) ||
657 !dvmInitClass(gDvm.classJavaLangVMThread))
659 LOGE("thread classes failed to initialize\n");
663 groupObj = dvmGetMainThreadGroup();
664 if (groupObj == NULL)
668 * Allocate and construct a Thread with the internal-creation
671 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
672 if (threadObj == NULL) {
673 LOGE("unable to allocate main thread object\n");
676 dvmReleaseTrackedAlloc(threadObj, NULL);
678 threadNameStr = dvmCreateStringFromCstr("main", ALLOC_DEFAULT);
679 if (threadNameStr == NULL)
681 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
683 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
684 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
685 assert(init != NULL);
686 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
687 THREAD_NORM_PRIORITY, false);
688 if (dvmCheckException(thread)) {
689 LOGE("exception thrown while constructing main thread object\n");
694 * Allocate and construct a VMThread.
696 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
697 if (vmThreadObj == NULL) {
698 LOGE("unable to allocate main vmthread object\n");
701 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
703 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
704 "(Ljava/lang/Thread;)V");
705 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
706 if (dvmCheckException(thread)) {
707 LOGE("exception thrown while constructing main vmthread object\n");
711 /* set the VMThread.vmData field to our Thread struct */
712 assert(gDvm.offJavaLangVMThread_vmData != 0);
713 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
716 * Stuff the VMThread back into the Thread. From this point on, other
717 * Threads will see that this Thread is running.
719 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
722 thread->threadObj = threadObj;
725 * Finish our thread prep.
728 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
729 gDvm.nonDaemonThreadCount++;
736 * Alloc and initialize a Thread struct.
738 * "threadObj" is the java.lang.Thread object. It will be NULL for the
739 * main VM thread, but non-NULL for everything else.
741 * Does not create any objects, just stuff on the system (malloc) heap. (If
742 * this changes, we need to use ALLOC_NO_GC. And also verify that we're
743 * ready to load classes at the time this is called.)
745 static Thread* allocThread(int interpStackSize)
750 thread = (Thread*) calloc(1, sizeof(Thread));
754 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
756 thread->status = THREAD_INITIALIZING;
757 thread->suspendCount = 0;
759 #ifdef WITH_ALLOC_LIMITS
760 thread->allocLimit = -1;
764 * Allocate and initialize the interpreted code stack. We essentially
765 * "lose" the alloc pointer, which points at the bottom of the stack,
766 * but we can get it back later because we know how big the stack is.
768 * The stack must be aligned on a 4-byte boundary.
770 #ifdef MALLOC_INTERP_STACK
771 stackBottom = (u1*) malloc(interpStackSize);
772 if (stackBottom == NULL) {
776 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
778 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
779 MAP_PRIVATE | MAP_ANON, -1, 0);
780 if (stackBottom == MAP_FAILED) {
786 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
787 thread->interpStackSize = interpStackSize;
788 thread->interpStackStart = stackBottom + interpStackSize;
789 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
791 /* give the thread code a chance to set things up */
792 dvmInitInterpStack(thread, interpStackSize);
798 * Get a meaningful thread ID. At present this only has meaning under Linux,
799 * where getpid() and gettid() sometimes agree and sometimes don't depending
800 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
802 pid_t dvmGetSysThreadId(void)
812 * Finish initialization of a Thread struct.
814 * This must be called while executing in the new thread, but before the
815 * thread is added to the thread list.
817 * *** NOTE: The threadListLock must be held by the caller (needed for
820 static bool prepareThread(Thread* thread)
822 assignThreadId(thread);
823 thread->handle = pthread_self();
824 thread->systemTid = dvmGetSysThreadId();
826 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
828 setThreadSelf(thread);
830 LOGV("threadid=%d: interp stack at %p\n",
831 thread->threadId, thread->interpStackStart - thread->interpStackSize);
834 * Initialize invokeReq.
836 pthread_mutex_init(&thread->invokeReq.lock, NULL);
837 pthread_cond_init(&thread->invokeReq.cv, NULL);
840 * Initialize our reference tracking tables.
842 * The JNI local ref table *must* be fixed-size because we keep pointers
843 * into the table in our stack frames.
845 * Most threads won't use jniMonitorRefTable, so we clear out the
846 * structure but don't call the init function (which allocs storage).
848 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
849 kJniLocalRefMax, kJniLocalRefMax))
851 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
852 kInternalRefDefault, kInternalRefMax))
855 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
861 * Remove a thread from the internal list.
862 * Clear out the links to make it obvious that the thread is
863 * no longer on the list. Caller must hold gDvm.threadListLock.
865 static void unlinkThread(Thread* thread)
867 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
868 if (thread == gDvm.threadList) {
869 assert(thread->prev == NULL);
870 gDvm.threadList = thread->next;
872 assert(thread->prev != NULL);
873 thread->prev->next = thread->next;
875 if (thread->next != NULL)
876 thread->next->prev = thread->prev;
877 thread->prev = thread->next = NULL;
881 * Free a Thread struct, and all the stuff allocated within.
883 static void freeThread(Thread* thread)
888 /* thread->threadId is zero at this point */
889 LOGVV("threadid=%d: freeing\n", thread->threadId);
891 if (thread->interpStackStart != NULL) {
892 u1* interpStackBottom;
894 interpStackBottom = thread->interpStackStart;
895 interpStackBottom -= thread->interpStackSize;
896 #ifdef MALLOC_INTERP_STACK
897 free(interpStackBottom);
899 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
900 LOGW("munmap(thread stack) failed\n");
904 dvmClearReferenceTable(&thread->jniLocalRefTable);
905 dvmClearReferenceTable(&thread->internalLocalRefTable);
906 if (&thread->jniMonitorRefTable.table != NULL)
907 dvmClearReferenceTable(&thread->jniMonitorRefTable);
913 * Like pthread_self(), but on a Thread*.
915 Thread* dvmThreadSelf(void)
917 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
921 * Explore our sense of self. Stuffs the thread pointer into TLS.
923 static void setThreadSelf(Thread* thread)
927 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
930 * Sometimes this fails under Bionic with EINVAL during shutdown.
931 * This can happen if the timing is just right, e.g. a thread
932 * fails to attach during shutdown, but the "fail" path calls
933 * here to ensure we clean up after ourselves.
935 if (thread != NULL) {
936 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
937 dvmAbort(); /* the world is fundamentally hosed */
943 * This is associated with the pthreadKeySelf key. It's called by the
944 * pthread library when a thread is exiting and the "self" pointer in TLS
945 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
946 * operation this should never be called.
948 * This is mainly of use to ensure that we don't leak resources if, for
949 * example, a thread attaches itself to us with AttachCurrentThread and
950 * then exits without notifying the VM.
952 static void threadExitCheck(void* arg)
954 Thread* thread = (Thread*) arg;
956 LOGI("In threadExitCheck %p\n", arg);
957 assert(thread != NULL);
959 if (thread->status != THREAD_ZOMBIE) {
960 /* TODO: instead of failing, we could call dvmDetachCurrentThread() */
961 LOGE("Native thread exited without telling us\n");
968 * Assign the threadId. This needs to be a small integer so that our
969 * "thin" locks fit in a small number of bits.
971 * We reserve zero for use as an invalid ID.
973 * This must be called with threadListLock held (unless we're still
974 * initializing the system).
976 static void assignThreadId(Thread* thread)
978 /* Find a small unique integer. threadIdMap is a vector of
979 * kMaxThreadId bits; dvmAllocBit() returns the index of a
980 * bit, meaning that it will always be < kMaxThreadId.
982 * The thin locking magic requires that the low bit is always
983 * set, so we do it once, here.
985 int num = dvmAllocBit(gDvm.threadIdMap);
987 LOGE("Ran out of thread IDs\n");
988 dvmAbort(); // TODO: make this a non-fatal error result
991 thread->threadId = ((num + 1) << 1) | 1;
993 assert(thread->threadId != 0);
994 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
998 * Give back the thread ID.
1000 static void releaseThreadId(Thread* thread)
1002 assert(thread->threadId > 0);
1003 dvmClearBit(gDvm.threadIdMap, (thread->threadId >> 1) - 1);
1004 thread->threadId = 0;
1009 * Add a stack frame that makes it look like the native code in the main
1010 * thread was originally invoked from interpreted code. This gives us a
1011 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1012 * VM begins by executing "main" in a class, so in a way this brings us
1013 * closer to the spec.
1015 static bool createFakeEntryFrame(Thread* thread)
1017 assert(thread->threadId == kMainThreadId); // main thread only
1019 /* find the method on first use */
1020 if (gDvm.methFakeNativeEntry == NULL) {
1021 ClassObject* nativeStart;
1024 nativeStart = dvmFindSystemClassNoInit(
1025 "Ldalvik/system/NativeStart;");
1026 if (nativeStart == NULL) {
1027 LOGE("Unable to find dalvik.system.NativeStart class\n");
1032 * Because we are creating a frame that represents application code, we
1033 * want to stuff the application class loader into the method's class
1034 * loader field, even though we're using the system class loader to
1035 * load it. This makes life easier over in JNI FindClass (though it
1036 * could bite us in other ways).
1038 * Unfortunately this is occurring too early in the initialization,
1039 * of necessity coming before JNI is initialized, and we're not quite
1040 * ready to set up the application class loader.
1042 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1043 * and check it in FindClass. The method is private so nobody else
1046 //nativeStart->classLoader = dvmGetSystemClassLoader();
1048 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1049 "main", "([Ljava/lang/String;)V");
1050 if (mainMeth == NULL) {
1051 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1055 gDvm.methFakeNativeEntry = mainMeth;
1058 return dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry);
1063 * Add a stack frame that makes it look like the native thread has been
1064 * executing interpreted code. This gives us a place to hang JNI local
1067 static bool createFakeRunFrame(Thread* thread)
1069 ClassObject* nativeStart;
1072 assert(thread->threadId != 1); // not for main thread
1075 dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
1076 if (nativeStart == NULL) {
1077 LOGE("Unable to find dalvik.system.NativeStart class\n");
1081 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1082 if (runMeth == NULL) {
1083 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1087 return dvmPushJNIFrame(thread, runMeth);
1091 * Helper function to set the name of the current thread
1093 static void setThreadName(const char *threadName)
1095 #if defined(HAVE_PRCTL)
1098 const char *s = threadName;
1100 if (*s == '.') hasDot = 1;
1101 else if (*s == '@') hasAt = 1;
1104 int len = s - threadName;
1105 if (len < 15 || hasAt || !hasDot) {
1108 s = threadName + len - 15;
1110 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
1115 * Create a thread as a result of java.lang.Thread.start().
1117 * We do have to worry about some concurrency problems, e.g. programs
1118 * that try to call Thread.start() on the same object from multiple threads.
1119 * (This will fail for all but one, but we have to make sure that it succeeds
1122 * Some of the complexity here arises from our desire to mimic the
1123 * Thread vs. VMThread class decomposition we inherited. We've been given
1124 * a Thread, and now we need to create a VMThread and then populate both
1125 * objects. We also need to create one of our internal Thread objects.
1127 * Pass in a stack size of 0 to get the default.
1129 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1131 pthread_attr_t threadAttr;
1132 pthread_t threadHandle;
1134 Thread* newThread = NULL;
1135 Object* vmThreadObj = NULL;
1138 assert(threadObj != NULL);
1141 dvmThrowException("Ljava/lang/IllegalStateException;",
1142 "No new threads in -Xzygote mode");
1147 self = dvmThreadSelf();
1148 if (reqStackSize == 0)
1149 stackSize = gDvm.stackSize;
1150 else if (reqStackSize < kMinStackSize)
1151 stackSize = kMinStackSize;
1152 else if (reqStackSize > kMaxStackSize)
1153 stackSize = kMaxStackSize;
1155 stackSize = reqStackSize;
1157 pthread_attr_init(&threadAttr);
1158 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1161 * To minimize the time spent in the critical section, we allocate the
1162 * vmThread object here.
1164 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1165 if (vmThreadObj == NULL)
1168 newThread = allocThread(stackSize);
1169 if (newThread == NULL)
1171 newThread->threadObj = threadObj;
1173 assert(newThread->status == THREAD_INITIALIZING);
1176 * We need to lock out other threads while we test and set the
1177 * "vmThread" field in java.lang.Thread, because we use that to determine
1178 * if this thread has been started before. We use the thread list lock
1179 * because it's handy and we're going to need to grab it again soon
1182 dvmLockThreadList(self);
1184 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1185 dvmUnlockThreadList();
1186 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1187 "thread has already been started");
1192 * There are actually three data structures: Thread (object), VMThread
1193 * (object), and Thread (C struct). All of them point to at least one
1196 * As soon as "VMThread.vmData" is assigned, other threads can start
1197 * making calls into us (e.g. setPriority).
1199 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1200 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1203 * Thread creation might take a while, so release the lock.
1205 dvmUnlockThreadList();
1207 if (pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1211 * Failure generally indicates that we have exceeded system
1212 * resource limits. VirtualMachineError is probably too severe,
1213 * so use OutOfMemoryError.
1215 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1217 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1219 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1220 "thread creation failed");
1225 * We need to wait for the thread to start. Otherwise, depending on
1226 * the whims of the OS scheduler, we could return and the code in our
1227 * thread could try to do operations on the new thread before it had
1228 * finished starting.
1230 * The new thread will lock the thread list, change its state to
1231 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1232 * on gDvm.threadStartCond (which uses the thread list lock). This
1233 * thread (the parent) will either see that the thread is already ready
1234 * after we grab the thread list lock, or will be awakened from the
1235 * condition variable on the broadcast.
1237 * We don't want to stall the rest of the VM while the new thread
1238 * starts, which can happen if the GC wakes up at the wrong moment.
1239 * So, we change our own status to VMWAIT, and self-suspend if
1240 * necessary after we finish adding the new thread.
1243 * We have to deal with an odd race with the GC/debugger suspension
1244 * mechanism when creating a new thread. The information about whether
1245 * or not a thread should be suspended is contained entirely within
1246 * the Thread struct; this is usually cleaner to deal with than having
1247 * one or more globally-visible suspension flags. The trouble is that
1248 * we could create the thread while the VM is trying to suspend all
1249 * threads. The suspend-count won't be nonzero for the new thread,
1250 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1252 * The easiest way to deal with this is to prevent the new thread from
1253 * running until the parent says it's okay. This results in the
1254 * following sequence of events for a "badly timed" GC:
1256 * - call pthread_create()
1257 * - lock thread list
1258 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1259 * - sleep on condition var (mutex = thread list lock) until child starts
1260 * + GC triggered by another thread
1261 * + thread list locked; suspend counts updated; thread list unlocked
1262 * + loop waiting for all runnable threads to suspend
1263 * + success, start GC
1264 * o child thread wakes, signals condition var to wake parent
1265 * o child waits for parent ack on condition variable
1266 * - we wake up, locking thread list
1267 * - add child to thread list
1268 * - unlock thread list
1269 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1270 * + GC finishes; all threads in thread list are resumed
1271 * - lock thread list
1272 * - set child to THREAD_VMWAIT, and signal it to start
1273 * - unlock thread list
1275 * o child changes state to THREAD_RUNNING
1277 * The above shows the GC starting up during thread creation, but if
1278 * it starts anywhere after VMThread.create() is called it will
1279 * produce the same series of events.
1281 * Once the child is in the thread list, it will be suspended and
1282 * resumed like any other thread. In the above scenario the resume-all
1283 * code will try to resume the new thread, which was never actually
1284 * suspended, and try to decrement the child's thread suspend count to -1.
1285 * We can catch this in the resume-all code.
1287 * Bouncing back and forth between threads like this adds a small amount
1288 * of scheduler overhead to thread startup.
1290 * One alternative to having the child wait for the parent would be
1291 * to have the child inherit the parents' suspension count. This
1292 * would work for a GC, since we can safely assume that the parent
1293 * thread didn't cause it, but we must only do so if the parent suspension
1294 * was caused by a suspend-all. If the parent was being asked to
1295 * suspend singly by the debugger, the child should not inherit the value.
1297 * We could also have a global "new thread suspend count" that gets
1298 * picked up by new threads before changing state to THREAD_RUNNING.
1299 * This would be protected by the thread list lock and set by a
1302 dvmLockThreadList(self);
1303 assert(self->status == THREAD_RUNNING);
1304 self->status = THREAD_VMWAIT;
1305 while (newThread->status != THREAD_STARTING)
1306 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1308 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1309 newThread->next = gDvm.threadList->next;
1310 if (newThread->next != NULL)
1311 newThread->next->prev = newThread;
1312 newThread->prev = gDvm.threadList;
1313 gDvm.threadList->next = newThread;
1315 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1316 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1318 dvmUnlockThreadList();
1320 /* change status back to RUNNING, self-suspending if necessary */
1321 dvmChangeStatus(self, THREAD_RUNNING);
1324 * Tell the new thread to start.
1326 * We must hold the thread list lock before messing with another thread.
1327 * In the general case we would also need to verify that newThread was
1328 * still in the thread list, but in our case the thread has not started
1329 * executing user code and therefore has not had a chance to exit.
1331 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1332 * comes with a suspend-pending check.
1334 dvmLockThreadList(self);
1336 assert(newThread->status == THREAD_STARTING);
1337 newThread->status = THREAD_VMWAIT;
1338 pthread_cond_broadcast(&gDvm.threadStartCond);
1340 dvmUnlockThreadList();
1342 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1346 freeThread(newThread);
1347 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1352 * pthread entry function for threads started from interpreted code.
1354 static void* interpThreadStart(void* arg)
1356 Thread* self = (Thread*) arg;
1358 char *threadName = dvmGetThreadName(self);
1359 setThreadName(threadName);
1363 * Finish initializing the Thread struct.
1365 prepareThread(self);
1367 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1370 * Change our status and wake our parent, who will add us to the
1371 * thread list and advance our state to VMWAIT.
1373 dvmLockThreadList(self);
1374 self->status = THREAD_STARTING;
1375 pthread_cond_broadcast(&gDvm.threadStartCond);
1378 * Wait until the parent says we can go. Assuming there wasn't a
1379 * suspend pending, this will happen immediately. When it completes,
1380 * we're full-fledged citizens of the VM.
1382 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1383 * because the pthread_cond_wait below needs to reacquire a lock that
1384 * suspend-all is also interested in. If we get unlucky, the parent could
1385 * change us to THREAD_RUNNING, then a GC could start before we get
1386 * signaled, and suspend-all will grab the thread list lock and then
1387 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1388 * trying to get the lock.
1390 while (self->status != THREAD_VMWAIT)
1391 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1393 dvmUnlockThreadList();
1396 * Add a JNI context.
1398 self->jniEnv = dvmCreateJNIEnv(self);
1401 * Change our state so the GC will wait for us from now on. If a GC is
1402 * in progress this call will suspend us.
1404 dvmChangeStatus(self, THREAD_RUNNING);
1407 * Notify the debugger & DDM. The debugger notification may cause
1408 * us to suspend ourselves (and others).
1410 if (gDvm.debuggerConnected)
1411 dvmDbgPostThreadStart(self);
1414 * Set the system thread priority according to the Thread object's
1415 * priority level. We don't usually need to do this, because both the
1416 * Thread object and system thread priorities inherit from parents. The
1417 * tricky case is when somebody creates a Thread object, calls
1418 * setPriority(), and then starts the thread. We could manage this with
1419 * a "needs priority update" flag to avoid the redundant call.
1421 int priority = dvmGetFieldBoolean(self->threadObj,
1422 gDvm.offJavaLangThread_priority);
1423 dvmChangeThreadPriority(self, priority);
1426 * Execute the "run" method.
1428 * At this point our stack is empty, so somebody who comes looking for
1429 * stack traces right now won't have much to look at. This is normal.
1431 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1434 LOGV("threadid=%d: calling run()\n", self->threadId);
1435 assert(strcmp(run->name, "run") == 0);
1436 dvmCallMethod(self, run, self->threadObj, &unused);
1437 LOGV("threadid=%d: exiting\n", self->threadId);
1440 * Remove the thread from various lists, report its death, and free
1443 dvmDetachCurrentThread();
1449 * The current thread is exiting with an uncaught exception. The
1450 * Java programming language allows the application to provide a
1451 * thread-exit-uncaught-exception handler for the VM, for a specific
1452 * Thread, and for all threads in a ThreadGroup.
1454 * Version 1.5 added the per-thread handler. We need to call
1455 * "uncaughtException" in the handler object, which is either the
1456 * ThreadGroup object or the Thread-specific handler.
1458 static void threadExitUncaughtException(Thread* self, Object* group)
1462 ClassObject* throwable;
1463 Method* uncaughtHandler = NULL;
1464 InstField* threadHandler;
1466 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1467 self->threadId, group);
1468 assert(group != NULL);
1471 * Get a pointer to the exception, then clear out the one in the
1472 * thread. We don't want to have it set when executing interpreted code.
1474 exception = dvmGetException(self);
1475 dvmAddTrackedAlloc(exception, self);
1476 dvmClearException(self);
1479 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1480 * else use "group" (which is an instance of UncaughtExceptionHandler).
1482 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1483 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1484 if (threadHandler == NULL) {
1485 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1488 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1489 if (handlerObj == NULL)
1493 * Find the "uncaughtHandler" field in this object.
1495 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1496 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1498 if (uncaughtHandler != NULL) {
1499 //LOGI("+++ calling %s.uncaughtException\n",
1500 // handlerObj->clazz->descriptor);
1502 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1503 self->threadObj, exception);
1505 /* restore it and dump a stack trace */
1506 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1507 handlerObj->clazz->descriptor);
1508 dvmSetException(self, exception);
1509 dvmLogExceptionStackTrace();
1513 dvmReleaseTrackedAlloc(exception, self);
1518 * Create an internal VM thread, for things like JDWP and finalizers.
1520 * The easiest way to do this is create a new thread and then use the
1521 * JNI AttachCurrentThread implementation.
1523 * This does not return until after the new thread has begun executing.
1525 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1526 InternalThreadStart func, void* funcArg)
1528 InternalStartArgs* pArgs;
1529 Object* systemGroup;
1530 pthread_attr_t threadAttr;
1531 volatile Thread* newThread = NULL;
1532 volatile int createStatus = 0;
1534 systemGroup = dvmGetSystemThreadGroup();
1535 if (systemGroup == NULL)
1538 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1540 pArgs->funcArg = funcArg;
1541 pArgs->name = strdup(name); // storage will be owned by new thread
1542 pArgs->group = systemGroup;
1543 pArgs->isDaemon = true;
1544 pArgs->pThread = &newThread;
1545 pArgs->pCreateStatus = &createStatus;
1547 pthread_attr_init(&threadAttr);
1548 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1550 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1553 LOGE("internal thread creation failed\n");
1560 * Wait for the child to start. This gives us an opportunity to make
1561 * sure that the thread started correctly, and allows our caller to
1562 * assume that the thread has started running.
1564 * Because we aren't holding a lock across the thread creation, it's
1565 * possible that the child will already have completed its
1566 * initialization. Because the child only adjusts "createStatus" while
1567 * holding the thread list lock, the initial condition on the "while"
1568 * loop will correctly avoid the wait if this occurs.
1570 * It's also possible that we'll have to wait for the thread to finish
1571 * being created, and as part of allocating a Thread object it might
1572 * need to initiate a GC. We switch to VMWAIT while we pause.
1574 Thread* self = dvmThreadSelf();
1575 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1576 dvmLockThreadList(self);
1577 while (createStatus == 0)
1578 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1580 if (newThread == NULL) {
1581 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1582 assert(createStatus < 0);
1583 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1584 dvmUnlockThreadList();
1585 dvmChangeStatus(self, oldStatus);
1589 /* thread could be in any state now (except early init states) */
1590 //assert(newThread->status == THREAD_RUNNING);
1592 dvmUnlockThreadList();
1593 dvmChangeStatus(self, oldStatus);
1599 * pthread entry function for internally-created threads.
1601 * We are expected to free "arg" and its contents. If we're a daemon
1602 * thread, and we get cancelled abruptly when the VM shuts down, the
1603 * storage won't be freed. If this becomes a concern we can make a copy
1606 static void* internalThreadStart(void* arg)
1608 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1609 JavaVMAttachArgs jniArgs;
1611 jniArgs.version = JNI_VERSION_1_2;
1612 jniArgs.name = pArgs->name;
1613 jniArgs.group = pArgs->group;
1615 setThreadName(pArgs->name);
1617 /* use local jniArgs as stack top */
1618 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1620 * Tell the parent of our success.
1622 * threadListLock is the mutex for threadStartCond.
1624 dvmLockThreadList(dvmThreadSelf());
1625 *pArgs->pCreateStatus = 1;
1626 *pArgs->pThread = dvmThreadSelf();
1627 pthread_cond_broadcast(&gDvm.threadStartCond);
1628 dvmUnlockThreadList();
1630 LOG_THREAD("threadid=%d: internal '%s'\n",
1631 dvmThreadSelf()->threadId, pArgs->name);
1634 (*pArgs->func)(pArgs->funcArg);
1636 /* detach ourselves */
1637 dvmDetachCurrentThread();
1640 * Tell the parent of our failure. We don't have a Thread struct,
1641 * so we can't be suspended, so we don't need to enter a critical
1644 dvmLockThreadList(dvmThreadSelf());
1645 *pArgs->pCreateStatus = -1;
1646 assert(*pArgs->pThread == NULL);
1647 pthread_cond_broadcast(&gDvm.threadStartCond);
1648 dvmUnlockThreadList();
1650 assert(*pArgs->pThread == NULL);
1659 * Attach the current thread to the VM.
1661 * Used for internally-created threads and JNI's AttachCurrentThread.
1663 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1665 Thread* self = NULL;
1666 Object* threadObj = NULL;
1667 Object* vmThreadObj = NULL;
1668 StringObject* threadNameStr = NULL;
1672 /* establish a basic sense of self */
1673 self = allocThread(gDvm.stackSize);
1676 setThreadSelf(self);
1679 * Create Thread and VMThread objects. We have to use ALLOC_NO_GC
1680 * because this thread is not yet visible to the VM. We could also
1681 * just grab the GC lock earlier, but that leaves us executing
1682 * interpreted code with the lock held, which is not prudent.
1684 * The alloc calls will block if a GC is in progress, so we don't need
1685 * to check for global suspension here.
1687 * It's also possible for the allocation calls to *cause* a GC.
1689 //BUG: deadlock if a GC happens here during HeapWorker creation
1690 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_NO_GC);
1691 if (threadObj == NULL)
1693 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_NO_GC);
1694 if (vmThreadObj == NULL)
1697 self->threadObj = threadObj;
1698 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1701 * Do some java.lang.Thread constructor prep before we lock stuff down.
1703 if (pArgs->name != NULL) {
1704 threadNameStr = dvmCreateStringFromCstr(pArgs->name, ALLOC_NO_GC);
1705 if (threadNameStr == NULL) {
1706 assert(dvmCheckException(dvmThreadSelf()));
1711 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1712 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1714 assert(dvmCheckException(dvmThreadSelf()));
1719 * Finish our thread prep. We need to do this before invoking any
1720 * interpreted code. prepareThread() requires that we hold the thread
1723 dvmLockThreadList(self);
1724 ok = prepareThread(self);
1725 dvmUnlockThreadList();
1729 self->jniEnv = dvmCreateJNIEnv(self);
1730 if (self->jniEnv == NULL)
1734 * Create a "fake" JNI frame at the top of the main thread interp stack.
1735 * It isn't really necessary for the internal threads, but it gives
1736 * the debugger something to show. It is essential for the JNI-attached
1739 if (!createFakeRunFrame(self))
1743 * The native side of the thread is ready; add it to the list.
1745 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1747 /* Start off in VMWAIT, because we may be about to block
1748 * on the heap lock, and we don't want any suspensions
1751 self->status = THREAD_VMWAIT;
1754 * Add ourselves to the thread list. Once we finish here we are
1755 * visible to the debugger and the GC.
1757 dvmLockThreadList(self);
1759 self->next = gDvm.threadList->next;
1760 if (self->next != NULL)
1761 self->next->prev = self;
1762 self->prev = gDvm.threadList;
1763 gDvm.threadList->next = self;
1765 gDvm.nonDaemonThreadCount++;
1767 dvmUnlockThreadList();
1770 * It's possible that a GC is currently running. Our thread
1771 * wasn't in the list when the GC started, so it's not properly
1772 * suspended in that case. Synchronize on the heap lock (held
1773 * when a GC is happening) to guarantee that any GCs from here
1774 * on will see this thread in the list.
1776 dvmLockMutex(&gDvm.gcHeapLock);
1777 dvmUnlockMutex(&gDvm.gcHeapLock);
1780 * Switch to the running state now that we're ready for
1781 * suspensions. This call may suspend.
1783 dvmChangeStatus(self, THREAD_RUNNING);
1786 * Now we're ready to run some interpreted code.
1788 * We need to construct the Thread object and set the VMThread field.
1789 * Setting VMThread tells interpreted code that we're alive.
1791 * Call the (group, name, priority, daemon) constructor on the Thread.
1792 * This sets the thread's name and adds it to the specified group, and
1793 * provides values for priority and daemon (which are normally inherited
1794 * from the current thread).
1797 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
1798 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
1799 if (dvmCheckException(self)) {
1800 LOGE("exception thrown while constructing attached thread object\n");
1804 // dvmSetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon, true);
1807 * Set the VMThread field, which tells interpreted code that we're alive.
1809 * The risk of a thread start collision here is very low; somebody
1810 * would have to be deliberately polling the ThreadGroup list and
1811 * trying to start threads against anything it sees, which would
1812 * generally cause problems for all thread creation. However, for
1813 * correctness we test "vmThread" before setting it.
1815 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1816 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1817 "thread has already been started");
1818 /* We don't want to free anything associated with the thread
1819 * because someone is obviously interested in it. Just let
1820 * it go and hope it will clean itself up when its finished.
1821 * This case should never happen anyway.
1823 * Since we're letting it live, we need to finish setting it up.
1824 * We just have to let the caller know that the intended operation
1827 * [ This seems strange -- stepping on the vmThread object that's
1828 * already present seems like a bad idea. TODO: figure this out. ]
1833 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1835 /* These are now reachable from the thread groups. */
1836 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
1837 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
1840 * The thread is ready to go; let the debugger see it.
1842 self->threadObj = threadObj;
1844 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
1845 self->threadId, pArgs->name);
1847 /* tell the debugger & DDM */
1848 if (gDvm.debuggerConnected)
1849 dvmDbgPostThreadStart(self);
1854 dvmLockThreadList(self);
1857 gDvm.nonDaemonThreadCount--;
1858 dvmUnlockThreadList();
1859 /* fall through to "fail" */
1861 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
1862 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
1864 if (self->jniEnv != NULL) {
1865 dvmDestroyJNIEnv(self->jniEnv);
1866 self->jniEnv = NULL;
1870 setThreadSelf(NULL);
1875 * Detach the thread from the various data structures, notify other threads
1876 * that are waiting to "join" it, and free up all heap-allocated storage.
1878 * Used for all threads.
1880 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
1881 * requires us to enforce this for the DetachCurrentThread call, probably
1882 * because it also says that DetachCurrentThread causes all monitors
1883 * associated with the thread to be released. (Because the stack is empty,
1884 * we only have to worry about explicit JNI calls to MonitorEnter.)
1887 * We might want to avoid freeing our internal Thread structure until the
1888 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
1889 * get to once the thread shuts down, but there is a small possibility of
1890 * an operation starting in another thread before this thread halts, and
1891 * finishing much later (perhaps the thread got stalled by a weird OS bug).
1892 * We don't want something like Thread.isInterrupted() crawling through
1893 * freed storage. Can do with a Thread finalizer, or by creating a
1894 * dedicated ThreadObject class for java/lang/Thread and moving all of our
1897 void dvmDetachCurrentThread(void)
1899 Thread* self = dvmThreadSelf();
1904 * Make sure we're not detaching a thread that's still running. (This
1905 * could happen with an explicit JNI detach call.)
1907 * A thread created by interpreted code will finish with a depth of
1908 * zero, while a JNI-attached thread will have the synthetic "stack
1909 * starter" native method at the top.
1911 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
1912 if (curDepth != 0) {
1913 bool topIsNative = false;
1915 if (curDepth == 1) {
1916 /* not expecting a lingering break frame; just look at curFrame */
1917 assert(!dvmIsBreakFrame(self->curFrame));
1918 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
1919 if (dvmIsNativeMethod(ssa->method))
1924 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
1926 dvmDumpThread(self, false);
1931 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
1932 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
1935 * Release any held monitors. Since there are no interpreted stack
1936 * frames, the only thing left are the monitors held by JNI MonitorEnter
1939 dvmReleaseJniMonitors(self);
1942 * Do some thread-exit uncaught exception processing if necessary.
1944 if (dvmCheckException(self))
1945 threadExitUncaughtException(self, group);
1948 * Remove the thread from the thread group.
1950 if (group != NULL) {
1951 Method* removeThread =
1952 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
1954 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
1958 * Clear the vmThread reference in the Thread object. Interpreted code
1959 * will now see that this Thread is not running. As this may be the
1960 * only reference to the VMThread object that the VM knows about, we
1961 * have to create an internal reference to it first.
1963 vmThread = dvmGetFieldObject(self->threadObj,
1964 gDvm.offJavaLangThread_vmThread);
1965 dvmAddTrackedAlloc(vmThread, self);
1966 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1968 /* clear out our struct Thread pointer, since it's going away */
1969 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
1972 * Tell the debugger & DDM. This may cause the current thread or all
1973 * threads to suspend.
1975 * The JDWP spec is somewhat vague about when this happens, other than
1976 * that it's issued by the dying thread, which may still appear in
1977 * an "all threads" listing.
1979 if (gDvm.debuggerConnected)
1980 dvmDbgPostThreadDeath(self);
1983 * Thread.join() is implemented as an Object.wait() on the VMThread
1984 * object. Signal anyone who is waiting.
1986 dvmLockObject(self, vmThread);
1987 dvmObjectNotifyAll(self, vmThread);
1988 dvmUnlockObject(self, vmThread);
1990 dvmReleaseTrackedAlloc(vmThread, self);
1994 * We're done manipulating objects, so it's okay if the GC runs in
1995 * parallel with us from here out. It's important to do this if
1996 * profiling is enabled, since we can wait indefinitely.
1998 self->status = THREAD_VMWAIT;
2000 #ifdef WITH_PROFILER
2002 * If we're doing method trace profiling, we don't want threads to exit,
2003 * because if they do we'll end up reusing thread IDs. This complicates
2004 * analysis and makes it impossible to have reasonable output in the
2005 * "threads" section of the "key" file.
2007 * We need to do this after Thread.join() completes, or other threads
2008 * could get wedged. Since self->threadObj is still valid, the Thread
2009 * object will not get GCed even though we're no longer in the ThreadGroup
2010 * list (which is important since the profiling thread needs to get
2011 * the thread's name).
2013 MethodTraceState* traceState = &gDvm.methodTrace;
2015 dvmLockMutex(&traceState->startStopLock);
2016 if (traceState->traceEnabled) {
2017 LOGI("threadid=%d: waiting for method trace to finish\n",
2019 while (traceState->traceEnabled) {
2021 cc = pthread_cond_wait(&traceState->threadExitCond,
2022 &traceState->startStopLock);
2026 dvmUnlockMutex(&traceState->startStopLock);
2029 dvmLockThreadList(self);
2032 * Lose the JNI context.
2034 dvmDestroyJNIEnv(self->jniEnv);
2035 self->jniEnv = NULL;
2037 self->status = THREAD_ZOMBIE;
2040 * Remove ourselves from the internal thread list.
2045 * If we're the last one standing, signal anybody waiting in
2046 * DestroyJavaVM that it's okay to exit.
2048 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2049 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2051 if (gDvm.nonDaemonThreadCount == 0) {
2054 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2055 //dvmDumpAllThreads(false);
2056 // cond var guarded by threadListLock, which we already hold
2057 cc = pthread_cond_signal(&gDvm.vmExitCond);
2062 LOGV("threadid=%d: bye!\n", self->threadId);
2063 releaseThreadId(self);
2064 dvmUnlockThreadList();
2066 setThreadSelf(NULL);
2072 * Suspend a single thread. Do not use to suspend yourself.
2074 * This is used primarily for debugger/DDMS activity. Does not return
2075 * until the thread has suspended or is in a "safe" state (e.g. executing
2076 * native code outside the VM).
2078 * The thread list lock should be held before calling here -- it's not
2079 * entirely safe to hang on to a Thread* from another thread otherwise.
2080 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2082 void dvmSuspendThread(Thread* thread)
2084 assert(thread != NULL);
2085 assert(thread != dvmThreadSelf());
2086 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2088 lockThreadSuspendCount();
2089 thread->suspendCount++;
2090 thread->dbgSuspendCount++;
2092 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2093 thread->threadId, thread->suspendCount);
2094 unlockThreadSuspendCount();
2096 waitForThreadSuspend(dvmThreadSelf(), thread);
2100 * Reduce the suspend count of a thread. If it hits zero, tell it to
2103 * Used primarily for debugger/DDMS activity. The thread in question
2104 * might have been suspended singly or as part of a suspend-all operation.
2106 * The thread list lock should be held before calling here -- it's not
2107 * entirely safe to hang on to a Thread* from another thread otherwise.
2108 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2110 void dvmResumeThread(Thread* thread)
2112 assert(thread != NULL);
2113 assert(thread != dvmThreadSelf());
2114 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2116 lockThreadSuspendCount();
2117 if (thread->suspendCount > 0) {
2118 thread->suspendCount--;
2119 thread->dbgSuspendCount--;
2121 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2125 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2126 thread->threadId, thread->suspendCount);
2128 if (thread->suspendCount == 0) {
2129 int cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2133 unlockThreadSuspendCount();
2137 * Suspend yourself, as a result of debugger activity.
2139 void dvmSuspendSelf(bool jdwpActivity)
2141 Thread* self = dvmThreadSelf();
2143 /* debugger thread may not suspend itself due to debugger activity! */
2144 assert(gDvm.jdwpState != NULL);
2145 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2151 * Collisions with other suspends aren't really interesting. We want
2152 * to ensure that we're the only one fiddling with the suspend count
2155 lockThreadSuspendCount();
2156 self->suspendCount++;
2157 self->dbgSuspendCount++;
2160 * Suspend ourselves.
2162 assert(self->suspendCount > 0);
2163 self->isSuspended = true;
2164 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2167 * Tell JDWP that we've completed suspension. The JDWP thread can't
2168 * tell us to resume before we're fully asleep because we hold the
2169 * suspend count lock.
2171 * If we got here via waitForDebugger(), don't do this part.
2174 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2175 // self->threadId, (int) self->handle);
2176 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2179 while (self->suspendCount != 0) {
2181 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
2182 &gDvm.threadSuspendCountLock);
2184 if (self->suspendCount != 0) {
2185 LOGD("threadid=%d: still suspended after undo (s=%d d=%d)\n",
2186 self->threadId, self->suspendCount, self->dbgSuspendCount);
2189 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2190 self->isSuspended = false;
2191 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2192 self->threadId, self->status);
2194 unlockThreadSuspendCount();
2199 # define NUM_FRAMES 20
2200 # include <execinfo.h>
2202 * glibc-only stack dump function. Requires link with "--export-dynamic".
2204 * TODO: move this into libs/cutils and make it work for all platforms.
2206 static void printBackTrace(void)
2208 void* array[NUM_FRAMES];
2213 size = backtrace(array, NUM_FRAMES);
2214 strings = backtrace_symbols(array, size);
2216 LOGW("Obtained %zd stack frames.\n", size);
2218 for (i = 0; i < size; i++)
2219 LOGW("%s\n", strings[i]);
2224 static void printBackTrace(void) {}
2228 * Dump the state of the current thread and that of another thread that
2229 * we think is wedged.
2231 static void dumpWedgedThread(Thread* thread)
2236 * The "executablepath" function in libutils is host-side only.
2238 strcpy(exePath, "-");
2242 sprintf(proc, "/proc/%d/exe", getpid());
2245 len = readlink(proc, exePath, sizeof(exePath)-1);
2246 exePath[len] = '\0';
2250 LOGW("dumping state: process %s %d\n", exePath, getpid());
2251 dvmDumpThread(dvmThreadSelf(), false);
2254 // dumping a running thread is risky, but could be useful
2255 dvmDumpThread(thread, true);
2258 // stop now and get a core dump
2264 * Wait for another thread to see the pending suspension and stop running.
2265 * It can either suspend itself or go into a non-running state such as
2266 * VMWAIT or NATIVE in which it cannot interact with the GC.
2268 * If we're running at a higher priority, sched_yield() may not do anything,
2269 * so we need to sleep for "long enough" to guarantee that the other
2270 * thread has a chance to finish what it's doing. Sleeping for too short
2271 * a period (e.g. less than the resolution of the sleep clock) might cause
2272 * the scheduler to return immediately, so we want to start with a
2273 * "reasonable" value and expand.
2275 * This does not return until the other thread has stopped running.
2276 * Eventually we time out and the VM aborts.
2278 * This does not try to detect the situation where two threads are
2279 * waiting for each other to suspend. In normal use this is part of a
2280 * suspend-all, which implies that the suspend-all lock is held, or as
2281 * part of a debugger action in which the JDWP thread is always the one
2282 * doing the suspending. (We may need to re-evaluate this now that
2283 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2285 * TODO: track basic stats about time required to suspend VM.
2287 static void waitForThreadSuspend(Thread* self, Thread* thread)
2289 const int kMaxRetries = 10;
2290 const int kSpinSleepTime = 750*1000; /* 0.75s */
2294 u8 startWhen = 0; // init req'd to placate gcc
2296 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
2297 if (sleepIter == 0) // get current time on first iteration
2298 startWhen = dvmGetRelativeTimeUsec();
2300 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
2301 LOGW("threadid=%d (h=%d): spin on suspend threadid=%d (handle=%d)\n",
2302 self->threadId, (int)self->handle,
2303 thread->threadId, (int)thread->handle);
2304 dumpWedgedThread(thread);
2306 // keep going; could be slow due to valgrind
2309 if (retryCount++ == kMaxRetries) {
2310 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2311 self->threadId, thread->threadId);
2312 dvmDumpAllThreads(false);
2320 * Suspend all threads except the current one. This is used by the GC,
2321 * the debugger, and by any thread that hits a "suspend all threads"
2322 * debugger event (e.g. breakpoint or exception).
2324 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2325 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2326 * create objects and even execute arbitrary code. The "why" argument
2327 * allows the caller to say why the suspension is taking place.
2329 * This can be called when a global suspend has already happened, due to
2330 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2333 * DO NOT grab any locks before calling here. We grab & release the thread
2334 * lock and suspend lock here (and we're not using recursive threads), and
2335 * we might have to self-suspend if somebody else beats us here.
2337 * The current thread may not be attached to the VM. This can happen if
2338 * we happen to GC as the result of an allocation of a Thread object.
2340 void dvmSuspendAllThreads(SuspendCause why)
2342 Thread* self = dvmThreadSelf();
2348 * Start by grabbing the thread suspend lock. If we can't get it, most
2349 * likely somebody else is in the process of performing a suspend or
2350 * resume, so lockThreadSuspend() will cause us to self-suspend.
2352 * We keep the lock until all other threads are suspended.
2354 lockThreadSuspend("susp-all", why);
2356 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2359 * This is possible if the current thread was in VMWAIT mode when a
2360 * suspend-all happened, and then decided to do its own suspend-all.
2361 * This can happen when a couple of threads have simultaneous events
2362 * of interest to the debugger.
2364 //assert(self->suspendCount == 0);
2367 * Increment everybody's suspend count (except our own).
2369 dvmLockThreadList(self);
2371 lockThreadSuspendCount();
2372 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2376 /* debugger events don't suspend JDWP thread */
2377 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2378 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2381 thread->suspendCount++;
2382 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2383 thread->dbgSuspendCount++;
2385 unlockThreadSuspendCount();
2388 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2389 * indicate the code is either running natively or sleeping quietly.
2390 * Any attempt to transition back to THREAD_RUNNING will cause a check
2391 * for suspension, so it should be impossible for anything to execute
2392 * interpreted code or modify objects (assuming native code plays nicely).
2394 * It's also okay if the thread transitions to a non-RUNNING state.
2396 * Note we released the threadSuspendCountLock before getting here,
2397 * so if another thread is fiddling with its suspend count (perhaps
2398 * self-suspending for the debugger) it won't block while we're waiting
2401 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2405 /* debugger events don't suspend JDWP thread */
2406 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2407 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2410 /* wait for the other thread to see the pending suspend */
2411 waitForThreadSuspend(self, thread);
2413 LOG_THREAD("threadid=%d: threadid=%d status=%d c=%d dc=%d isSusp=%d\n",
2415 thread->threadId, thread->status, thread->suspendCount,
2416 thread->dbgSuspendCount, thread->isSuspended);
2419 dvmUnlockThreadList();
2420 unlockThreadSuspend();
2422 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2426 * Resume all threads that are currently suspended.
2428 * The "why" must match with the previous suspend.
2430 void dvmResumeAllThreads(SuspendCause why)
2432 Thread* self = dvmThreadSelf();
2436 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2437 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2440 * Decrement the suspend counts for all threads. No need for atomic
2441 * writes, since nobody should be moving until we decrement the count.
2442 * We do need to hold the thread list because of JNI attaches.
2444 dvmLockThreadList(self);
2445 lockThreadSuspendCount();
2446 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2450 /* debugger events don't suspend JDWP thread */
2451 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2452 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2455 if (thread->suspendCount > 0) {
2456 thread->suspendCount--;
2457 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2458 thread->dbgSuspendCount--;
2460 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2464 unlockThreadSuspendCount();
2465 dvmUnlockThreadList();
2468 * Broadcast a notification to all suspended threads, some or all of
2469 * which may choose to wake up. No need to wait for them.
2471 lockThreadSuspendCount();
2472 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2474 unlockThreadSuspendCount();
2476 unlockThreadSuspend();
2478 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2482 * Undo any debugger suspensions. This is called when the debugger
2485 void dvmUndoDebuggerSuspensions(void)
2487 Thread* self = dvmThreadSelf();
2491 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2492 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2495 * Decrement the suspend counts for all threads. No need for atomic
2496 * writes, since nobody should be moving until we decrement the count.
2497 * We do need to hold the thread list because of JNI attaches.
2499 dvmLockThreadList(self);
2500 lockThreadSuspendCount();
2501 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2505 /* debugger events don't suspend JDWP thread */
2506 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2507 assert(thread->dbgSuspendCount == 0);
2511 assert(thread->suspendCount >= thread->dbgSuspendCount);
2512 thread->suspendCount -= thread->dbgSuspendCount;
2513 thread->dbgSuspendCount = 0;
2515 unlockThreadSuspendCount();
2516 dvmUnlockThreadList();
2519 * Broadcast a notification to all suspended threads, some or all of
2520 * which may choose to wake up. No need to wait for them.
2522 lockThreadSuspendCount();
2523 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2525 unlockThreadSuspendCount();
2527 unlockThreadSuspend();
2529 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2533 * Determine if a thread is suspended.
2535 * As with all operations on foreign threads, the caller should hold
2536 * the thread list lock before calling.
2538 bool dvmIsSuspended(Thread* thread)
2541 * The thread could be:
2542 * (1) Running happily. status is RUNNING, isSuspended is false,
2543 * suspendCount is zero. Return "false".
2544 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2545 * suspendCount is nonzero. Return "false".
2546 * (3) Suspended. suspendCount is nonzero, and either (status is
2547 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2549 * (4) Waking up. suspendCount is zero, status is RUNNING and
2550 * isSuspended is true. Return "false" (since it could change
2551 * out from under us, unless we hold suspendCountLock).
2554 return (thread->suspendCount != 0 &&
2555 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2556 (thread->status != THREAD_RUNNING)));
2560 * Wait until another thread self-suspends. This is specifically for
2561 * synchronization between the JDWP thread and a thread that has decided
2562 * to suspend itself after sending an event to the debugger.
2564 * Threads that encounter "suspend all" events work as well -- the thread
2565 * in question suspends everybody else and then itself.
2567 * We can't hold a thread lock here or in the caller, because we could
2568 * get here just before the to-be-waited-for-thread issues a "suspend all".
2569 * There's an opportunity for badness if the thread we're waiting for exits
2570 * and gets cleaned up, but since the thread in question is processing a
2571 * debugger event, that's not really a possibility. (To avoid deadlock,
2572 * it's important that we not be in THREAD_RUNNING while we wait.)
2574 void dvmWaitForSuspend(Thread* thread)
2576 Thread* self = dvmThreadSelf();
2578 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
2579 self->threadId, thread->threadId);
2581 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2582 assert(thread != self);
2583 assert(self->status != THREAD_RUNNING);
2585 waitForThreadSuspend(self, thread);
2587 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
2588 self->threadId, thread->threadId);
2592 * Check to see if we need to suspend ourselves. If so, go to sleep on
2593 * a condition variable.
2595 * Takes "self" as an argument as an optimization. Pass in NULL to have
2598 * Returns "true" if we suspended ourselves.
2600 bool dvmCheckSuspendPending(Thread* self)
2605 self = dvmThreadSelf();
2607 /* fast path: if count is zero, bail immediately */
2608 if (self->suspendCount == 0)
2611 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
2613 assert(self->suspendCount >= 0); /* XXX: valid? useful? */
2615 didSuspend = (self->suspendCount != 0);
2616 self->isSuspended = true;
2617 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
2618 while (self->suspendCount != 0) {
2619 /* wait for wakeup signal; releases lock */
2621 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
2622 &gDvm.threadSuspendCountLock);
2625 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2626 self->isSuspended = false;
2627 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
2628 self->threadId, self->status);
2630 unlockThreadSuspendCount();
2636 * Update our status.
2638 * The "self" argument, which may be NULL, is accepted as an optimization.
2640 * Returns the old status.
2642 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
2644 ThreadStatus oldStatus;
2647 self = dvmThreadSelf();
2649 LOGVV("threadid=%d: (status %d -> %d)\n",
2650 self->threadId, self->status, newStatus);
2652 oldStatus = self->status;
2654 if (newStatus == THREAD_RUNNING) {
2656 * Change our status to THREAD_RUNNING. The transition requires
2657 * that we check for pending suspension, because the VM considers
2658 * us to be "asleep" in all other states.
2660 * We need to do the "suspend pending" check FIRST, because it grabs
2661 * a lock that could be held by something that wants us to suspend.
2662 * If we're in RUNNING it will wait for us, and we'll be waiting
2663 * for the lock it holds.
2665 assert(self->status != THREAD_RUNNING);
2667 dvmCheckSuspendPending(self);
2668 self->status = THREAD_RUNNING;
2671 * Change from one state to another, neither of which is
2672 * THREAD_RUNNING. This is most common during system or thread
2675 self->status = newStatus;
2682 * Get a statically defined thread group from a field in the ThreadGroup
2683 * Class object. Expected arguments are "mMain" and "mSystem".
2685 static Object* getStaticThreadGroup(const char* fieldName)
2687 StaticField* groupField;
2690 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
2691 fieldName, "Ljava/lang/ThreadGroup;");
2692 if (groupField == NULL) {
2693 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
2694 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
2697 groupObj = dvmGetStaticFieldObject(groupField);
2698 if (groupObj == NULL) {
2699 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
2700 dvmThrowException("Ljava/lang/InternalError;", NULL);
2706 Object* dvmGetSystemThreadGroup(void)
2708 return getStaticThreadGroup("mSystem");
2710 Object* dvmGetMainThreadGroup(void)
2712 return getStaticThreadGroup("mMain");
2716 * Given a VMThread object, return the associated Thread*.
2718 * NOTE: if the thread detaches, the struct Thread will disappear, and
2719 * we will be touching invalid data. For safety, lock the thread list
2720 * before calling this.
2722 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
2726 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
2727 return (Thread*) vmData;
2732 * Conversion map for "nice" values.
2734 * We use Android thread priority constants to be consistent with the rest
2735 * of the system. In some cases adjacent entries may overlap.
2737 static const int kNiceValues[10] = {
2738 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
2739 ANDROID_PRIORITY_BACKGROUND + 6,
2740 ANDROID_PRIORITY_BACKGROUND + 3,
2741 ANDROID_PRIORITY_BACKGROUND,
2742 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
2743 ANDROID_PRIORITY_NORMAL - 2,
2744 ANDROID_PRIORITY_NORMAL - 4,
2745 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
2746 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
2747 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
2751 * Change the scheduler cgroup of a pid
2753 int dvmChangeThreadSchedulerGroup(const char *cgroup)
2755 #ifdef HAVE_ANDROID_OS
2760 sprintf(path, "/dev/cpuctl/%s/tasks", (cgroup ? cgroup : ""));
2762 if (!(fp = fopen(path, "w"))) {
2763 #if ENABLE_CGROUP_ERR_LOGGING
2764 LOGW("Unable to open %s (%s)\n", path, strerror(errno));
2769 rc = fprintf(fp, "0");
2773 #if ENABLE_CGROUP_ERR_LOGGING
2774 LOGW("Unable to move pid %d to cgroup %s (%s)\n", getpid(),
2775 (cgroup ? cgroup : "<default>"), strerror(errno));
2779 return (rc < 0) ? errno : 0;
2780 #else // HAVE_ANDROID_OS
2786 * Change the priority of a system thread to match that of the Thread object.
2788 * We map a priority value from 1-10 to Linux "nice" values, where lower
2789 * numbers indicate higher priority.
2791 void dvmChangeThreadPriority(Thread* thread, int newPriority)
2793 pid_t pid = thread->systemTid;
2796 if (newPriority < 1 || newPriority > 10) {
2797 LOGW("bad priority %d\n", newPriority);
2800 newNice = kNiceValues[newPriority-1];
2802 if (newPriority == ANDROID_PRIORITY_BACKGROUND) {
2803 dvmChangeThreadSchedulerGroup("bg_non_interactive");
2804 } else if (getpriority(PRIO_PROCESS, pid) == ANDROID_PRIORITY_BACKGROUND) {
2805 dvmChangeThreadSchedulerGroup(NULL);
2808 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
2809 char* str = dvmGetThreadName(thread);
2810 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
2811 pid, str, newPriority, newNice, strerror(errno));
2814 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
2815 pid, newPriority, newNice);
2820 * Get the thread priority for the current thread by querying the system.
2821 * This is useful when attaching a thread through JNI.
2823 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
2825 static int getThreadPriorityFromSystem(void)
2827 int i, sysprio, jprio;
2830 sysprio = getpriority(PRIO_PROCESS, 0);
2831 if (sysprio == -1 && errno != 0) {
2832 LOGW("getpriority() failed: %s\n", strerror(errno));
2833 return THREAD_NORM_PRIORITY;
2836 jprio = THREAD_MIN_PRIORITY;
2837 for (i = 0; i < NELEM(kNiceValues); i++) {
2838 if (sysprio >= kNiceValues[i])
2842 if (jprio > THREAD_MAX_PRIORITY)
2843 jprio = THREAD_MAX_PRIORITY;
2850 * Return true if the thread is on gDvm.threadList.
2851 * Caller should not hold gDvm.threadListLock.
2853 bool dvmIsOnThreadList(const Thread* thread)
2857 dvmLockThreadList(NULL);
2858 if (thread == gDvm.threadList) {
2861 ret = thread->prev != NULL || thread->next != NULL;
2863 dvmUnlockThreadList();
2869 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
2872 void dvmDumpThread(Thread* thread, bool isRunning)
2874 DebugOutputTarget target;
2876 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
2877 dvmDumpThreadEx(&target, thread, isRunning);
2881 * Print information about the specified thread.
2883 * Works best when the thread in question is "self" or has been suspended.
2884 * When dumping a separate thread that's still running, set "isRunning" to
2885 * use a more cautious thread dump function.
2887 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
2890 /* tied to ThreadStatus enum */
2891 static const char* kStatusNames[] = {
2892 "ZOMBIE", "RUNNABLE", "TIMED_WAIT", "MONITOR", "WAIT",
2893 "INITIALIZING", "STARTING", "NATIVE", "VMWAIT"
2897 StringObject* nameStr;
2898 char* threadName = NULL;
2899 char* groupName = NULL;
2901 int priority; // java.lang.Thread priority
2902 int policy; // pthread policy
2903 struct sched_param sp; // pthread scheduling parameters
2905 threadObj = thread->threadObj;
2906 if (threadObj == NULL) {
2907 LOGW("Can't dump thread %d: threadObj not set\n", thread->threadId);
2910 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
2911 gDvm.offJavaLangThread_name);
2912 threadName = dvmCreateCstrFromString(nameStr);
2914 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
2915 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
2917 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
2918 LOGW("Warning: pthread_getschedparam failed\n");
2920 sp.sched_priority = -1;
2923 /* a null value for group is not expected, but deal with it anyway */
2924 groupObj = (Object*) dvmGetFieldObject(threadObj,
2925 gDvm.offJavaLangThread_group);
2926 if (groupObj != NULL) {
2927 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
2928 "name", "Ljava/lang/String;");
2930 LOGW("Unable to find 'name' field in ThreadGroup\n");
2932 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
2933 groupName = dvmCreateCstrFromString(nameStr);
2936 if (groupName == NULL)
2937 groupName = strdup("(BOGUS GROUP)");
2939 assert(thread->status < NELEM(kStatusNames));
2940 dvmPrintDebugMessage(target,
2941 "\"%s\"%s prio=%d tid=%d %s\n",
2942 threadName, isDaemon ? " daemon" : "",
2943 priority, thread->threadId, kStatusNames[thread->status]);
2944 dvmPrintDebugMessage(target,
2945 " | group=\"%s\" sCount=%d dsCount=%d s=%d obj=%p\n",
2946 groupName, thread->suspendCount, thread->dbgSuspendCount,
2947 thread->isSuspended, thread->threadObj);
2948 dvmPrintDebugMessage(target,
2949 " | sysTid=%d nice=%d sched=%d/%d handle=%d\n",
2950 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
2951 policy, sp.sched_priority, (int)thread->handle);
2953 #ifdef WITH_MONITOR_TRACKING
2955 LockedObjectData* lod = thread->pLockedObjects;
2957 dvmPrintDebugMessage(target, " | monitors held:\n");
2959 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
2960 while (lod != NULL) {
2961 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
2962 lod->obj, lod->recursionCount, lod->obj->clazz->descriptor);
2969 dvmDumpRunningThreadStack(target, thread);
2971 dvmDumpThreadStack(target, thread);
2979 * Get the name of a thread.
2981 * For correctness, the caller should hold the thread list lock to ensure
2982 * that the thread doesn't go away mid-call.
2984 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
2986 char* dvmGetThreadName(Thread* thread)
2988 StringObject* nameObj;
2990 if (thread->threadObj == NULL) {
2991 LOGW("threadObj is NULL, name not available\n");
2992 return strdup("-unknown-");
2995 nameObj = (StringObject*)
2996 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
2997 return dvmCreateCstrFromString(nameObj);
3001 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3004 void dvmDumpAllThreads(bool grabLock)
3006 DebugOutputTarget target;
3008 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3009 dvmDumpAllThreadsEx(&target, grabLock);
3013 * Print information about all known threads. Assumes they have been
3014 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3016 * If "grabLock" is true, we grab the thread lock list. This is important
3017 * to do unless the caller already holds the lock.
3019 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3023 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3026 dvmLockThreadList(dvmThreadSelf());
3028 thread = gDvm.threadList;
3029 while (thread != NULL) {
3030 dvmDumpThreadEx(target, thread, false);
3033 assert(thread->next == NULL || thread->next->prev == thread);
3035 thread = thread->next;
3039 dvmUnlockThreadList();
3042 #ifdef WITH_MONITOR_TRACKING
3044 * Count up the #of locked objects in the current thread.
3046 static int getThreadObjectCount(const Thread* self)
3048 LockedObjectData* lod;
3051 lod = self->pLockedObjects;
3052 while (lod != NULL) {
3060 * Add the object to the thread's locked object list if it doesn't already
3061 * exist. The most recently added object is the most likely to be released
3062 * next, so we insert at the head of the list.
3064 * If it already exists, we increase the recursive lock count.
3066 * The object's lock may be thin or fat.
3068 void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3070 LockedObjectData* newLod;
3071 LockedObjectData* lod;
3075 lod = self->pLockedObjects;
3076 while (lod != NULL) {
3077 if (lod->obj == obj) {
3078 lod->recursionCount++;
3079 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3085 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3086 if (newLod == NULL) {
3087 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3091 newLod->recursionCount = 0;
3094 trace = dvmFillInStackTraceRaw(self, &depth);
3095 newLod->rawStackTrace = trace;
3096 newLod->stackDepth = depth;
3099 newLod->next = self->pLockedObjects;
3100 self->pLockedObjects = newLod;
3102 LOGV("+++ threadid=%d: added %p, now %d\n",
3103 self->threadId, newLod, getThreadObjectCount(self));
3107 * Remove the object from the thread's locked object list. If the entry
3108 * has a nonzero recursion count, we just decrement the count instead.
3110 void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3112 LockedObjectData* lod;
3113 LockedObjectData* prevLod;
3115 lod = self->pLockedObjects;
3117 while (lod != NULL) {
3118 if (lod->obj == obj) {
3119 if (lod->recursionCount > 0) {
3120 lod->recursionCount--;
3121 LOGV("+++ -recursive lock %p -> %d\n",
3122 obj, lod->recursionCount);
3133 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3136 if (prevLod == NULL) {
3137 /* first item in list */
3138 assert(self->pLockedObjects == lod);
3139 self->pLockedObjects = lod->next;
3141 /* middle/end of list */
3142 prevLod->next = lod->next;
3145 LOGV("+++ threadid=%d: removed %p, now %d\n",
3146 self->threadId, lod, getThreadObjectCount(self));
3147 free(lod->rawStackTrace);
3152 * If the specified object is already in the thread's locked object list,
3153 * return the LockedObjectData struct. Otherwise return NULL.
3155 LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3157 LockedObjectData* lod;
3159 lod = self->pLockedObjects;
3160 while (lod != NULL) {
3161 if (lod->obj == obj)
3167 #endif /*WITH_MONITOR_TRACKING*/
3171 * GC helper functions
3174 static void gcScanInterpStackReferences(Thread *thread)
3178 framePtr = (const u4 *)thread->curFrame;
3179 while (framePtr != NULL) {
3180 const StackSaveArea *saveArea;
3181 const Method *method;
3183 saveArea = SAVEAREA_FROM_FP(framePtr);
3184 method = saveArea->method;
3185 if (method != NULL) {
3186 #ifdef COUNT_PRECISE_METHODS
3187 /* the GC is running, so no lock required */
3188 if (!dvmIsNativeMethod(method)) {
3189 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3190 LOGI("Added %s.%s %p\n",
3191 method->clazz->descriptor, method->name, method);
3195 for (i = method->registersSize - 1; i >= 0; i--) {
3196 u4 rval = *framePtr++;
3197 //TODO: wrap markifobject in a macro that does pointer checks
3198 if (rval != 0 && (rval & 0x3) == 0) {
3199 dvmMarkIfObject((Object *)rval);
3203 /* else this is a break frame; nothing to mark.
3206 /* Don't fall into an infinite loop if things get corrupted.
3208 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
3209 saveArea->prevFrame == NULL);
3210 framePtr = saveArea->prevFrame;
3214 static void gcScanReferenceTable(ReferenceTable *refTable)
3218 //TODO: these asserts are overkill; turn them off when things stablize.
3219 assert(refTable != NULL);
3220 assert(refTable->table != NULL);
3221 assert(refTable->nextEntry != NULL);
3222 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
3223 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
3225 op = refTable->table;
3226 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
3227 dvmMarkObjectNonNull(*(op++));
3232 * Scan a Thread and mark any objects it references.
3234 static void gcScanThread(Thread *thread)
3236 assert(thread != NULL);
3239 * The target thread must be suspended or in a state where it can't do
3240 * any harm (e.g. in Object.wait()). The only exception is the current
3241 * thread, which will still be active and in the "running" state.
3243 * (Newly-created threads shouldn't be able to shift themselves to
3244 * RUNNING without a suspend-pending check, so this shouldn't cause
3245 * a false-positive.)
3247 assert(thread->status != THREAD_RUNNING || thread->isSuspended ||
3248 thread == dvmThreadSelf());
3250 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
3252 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
3254 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
3256 dvmMarkObject(thread->exception); // usually NULL
3257 gcScanReferenceTable(&thread->internalLocalRefTable);
3259 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
3261 gcScanReferenceTable(&thread->jniLocalRefTable);
3263 if (thread->jniMonitorRefTable.table != NULL) {
3264 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
3266 gcScanReferenceTable(&thread->jniMonitorRefTable);
3269 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
3271 gcScanInterpStackReferences(thread);
3273 HPROF_CLEAR_GC_SCAN_STATE();
3276 static void gcScanAllThreads()
3280 /* Lock the thread list so we can safely use the
3281 * next/prev pointers.
3283 dvmLockThreadList(dvmThreadSelf());
3285 for (thread = gDvm.threadList; thread != NULL;
3286 thread = thread->next)
3288 /* We need to scan our own stack, so don't special-case
3289 * the current thread.
3291 gcScanThread(thread);
3294 dvmUnlockThreadList();
3297 void dvmGcScanRootThreadGroups()
3299 /* We scan the VM's list of threads instead of going
3300 * through the actual ThreadGroups, but it should be
3303 * This assumes that the ThreadGroup class object is in
3304 * the root set, which should always be true; it's
3305 * loaded by the built-in class loader, which is part