blob: 54d0f4bddd800a572a4e7f04a9a7c12cf53ff8a0 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project99409882009-03-18 22:20:24 -070016
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080017/*
18 * Thread support.
19 */
20#include "Dalvik.h"
21
22#include "utils/threads.h" // need Android thread priorities
23
24#include <stdlib.h>
25#include <unistd.h>
26#include <sys/time.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070027#include <sys/types.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080028#include <sys/resource.h>
29#include <sys/mman.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070030#include <signal.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080031#include <errno.h>
Andy McFaddend62c0b52009-08-04 15:02:12 -070032#include <fcntl.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080033
34#if defined(HAVE_PRCTL)
35#include <sys/prctl.h>
36#endif
37
Ben Chengfe1be872009-08-21 16:18:46 -070038#if defined(WITH_SELF_VERIFICATION)
39#include "interp/Jit.h" // need for self verification
40#endif
41
42
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080043/* desktop Linux needs a little help with gettid() */
44#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
45#define __KERNEL__
46# include <linux/unistd.h>
47#ifdef _syscall0
48_syscall0(pid_t,gettid)
49#else
50pid_t gettid() { return syscall(__NR_gettid);}
51#endif
52#undef __KERNEL__
53#endif
54
San Mehat256fc152009-04-21 14:03:06 -070055// Change this to enable logging on cgroup errors
56#define ENABLE_CGROUP_ERR_LOGGING 0
57
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080058// change this to LOGV/LOGD to debug thread activity
59#define LOG_THREAD LOGVV
60
61/*
62Notes on Threading
63
64All threads are native pthreads. All threads, except the JDWP debugger
65thread, are visible to code running in the VM and to the debugger. (We
66don't want the debugger to try to manipulate the thread that listens for
67instructions from the debugger.) Internal VM threads are in the "system"
68ThreadGroup, all others are in the "main" ThreadGroup, per convention.
69
70The GC only runs when all threads have been suspended. Threads are
71expected to suspend themselves, using a "safe point" mechanism. We check
72for a suspend request at certain points in the main interpreter loop,
73and on requests coming in from native code (e.g. all JNI functions).
74Certain debugger events may inspire threads to self-suspend.
75
76Native methods must use JNI calls to modify object references to avoid
77clashes with the GC. JNI doesn't provide a way for native code to access
78arrays of objects as such -- code must always get/set individual entries --
79so it should be possible to fully control access through JNI.
80
81Internal native VM threads, such as the finalizer thread, must explicitly
82check for suspension periodically. In most cases they will be sound
83asleep on a condition variable, and won't notice the suspension anyway.
84
85Threads may be suspended by the GC, debugger, or the SIGQUIT listener
86thread. The debugger may suspend or resume individual threads, while the
87GC always suspends all threads. Each thread has a "suspend count" that
88is incremented on suspend requests and decremented on resume requests.
89When the count is zero, the thread is runnable. This allows us to fulfill
90a debugger requirement: if the debugger suspends a thread, the thread is
91not allowed to run again until the debugger resumes it (or disconnects,
92in which case we must resume all debugger-suspended threads).
93
94Paused threads sleep on a condition variable, and are awoken en masse.
95Certain "slow" VM operations, such as starting up a new thread, will be
96done in a separate "VMWAIT" state, so that the rest of the VM doesn't
97freeze up waiting for the operation to finish. Threads must check for
98pending suspension when leaving VMWAIT.
99
100Because threads suspend themselves while interpreting code or when native
101code makes JNI calls, there is no risk of suspending while holding internal
102VM locks. All threads can enter a suspended (or native-code-only) state.
103Also, we don't have to worry about object references existing solely
104in hardware registers.
105
106We do, however, have to worry about objects that were allocated internally
107and aren't yet visible to anything else in the VM. If we allocate an
108object, and then go to sleep on a mutex after changing to a non-RUNNING
109state (e.g. while trying to allocate a second object), the first object
110could be garbage-collected out from under us while we sleep. To manage
111this, we automatically add all allocated objects to an internal object
112tracking list, and only remove them when we know we won't be suspended
113before the object appears in the GC root set.
114
115The debugger may choose to suspend or resume a single thread, which can
116lead to application-level deadlocks; this is expected behavior. The VM
117will only check for suspension of single threads when the debugger is
118active (the java.lang.Thread calls for this are deprecated and hence are
119not supported). Resumption of a single thread is handled by decrementing
120the thread's suspend count and sending a broadcast signal to the condition
121variable. (This will cause all threads to wake up and immediately go back
122to sleep, which isn't tremendously efficient, but neither is having the
123debugger attached.)
124
125The debugger is not allowed to resume threads suspended by the GC. This
126is trivially enforced by ignoring debugger requests while the GC is running
127(the JDWP thread is suspended during GC).
128
129The VM maintains a Thread struct for every pthread known to the VM. There
130is a java/lang/Thread object associated with every Thread. At present,
131there is no safe way to go from a Thread object to a Thread struct except by
132locking and scanning the list; this is necessary because the lifetimes of
133the two are not closely coupled. We may want to change this behavior,
134though at present the only performance impact is on the debugger (see
135threadObjToThread()). See also notes about dvmDetachCurrentThread().
136*/
137/*
138Alternate implementation (signal-based):
139
140Threads run without safe points -- zero overhead. The VM uses a signal
141(e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
142
143The trouble with using signals to suspend threads is that it means a thread
144can be in the middle of an operation when garbage collection starts.
145To prevent some sticky situations, we have to introduce critical sections
146to the VM code.
147
148Critical sections temporarily block suspension for a given thread.
149The thread must move to a non-blocked state (and self-suspend) after
150finishing its current task. If the thread blocks on a resource held
151by a suspended thread, we're hosed.
152
153One approach is to require that no blocking operations, notably
154acquisition of mutexes, can be performed within a critical section.
155This is too limiting. For example, if thread A gets suspended while
156holding the thread list lock, it will prevent the GC or debugger from
157being able to safely access the thread list. We need to wrap the critical
158section around the entire operation (enter critical, get lock, do stuff,
159release lock, exit critical).
160
161A better approach is to declare that certain resources can only be held
162within critical sections. A thread that enters a critical section and
163then gets blocked on the thread list lock knows that the thread it is
164waiting for is also in a critical section, and will release the lock
165before suspending itself. Eventually all threads will complete their
166operations and self-suspend. For this to work, the VM must:
167
168 (1) Determine the set of resources that may be accessed from the GC or
169 debugger threads. The mutexes guarding those go into the "critical
170 resource set" (CRS).
171 (2) Ensure that no resource in the CRS can be acquired outside of a
172 critical section. This can be verified with an assert().
173 (3) Ensure that only resources in the CRS can be held while in a critical
174 section. This is harder to enforce.
175
176If any of these conditions are not met, deadlock can ensue when grabbing
177resources in the GC or debugger (#1) or waiting for threads to suspend
178(#2,#3). (You won't actually deadlock in the GC, because if the semantics
179above are followed you don't need to lock anything in the GC. The risk is
180rather that the GC will access data structures in an intermediate state.)
181
182This approach requires more care and awareness in the VM than
183safe-pointing. Because the GC and debugger are fairly intrusive, there
184really aren't any internal VM resources that aren't shared. Thus, the
185enter/exit critical calls can be added to internal mutex wrappers, which
186makes it easy to get #1 and #2 right.
187
188An ordering should be established for all locks to avoid deadlocks.
189
190Monitor locks, which are also implemented with pthread calls, should not
191cause any problems here. Threads fighting over such locks will not be in
192critical sections and can be suspended freely.
193
194This can get tricky if we ever need exclusive access to VM and non-VM
195resources at the same time. It's not clear if this is a real concern.
196
197There are (at least) two ways to handle the incoming signals:
198
199 (a) Always accept signals. If we're in a critical section, the signal
200 handler just returns without doing anything (the "suspend level"
201 should have been incremented before the signal was sent). Otherwise,
202 if the "suspend level" is nonzero, we go to sleep.
203 (b) Block signals in critical sections. This ensures that we can't be
204 interrupted in a critical section, but requires pthread_sigmask()
205 calls on entry and exit.
206
207This is a choice between blocking the message and blocking the messenger.
208Because UNIX signals are unreliable (you can only know that you have been
209signaled, not whether you were signaled once or 10 times), the choice is
210not significant for correctness. The choice depends on the efficiency
211of pthread_sigmask() and the desire to actually block signals. Either way,
212it is best to ensure that there is only one indication of "blocked";
213having two (i.e. block signals and set a flag, then only send a signal
214if the flag isn't set) can lead to race conditions.
215
216The signal handler must take care to copy registers onto the stack (via
217setjmp), so that stack scans find all references. Because we have to scan
218native stacks, "exact" GC is not possible with this approach.
219
220Some other concerns with flinging signals around:
221 - Odd interactions with some debuggers (e.g. gdb on the Mac)
222 - Restrictions on some standard library calls during GC (e.g. don't
223 use printf on stdout to print GC debug messages)
224*/
225
Carl Shapiro59a93122010-01-26 17:12:51 -0800226#define kMaxThreadId ((1 << 16) - 1)
227#define kMainThreadId 1
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800228
229
230static Thread* allocThread(int interpStackSize);
231static bool prepareThread(Thread* thread);
232static void setThreadSelf(Thread* thread);
233static void unlinkThread(Thread* thread);
234static void freeThread(Thread* thread);
235static void assignThreadId(Thread* thread);
236static bool createFakeEntryFrame(Thread* thread);
237static bool createFakeRunFrame(Thread* thread);
238static void* interpThreadStart(void* arg);
239static void* internalThreadStart(void* arg);
240static void threadExitUncaughtException(Thread* thread, Object* group);
241static void threadExitCheck(void* arg);
242static void waitForThreadSuspend(Thread* self, Thread* thread);
243static int getThreadPriorityFromSystem(void);
244
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700245/*
246 * The JIT needs to know if any thread is suspended. We do this by
247 * maintaining a global sum of all threads' suspend counts. All suspendCount
248 * updates should go through this after aquiring threadSuspendCountLock.
249 */
250static inline void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
251{
252 *pSuspendCount += delta;
253 gDvm.sumThreadSuspendCount += delta;
254}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800255
256/*
257 * Initialize thread list and main thread's environment. We need to set
258 * up some basic stuff so that dvmThreadSelf() will work when we start
259 * loading classes (e.g. to check for exceptions).
260 */
261bool dvmThreadStartup(void)
262{
263 Thread* thread;
264
265 /* allocate a TLS slot */
266 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
267 LOGE("ERROR: pthread_key_create failed\n");
268 return false;
269 }
270
271 /* test our pthread lib */
272 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
273 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
274
275 /* prep thread-related locks and conditions */
276 dvmInitMutex(&gDvm.threadListLock);
277 pthread_cond_init(&gDvm.threadStartCond, NULL);
278 //dvmInitMutex(&gDvm.vmExitLock);
279 pthread_cond_init(&gDvm.vmExitCond, NULL);
280 dvmInitMutex(&gDvm._threadSuspendLock);
281 dvmInitMutex(&gDvm.threadSuspendCountLock);
282 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
283#ifdef WITH_DEADLOCK_PREDICTION
284 dvmInitMutex(&gDvm.deadlockHistoryLock);
285#endif
286
287 /*
288 * Dedicated monitor for Thread.sleep().
289 * TODO: change this to an Object* so we don't have to expose this
290 * call, and we interact better with JDWP monitor calls. Requires
291 * deferring the object creation to much later (e.g. final "main"
292 * thread prep) or until first use.
293 */
294 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
295
296 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
297
298 thread = allocThread(gDvm.stackSize);
299 if (thread == NULL)
300 return false;
301
302 /* switch mode for when we run initializers */
303 thread->status = THREAD_RUNNING;
304
305 /*
306 * We need to assign the threadId early so we can lock/notify
307 * object monitors. We'll set the "threadObj" field later.
308 */
309 prepareThread(thread);
310 gDvm.threadList = thread;
311
312#ifdef COUNT_PRECISE_METHODS
313 gDvm.preciseMethods = dvmPointerSetAlloc(200);
314#endif
315
316 return true;
317}
318
319/*
320 * We're a little farther up now, and can load some basic classes.
321 *
322 * We're far enough along that we can poke at java.lang.Thread and friends,
323 * but should not assume that static initializers have run (or cause them
324 * to do so). That means no object allocations yet.
325 */
326bool dvmThreadObjStartup(void)
327{
328 /*
329 * Cache the locations of these classes. It's likely that we're the
330 * first to reference them, so they're being loaded now.
331 */
332 gDvm.classJavaLangThread =
333 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
334 gDvm.classJavaLangVMThread =
335 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
336 gDvm.classJavaLangThreadGroup =
337 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
338 if (gDvm.classJavaLangThread == NULL ||
339 gDvm.classJavaLangThreadGroup == NULL ||
340 gDvm.classJavaLangThreadGroup == NULL)
341 {
342 LOGE("Could not find one or more essential thread classes\n");
343 return false;
344 }
345
346 /*
347 * Cache field offsets. This makes things a little faster, at the
348 * expense of hard-coding non-public field names into the VM.
349 */
350 gDvm.offJavaLangThread_vmThread =
351 dvmFindFieldOffset(gDvm.classJavaLangThread,
352 "vmThread", "Ljava/lang/VMThread;");
353 gDvm.offJavaLangThread_group =
354 dvmFindFieldOffset(gDvm.classJavaLangThread,
355 "group", "Ljava/lang/ThreadGroup;");
356 gDvm.offJavaLangThread_daemon =
357 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
358 gDvm.offJavaLangThread_name =
359 dvmFindFieldOffset(gDvm.classJavaLangThread,
360 "name", "Ljava/lang/String;");
361 gDvm.offJavaLangThread_priority =
362 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
363
364 if (gDvm.offJavaLangThread_vmThread < 0 ||
365 gDvm.offJavaLangThread_group < 0 ||
366 gDvm.offJavaLangThread_daemon < 0 ||
367 gDvm.offJavaLangThread_name < 0 ||
368 gDvm.offJavaLangThread_priority < 0)
369 {
370 LOGE("Unable to find all fields in java.lang.Thread\n");
371 return false;
372 }
373
374 gDvm.offJavaLangVMThread_thread =
375 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
376 "thread", "Ljava/lang/Thread;");
377 gDvm.offJavaLangVMThread_vmData =
378 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
379 if (gDvm.offJavaLangVMThread_thread < 0 ||
380 gDvm.offJavaLangVMThread_vmData < 0)
381 {
382 LOGE("Unable to find all fields in java.lang.VMThread\n");
383 return false;
384 }
385
386 /*
387 * Cache the vtable offset for "run()".
388 *
389 * We don't want to keep the Method* because then we won't find see
390 * methods defined in subclasses.
391 */
392 Method* meth;
393 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
394 if (meth == NULL) {
395 LOGE("Unable to find run() in java.lang.Thread\n");
396 return false;
397 }
398 gDvm.voffJavaLangThread_run = meth->methodIndex;
399
400 /*
401 * Cache vtable offsets for ThreadGroup methods.
402 */
403 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
404 "removeThread", "(Ljava/lang/Thread;)V");
405 if (meth == NULL) {
406 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
407 return false;
408 }
409 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
410
411 return true;
412}
413
414/*
415 * All threads should be stopped by now. Clean up some thread globals.
416 */
417void dvmThreadShutdown(void)
418{
419 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700420 /*
421 * If we walk through the thread list and try to free the
422 * lingering thread structures (which should only be for daemon
423 * threads), the daemon threads may crash if they execute before
424 * the process dies. Let them leak.
425 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800426 freeThread(gDvm.threadList);
427 gDvm.threadList = NULL;
428 }
429
430 dvmFreeBitVector(gDvm.threadIdMap);
431
432 dvmFreeMonitorList();
433
434 pthread_key_delete(gDvm.pthreadKeySelf);
435}
436
437
438/*
439 * Grab the suspend count global lock.
440 */
441static inline void lockThreadSuspendCount(void)
442{
443 /*
444 * Don't try to change to VMWAIT here. When we change back to RUNNING
445 * we have to check for a pending suspend, which results in grabbing
446 * this lock recursively. Doesn't work with "fast" pthread mutexes.
447 *
448 * This lock is always held for very brief periods, so as long as
449 * mutex ordering is respected we shouldn't stall.
450 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700451 dvmLockMutex(&gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800452}
453
454/*
455 * Release the suspend count global lock.
456 */
457static inline void unlockThreadSuspendCount(void)
458{
459 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
460}
461
462/*
463 * Grab the thread list global lock.
464 *
465 * This is held while "suspend all" is trying to make everybody stop. If
466 * the shutdown is in progress, and somebody tries to grab the lock, they'll
467 * have to wait for the GC to finish. Therefore it's important that the
468 * thread not be in RUNNING mode.
469 *
470 * We don't have to check to see if we should be suspended once we have
471 * the lock. Nobody can suspend all threads without holding the thread list
472 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700473 *
Andy McFadden3469a7e2010-08-04 16:09:10 -0700474 * This function deliberately avoids the use of dvmChangeStatus(),
475 * which could grab threadSuspendCountLock. To avoid deadlock, threads
476 * are required to grab the thread list lock before the thread suspend
477 * count lock. (See comment in DvmGlobals.)
478 *
Andy McFadden44860362009-08-06 17:56:14 -0700479 * TODO: consider checking for suspend after acquiring the lock, and
480 * backing off if set. As stated above, it can't happen during normal
481 * execution, but it *can* happen during shutdown when daemon threads
482 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800483 */
484void dvmLockThreadList(Thread* self)
485{
486 ThreadStatus oldStatus;
487
488 if (self == NULL) /* try to get it from TLS */
489 self = dvmThreadSelf();
490
491 if (self != NULL) {
492 oldStatus = self->status;
493 self->status = THREAD_VMWAIT;
494 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700495 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800496 //LOGW("NULL self in dvmLockThreadList\n");
497 oldStatus = -1; // shut up gcc
498 }
499
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700500 dvmLockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800501
502 if (self != NULL)
503 self->status = oldStatus;
504}
505
506/*
Andy McFaddend19988d2010-10-22 13:32:12 -0700507 * Try to lock the thread list.
508 *
509 * Returns "true" if we locked it. This is a "fast" mutex, so if the
510 * current thread holds the lock this will fail.
511 */
512bool dvmTryLockThreadList(void)
513{
514 return (dvmTryLockMutex(&gDvm.threadListLock) == 0);
515}
516
517/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800518 * Release the thread list global lock.
519 */
520void dvmUnlockThreadList(void)
521{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700522 dvmUnlockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800523}
524
The Android Open Source Project99409882009-03-18 22:20:24 -0700525/*
526 * Convert SuspendCause to a string.
527 */
528static const char* getSuspendCauseStr(SuspendCause why)
529{
530 switch (why) {
531 case SUSPEND_NOT: return "NOT?";
532 case SUSPEND_FOR_GC: return "gc";
533 case SUSPEND_FOR_DEBUG: return "debug";
534 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
535 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700536 case SUSPEND_FOR_VERIFY: return "verify";
Carl Shapiro07018e22010-10-26 21:07:41 -0700537 case SUSPEND_FOR_HPROF: return "hprof";
Ben Chenga8e64a72009-10-20 13:01:36 -0700538#if defined(WITH_JIT)
539 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
540 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800541 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800542 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700543#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700544 default: return "UNKNOWN";
545 }
546}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800547
548/*
549 * Grab the "thread suspend" lock. This is required to prevent the
550 * GC and the debugger from simultaneously suspending all threads.
551 *
552 * If we fail to get the lock, somebody else is trying to suspend all
553 * threads -- including us. If we go to sleep on the lock we'll deadlock
554 * the VM. Loop until we get it or somebody puts us to sleep.
555 */
556static void lockThreadSuspend(const char* who, SuspendCause why)
557{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800558 const int kSpinSleepTime = 3*1000*1000; /* 3s */
559 u8 startWhen = 0; // init req'd to placate gcc
560 int sleepIter = 0;
561 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700562
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800563 do {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700564 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800565 if (cc != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700566 Thread* self = dvmThreadSelf();
567
568 if (!dvmCheckSuspendPending(self)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800569 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700570 * Could be that a resume-all is in progress, and something
571 * grabbed the CPU when the wakeup was broadcast. The thread
572 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700573 * thread suspend lock. (We release before the broadcast,
574 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700575 *
576 * Could be we hit the window as a suspend was started,
577 * and the lock has been grabbed but the suspend counts
578 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700579 *
580 * Could be an unusual JNI thread-attach thing.
581 *
582 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800583 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700584 *
585 * Could be two app threads both want to patch predicted
586 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800587 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700588 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
589 " it's held, no suspend pending\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700590 self->threadId, who, getSuspendCauseStr(why));
The Android Open Source Project99409882009-03-18 22:20:24 -0700591 } else {
592 /* we suspended; reset timeout */
593 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800594 }
595
596 /* give the lock-holder a chance to do some work */
597 if (sleepIter == 0)
598 startWhen = dvmGetRelativeTimeUsec();
599 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700600 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800601 " bailing\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700602 self->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700603 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800604 dvmDumpAllThreads(false);
605 dvmAbort();
606 }
607 }
608 } while (cc != 0);
609 assert(cc == 0);
610}
611
612/*
613 * Release the "thread suspend" lock.
614 */
615static inline void unlockThreadSuspend(void)
616{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700617 dvmUnlockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800618}
619
620
621/*
622 * Kill any daemon threads that still exist. All of ours should be
623 * stopped, so these should be Thread objects or JNI-attached threads
624 * started by the application. Actively-running threads are likely
625 * to crash the process if they continue to execute while the VM
626 * shuts down, so we really need to kill or suspend them. (If we want
627 * the VM to restart within this process, we need to kill them, but that
628 * leaves open the possibility of orphaned resources.)
629 *
630 * Waiting for the thread to suspend may be unwise at this point, but
631 * if one of these is wedged in a critical section then we probably
632 * would've locked up on the last GC attempt.
633 *
634 * It's possible for this function to get called after a failed
635 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700636 *
637 * This will be called from whatever thread calls DestroyJavaVM, usually
638 * but not necessarily the main thread. It's likely, but not guaranteed,
639 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800640 */
641void dvmSlayDaemons(void)
642{
Andy McFadden44860362009-08-06 17:56:14 -0700643 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800644 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700645 int threadId = 0;
646 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800647
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800648 dvmLockThreadList(self);
649
Andy McFadden44860362009-08-06 17:56:14 -0700650 if (self != NULL)
651 threadId = self->threadId;
652
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800653 target = gDvm.threadList;
654 while (target != NULL) {
655 if (target == self) {
656 target = target->next;
657 continue;
658 }
659
660 if (!dvmGetFieldBoolean(target->threadObj,
661 gDvm.offJavaLangThread_daemon))
662 {
Andy McFadden44860362009-08-06 17:56:14 -0700663 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800664 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700665 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800666 }
667
Andy McFadden44860362009-08-06 17:56:14 -0700668 char* threadName = dvmGetThreadName(target);
669 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
670 threadId, target->threadId, threadName);
671 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800672
Andy McFadden44860362009-08-06 17:56:14 -0700673 /* mark as suspended */
674 lockThreadSuspendCount();
675 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
676 unlockThreadSuspendCount();
677 doWait = true;
678
679 target = target->next;
680 }
681
682 //dvmDumpAllThreads(false);
683
684 /*
685 * Unlock the thread list, relocking it later if necessary. It's
686 * possible a thread is in VMWAIT after calling dvmLockThreadList,
687 * and that function *doesn't* check for pending suspend after
688 * acquiring the lock. We want to let them finish their business
689 * and see the pending suspend before we continue here.
690 *
691 * There's no guarantee of mutex fairness, so this might not work.
692 * (The alternative is to have dvmLockThreadList check for suspend
693 * after acquiring the lock and back off, something we should consider.)
694 */
695 dvmUnlockThreadList();
696
697 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800698 bool complained = false;
699
Andy McFadden44860362009-08-06 17:56:14 -0700700 usleep(200 * 1000);
701
702 dvmLockThreadList(self);
703
704 /*
705 * Sleep for a bit until the threads have suspended. We're trying
706 * to exit, so don't wait for too long.
707 */
708 int i;
709 for (i = 0; i < 10; i++) {
710 bool allSuspended = true;
711
712 target = gDvm.threadList;
713 while (target != NULL) {
714 if (target == self) {
715 target = target->next;
716 continue;
717 }
718
Andy McFadden6dce9962010-08-23 16:45:24 -0700719 if (target->status == THREAD_RUNNING) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800720 if (!complained)
721 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700722 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800723 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700724 }
725
726 target = target->next;
727 }
728
729 if (allSuspended) {
730 LOGD("threadid=%d: all daemons have suspended\n", threadId);
731 break;
732 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800733 if (!complained) {
734 complained = true;
735 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
736 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800737 }
Andy McFadden44860362009-08-06 17:56:14 -0700738 }
739
740 usleep(200 * 1000);
741 }
742 dvmUnlockThreadList();
743 }
744
745#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
746 /*
747 * Abandon the threads and recover their resources.
748 */
749 target = gDvm.threadList;
750 while (target != NULL) {
751 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800752 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800753 freeThread(target);
754 target = nextTarget;
755 }
Andy McFadden44860362009-08-06 17:56:14 -0700756#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800757
Andy McFadden44860362009-08-06 17:56:14 -0700758 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800759}
760
761
762/*
763 * Finish preparing the parts of the Thread struct required to support
764 * JNI registration.
765 */
766bool dvmPrepMainForJni(JNIEnv* pEnv)
767{
768 Thread* self;
769
770 /* main thread is always first in list at this point */
771 self = gDvm.threadList;
772 assert(self->threadId == kMainThreadId);
773
774 /* create a "fake" JNI frame at the top of the main thread interp stack */
775 if (!createFakeEntryFrame(self))
776 return false;
777
778 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
779 dvmSetJniEnvThreadId(pEnv, self);
780 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
781
782 return true;
783}
784
785
786/*
787 * Finish preparing the main thread, allocating some objects to represent
788 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700789 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800790 */
791bool dvmPrepMainThread(void)
792{
793 Thread* thread;
794 Object* groupObj;
795 Object* threadObj;
796 Object* vmThreadObj;
797 StringObject* threadNameStr;
798 Method* init;
799 JValue unused;
800
801 LOGV("+++ finishing prep on main VM thread\n");
802
803 /* main thread is always first in list at this point */
804 thread = gDvm.threadList;
805 assert(thread->threadId == kMainThreadId);
806
807 /*
808 * Make sure the classes are initialized. We have to do this before
809 * we create an instance of them.
810 */
811 if (!dvmInitClass(gDvm.classJavaLangClass)) {
812 LOGE("'Class' class failed to initialize\n");
813 return false;
814 }
815 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
816 !dvmInitClass(gDvm.classJavaLangThread) ||
817 !dvmInitClass(gDvm.classJavaLangVMThread))
818 {
819 LOGE("thread classes failed to initialize\n");
820 return false;
821 }
822
823 groupObj = dvmGetMainThreadGroup();
824 if (groupObj == NULL)
825 return false;
826
827 /*
828 * Allocate and construct a Thread with the internal-creation
829 * constructor.
830 */
831 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
832 if (threadObj == NULL) {
833 LOGE("unable to allocate main thread object\n");
834 return false;
835 }
836 dvmReleaseTrackedAlloc(threadObj, NULL);
837
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700838 threadNameStr = dvmCreateStringFromCstr("main");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800839 if (threadNameStr == NULL)
840 return false;
841 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
842
843 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
844 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
845 assert(init != NULL);
846 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
847 THREAD_NORM_PRIORITY, false);
848 if (dvmCheckException(thread)) {
849 LOGE("exception thrown while constructing main thread object\n");
850 return false;
851 }
852
853 /*
854 * Allocate and construct a VMThread.
855 */
856 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
857 if (vmThreadObj == NULL) {
858 LOGE("unable to allocate main vmthread object\n");
859 return false;
860 }
861 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
862
863 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
864 "(Ljava/lang/Thread;)V");
865 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
866 if (dvmCheckException(thread)) {
867 LOGE("exception thrown while constructing main vmthread object\n");
868 return false;
869 }
870
871 /* set the VMThread.vmData field to our Thread struct */
872 assert(gDvm.offJavaLangVMThread_vmData != 0);
873 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
874
875 /*
876 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700877 * Threads will see that this Thread is running (at least, they would,
878 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800879 */
880 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
881 vmThreadObj);
882
883 thread->threadObj = threadObj;
884
885 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700886 * Set the context class loader. This invokes a ClassLoader method,
887 * which could conceivably call Thread.currentThread(), so we want the
888 * Thread to be fully configured before we do this.
889 */
890 Object* systemLoader = dvmGetSystemClassLoader();
891 if (systemLoader == NULL) {
892 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
893 /* keep going */
894 }
895 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
896 "contextClassLoader", "Ljava/lang/ClassLoader;");
897 if (ctxtClassLoaderOffset < 0) {
898 LOGE("Unable to find contextClassLoader field in Thread\n");
899 return false;
900 }
901 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
Andy McFadden50cab512010-10-07 15:11:43 -0700902 dvmReleaseTrackedAlloc(systemLoader, NULL);
Andy McFaddena1a7a342009-05-04 13:29:30 -0700903
904 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800905 * Finish our thread prep.
906 */
907
908 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
909 gDvm.nonDaemonThreadCount++;
910
911 return true;
912}
913
914
915/*
916 * Alloc and initialize a Thread struct.
917 *
Andy McFaddene3346d82010-06-02 15:37:21 -0700918 * Does not create any objects, just stuff on the system (malloc) heap.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800919 */
920static Thread* allocThread(int interpStackSize)
921{
922 Thread* thread;
923 u1* stackBottom;
924
925 thread = (Thread*) calloc(1, sizeof(Thread));
926 if (thread == NULL)
927 return NULL;
928
Jeff Hao97319a82009-08-12 16:57:15 -0700929#if defined(WITH_SELF_VERIFICATION)
930 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
931 return NULL;
932#endif
933
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800934 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
935
936 thread->status = THREAD_INITIALIZING;
937 thread->suspendCount = 0;
938
939#ifdef WITH_ALLOC_LIMITS
940 thread->allocLimit = -1;
941#endif
942
943 /*
944 * Allocate and initialize the interpreted code stack. We essentially
945 * "lose" the alloc pointer, which points at the bottom of the stack,
946 * but we can get it back later because we know how big the stack is.
947 *
948 * The stack must be aligned on a 4-byte boundary.
949 */
950#ifdef MALLOC_INTERP_STACK
951 stackBottom = (u1*) malloc(interpStackSize);
952 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700953#if defined(WITH_SELF_VERIFICATION)
954 dvmSelfVerificationShadowSpaceFree(thread);
955#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800956 free(thread);
957 return NULL;
958 }
959 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
960#else
961 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
962 MAP_PRIVATE | MAP_ANON, -1, 0);
963 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700964#if defined(WITH_SELF_VERIFICATION)
965 dvmSelfVerificationShadowSpaceFree(thread);
966#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800967 free(thread);
968 return NULL;
969 }
970#endif
971
972 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
973 thread->interpStackSize = interpStackSize;
974 thread->interpStackStart = stackBottom + interpStackSize;
975 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
976
977 /* give the thread code a chance to set things up */
978 dvmInitInterpStack(thread, interpStackSize);
979
980 return thread;
981}
982
983/*
984 * Get a meaningful thread ID. At present this only has meaning under Linux,
985 * where getpid() and gettid() sometimes agree and sometimes don't depending
986 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
987 */
988pid_t dvmGetSysThreadId(void)
989{
990#ifdef HAVE_GETTID
991 return gettid();
992#else
993 return getpid();
994#endif
995}
996
997/*
998 * Finish initialization of a Thread struct.
999 *
1000 * This must be called while executing in the new thread, but before the
1001 * thread is added to the thread list.
1002 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001003 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001004 * assignThreadId()).
1005 */
1006static bool prepareThread(Thread* thread)
1007{
1008 assignThreadId(thread);
1009 thread->handle = pthread_self();
1010 thread->systemTid = dvmGetSysThreadId();
1011
1012 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1013 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001014 /*
1015 * If we were called by dvmAttachCurrentThread, the self value is
1016 * already correctly established as "thread".
1017 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001018 setThreadSelf(thread);
1019
1020 LOGV("threadid=%d: interp stack at %p\n",
1021 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1022
1023 /*
1024 * Initialize invokeReq.
1025 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001026 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001027 pthread_cond_init(&thread->invokeReq.cv, NULL);
1028
1029 /*
1030 * Initialize our reference tracking tables.
1031 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001032 * Most threads won't use jniMonitorRefTable, so we clear out the
1033 * structure but don't call the init function (which allocs storage).
1034 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001035#ifdef USE_INDIRECT_REF
1036 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1037 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1038 return false;
1039#else
1040 /*
1041 * The JNI local ref table *must* be fixed-size because we keep pointers
1042 * into the table in our stack frames.
1043 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001044 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1045 kJniLocalRefMax, kJniLocalRefMax))
1046 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001047#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001048 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1049 kInternalRefDefault, kInternalRefMax))
1050 return false;
1051
1052 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1053
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001054 pthread_cond_init(&thread->waitCond, NULL);
1055 dvmInitMutex(&thread->waitMutex);
1056
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001057 return true;
1058}
1059
1060/*
1061 * Remove a thread from the internal list.
1062 * Clear out the links to make it obvious that the thread is
1063 * no longer on the list. Caller must hold gDvm.threadListLock.
1064 */
1065static void unlinkThread(Thread* thread)
1066{
1067 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1068 if (thread == gDvm.threadList) {
1069 assert(thread->prev == NULL);
1070 gDvm.threadList = thread->next;
1071 } else {
1072 assert(thread->prev != NULL);
1073 thread->prev->next = thread->next;
1074 }
1075 if (thread->next != NULL)
1076 thread->next->prev = thread->prev;
1077 thread->prev = thread->next = NULL;
1078}
1079
1080/*
1081 * Free a Thread struct, and all the stuff allocated within.
1082 */
1083static void freeThread(Thread* thread)
1084{
1085 if (thread == NULL)
1086 return;
1087
1088 /* thread->threadId is zero at this point */
1089 LOGVV("threadid=%d: freeing\n", thread->threadId);
1090
1091 if (thread->interpStackStart != NULL) {
1092 u1* interpStackBottom;
1093
1094 interpStackBottom = thread->interpStackStart;
1095 interpStackBottom -= thread->interpStackSize;
1096#ifdef MALLOC_INTERP_STACK
1097 free(interpStackBottom);
1098#else
1099 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1100 LOGW("munmap(thread stack) failed\n");
1101#endif
1102 }
1103
Andy McFaddend5ab7262009-08-25 07:19:34 -07001104#ifdef USE_INDIRECT_REF
1105 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1106#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001107 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001108#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001109 dvmClearReferenceTable(&thread->internalLocalRefTable);
1110 if (&thread->jniMonitorRefTable.table != NULL)
1111 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1112
Jeff Hao97319a82009-08-12 16:57:15 -07001113#if defined(WITH_SELF_VERIFICATION)
1114 dvmSelfVerificationShadowSpaceFree(thread);
1115#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001116 free(thread);
1117}
1118
1119/*
1120 * Like pthread_self(), but on a Thread*.
1121 */
1122Thread* dvmThreadSelf(void)
1123{
1124 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1125}
1126
1127/*
1128 * Explore our sense of self. Stuffs the thread pointer into TLS.
1129 */
1130static void setThreadSelf(Thread* thread)
1131{
1132 int cc;
1133
1134 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1135 if (cc != 0) {
1136 /*
1137 * Sometimes this fails under Bionic with EINVAL during shutdown.
1138 * This can happen if the timing is just right, e.g. a thread
1139 * fails to attach during shutdown, but the "fail" path calls
1140 * here to ensure we clean up after ourselves.
1141 */
1142 if (thread != NULL) {
1143 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1144 dvmAbort(); /* the world is fundamentally hosed */
1145 }
1146 }
1147}
1148
1149/*
1150 * This is associated with the pthreadKeySelf key. It's called by the
1151 * pthread library when a thread is exiting and the "self" pointer in TLS
1152 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001153 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001154 *
1155 * This is mainly of use to ensure that we don't leak resources if, for
1156 * example, a thread attaches itself to us with AttachCurrentThread and
1157 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001158 *
1159 * We could do the detach here instead of aborting, but this will lead to
1160 * portability problems. Other implementations do not do this check and
1161 * will simply be unaware that the thread has exited, leading to resource
1162 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1163 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001164 *
1165 * Because some implementations may want to use the pthread destructor
1166 * to initiate the detach, and the ordering of destructors is not defined,
1167 * we want to iterate a couple of times to give those a chance to run.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001168 */
1169static void threadExitCheck(void* arg)
1170{
Andy McFadden909ce242009-12-10 16:38:30 -08001171 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001172
Andy McFadden909ce242009-12-10 16:38:30 -08001173 Thread* self = (Thread*) arg;
1174 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001175
Andy McFadden909ce242009-12-10 16:38:30 -08001176 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1177 self->threadId, arg, self->threadExitCheckCount);
1178
1179 if (self->status == THREAD_ZOMBIE) {
1180 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1181 self->threadId);
1182 return;
1183 }
1184
1185 if (self->threadExitCheckCount < kMaxCount) {
1186 /*
1187 * Spin a couple of times to let other destructors fire.
1188 */
1189 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1190 self->threadId, self->threadExitCheckCount);
1191 self->threadExitCheckCount++;
1192 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1193 if (cc != 0) {
1194 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1195 self->threadId);
1196 dvmAbort();
1197 }
1198 } else {
1199 LOGE("threadid=%d: native thread exited without detaching\n",
1200 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001201 dvmAbort();
1202 }
1203}
1204
1205
1206/*
1207 * Assign the threadId. This needs to be a small integer so that our
1208 * "thin" locks fit in a small number of bits.
1209 *
1210 * We reserve zero for use as an invalid ID.
1211 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001212 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001213 */
1214static void assignThreadId(Thread* thread)
1215{
Carl Shapiro59a93122010-01-26 17:12:51 -08001216 /*
1217 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001218 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1219 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001220 */
1221 int num = dvmAllocBit(gDvm.threadIdMap);
1222 if (num < 0) {
1223 LOGE("Ran out of thread IDs\n");
1224 dvmAbort(); // TODO: make this a non-fatal error result
1225 }
1226
Carl Shapiro59a93122010-01-26 17:12:51 -08001227 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001228
1229 assert(thread->threadId != 0);
1230 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1231}
1232
1233/*
1234 * Give back the thread ID.
1235 */
1236static void releaseThreadId(Thread* thread)
1237{
1238 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001239 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001240 thread->threadId = 0;
1241}
1242
1243
1244/*
1245 * Add a stack frame that makes it look like the native code in the main
1246 * thread was originally invoked from interpreted code. This gives us a
1247 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1248 * VM begins by executing "main" in a class, so in a way this brings us
1249 * closer to the spec.
1250 */
1251static bool createFakeEntryFrame(Thread* thread)
1252{
1253 assert(thread->threadId == kMainThreadId); // main thread only
1254
1255 /* find the method on first use */
1256 if (gDvm.methFakeNativeEntry == NULL) {
1257 ClassObject* nativeStart;
1258 Method* mainMeth;
1259
1260 nativeStart = dvmFindSystemClassNoInit(
1261 "Ldalvik/system/NativeStart;");
1262 if (nativeStart == NULL) {
1263 LOGE("Unable to find dalvik.system.NativeStart class\n");
1264 return false;
1265 }
1266
1267 /*
1268 * Because we are creating a frame that represents application code, we
1269 * want to stuff the application class loader into the method's class
1270 * loader field, even though we're using the system class loader to
1271 * load it. This makes life easier over in JNI FindClass (though it
1272 * could bite us in other ways).
1273 *
1274 * Unfortunately this is occurring too early in the initialization,
1275 * of necessity coming before JNI is initialized, and we're not quite
1276 * ready to set up the application class loader.
1277 *
1278 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1279 * and check it in FindClass. The method is private so nobody else
1280 * can call it.
1281 */
1282 //nativeStart->classLoader = dvmGetSystemClassLoader();
1283
1284 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1285 "main", "([Ljava/lang/String;)V");
1286 if (mainMeth == NULL) {
1287 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1288 return false;
1289 }
1290
1291 gDvm.methFakeNativeEntry = mainMeth;
1292 }
1293
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001294 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1295 return false;
1296
1297 /*
1298 * Null out the "String[] args" argument.
1299 */
1300 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1301 u4* framePtr = (u4*) thread->curFrame;
1302 framePtr[0] = 0;
1303
1304 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001305}
1306
1307
1308/*
1309 * Add a stack frame that makes it look like the native thread has been
1310 * executing interpreted code. This gives us a place to hang JNI local
1311 * references.
1312 */
1313static bool createFakeRunFrame(Thread* thread)
1314{
1315 ClassObject* nativeStart;
1316 Method* runMeth;
1317
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001318 /*
1319 * TODO: cache this result so we don't have to dig for it every time
1320 * somebody attaches a thread to the VM. Also consider changing this
1321 * to a static method so we don't have a null "this" pointer in the
1322 * "ins" on the stack. (Does it really need to look like a Runnable?)
1323 */
1324 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001325 if (nativeStart == NULL) {
1326 LOGE("Unable to find dalvik.system.NativeStart class\n");
1327 return false;
1328 }
1329
1330 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1331 if (runMeth == NULL) {
1332 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1333 return false;
1334 }
1335
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001336 if (!dvmPushJNIFrame(thread, runMeth))
1337 return false;
1338
1339 /*
1340 * Provide a NULL 'this' argument. The method we've put at the top of
1341 * the stack looks like a virtual call to run() in a Runnable class.
1342 * (If we declared the method static, it wouldn't take any arguments
1343 * and we wouldn't have to do this.)
1344 */
1345 assert(runMeth->registersSize == 1);
1346 u4* framePtr = (u4*) thread->curFrame;
1347 framePtr[0] = 0;
1348
1349 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001350}
1351
1352/*
1353 * Helper function to set the name of the current thread
1354 */
1355static void setThreadName(const char *threadName)
1356{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001357 int hasAt = 0;
1358 int hasDot = 0;
1359 const char *s = threadName;
1360 while (*s) {
1361 if (*s == '.') hasDot = 1;
1362 else if (*s == '@') hasAt = 1;
1363 s++;
1364 }
1365 int len = s - threadName;
1366 if (len < 15 || hasAt || !hasDot) {
1367 s = threadName;
1368 } else {
1369 s = threadName + len - 15;
1370 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001371#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001372 /* pthread_setname_np fails rather than truncating long strings */
1373 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1374 strncpy(buf, s, sizeof(buf)-1);
1375 buf[sizeof(buf)-1] = '\0';
1376 int err = pthread_setname_np(pthread_self(), buf);
1377 if (err != 0) {
1378 LOGW("Unable to set the name of current thread to '%s': %s\n",
1379 buf, strerror(err));
1380 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001381#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001382 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001383#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001384 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001385#endif
1386}
1387
1388/*
1389 * Create a thread as a result of java.lang.Thread.start().
1390 *
1391 * We do have to worry about some concurrency problems, e.g. programs
1392 * that try to call Thread.start() on the same object from multiple threads.
1393 * (This will fail for all but one, but we have to make sure that it succeeds
1394 * for exactly one.)
1395 *
1396 * Some of the complexity here arises from our desire to mimic the
1397 * Thread vs. VMThread class decomposition we inherited. We've been given
1398 * a Thread, and now we need to create a VMThread and then populate both
1399 * objects. We also need to create one of our internal Thread objects.
1400 *
1401 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001402 *
1403 * The "threadObj" reference must be pinned by the caller to prevent the GC
1404 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001405 */
1406bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1407{
1408 pthread_attr_t threadAttr;
1409 pthread_t threadHandle;
1410 Thread* self;
1411 Thread* newThread = NULL;
1412 Object* vmThreadObj = NULL;
1413 int stackSize;
1414
1415 assert(threadObj != NULL);
1416
1417 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001418 // Allow the sampling profiler thread. We shut it down before forking.
1419 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1420 gDvm.offJavaLangThread_name);
1421 char* threadName = dvmCreateCstrFromString(nameStr);
1422 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1423 free(threadName);
1424 if (!profilerThread) {
1425 dvmThrowException("Ljava/lang/IllegalStateException;",
1426 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001427
Bob Lee9dc72a32009-09-04 18:28:16 -07001428 goto fail;
1429 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001430 }
1431
1432 self = dvmThreadSelf();
1433 if (reqStackSize == 0)
1434 stackSize = gDvm.stackSize;
1435 else if (reqStackSize < kMinStackSize)
1436 stackSize = kMinStackSize;
1437 else if (reqStackSize > kMaxStackSize)
1438 stackSize = kMaxStackSize;
1439 else
1440 stackSize = reqStackSize;
1441
1442 pthread_attr_init(&threadAttr);
1443 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1444
1445 /*
1446 * To minimize the time spent in the critical section, we allocate the
1447 * vmThread object here.
1448 */
1449 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1450 if (vmThreadObj == NULL)
1451 goto fail;
1452
1453 newThread = allocThread(stackSize);
1454 if (newThread == NULL)
1455 goto fail;
1456 newThread->threadObj = threadObj;
1457
1458 assert(newThread->status == THREAD_INITIALIZING);
1459
1460 /*
1461 * We need to lock out other threads while we test and set the
1462 * "vmThread" field in java.lang.Thread, because we use that to determine
1463 * if this thread has been started before. We use the thread list lock
1464 * because it's handy and we're going to need to grab it again soon
1465 * anyway.
1466 */
1467 dvmLockThreadList(self);
1468
1469 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1470 dvmUnlockThreadList();
1471 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1472 "thread has already been started");
1473 goto fail;
1474 }
1475
1476 /*
1477 * There are actually three data structures: Thread (object), VMThread
1478 * (object), and Thread (C struct). All of them point to at least one
1479 * other.
1480 *
1481 * As soon as "VMThread.vmData" is assigned, other threads can start
1482 * making calls into us (e.g. setPriority).
1483 */
1484 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1485 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1486
1487 /*
1488 * Thread creation might take a while, so release the lock.
1489 */
1490 dvmUnlockThreadList();
1491
Carl Shapiro5617ad32010-07-02 10:50:57 -07001492 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1493 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001494 newThread);
1495 oldStatus = dvmChangeStatus(self, oldStatus);
1496
1497 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001498 /*
1499 * Failure generally indicates that we have exceeded system
1500 * resource limits. VirtualMachineError is probably too severe,
1501 * so use OutOfMemoryError.
1502 */
1503 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1504
1505 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1506
1507 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1508 "thread creation failed");
1509 goto fail;
1510 }
1511
1512 /*
1513 * We need to wait for the thread to start. Otherwise, depending on
1514 * the whims of the OS scheduler, we could return and the code in our
1515 * thread could try to do operations on the new thread before it had
1516 * finished starting.
1517 *
1518 * The new thread will lock the thread list, change its state to
1519 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1520 * on gDvm.threadStartCond (which uses the thread list lock). This
1521 * thread (the parent) will either see that the thread is already ready
1522 * after we grab the thread list lock, or will be awakened from the
1523 * condition variable on the broadcast.
1524 *
1525 * We don't want to stall the rest of the VM while the new thread
1526 * starts, which can happen if the GC wakes up at the wrong moment.
1527 * So, we change our own status to VMWAIT, and self-suspend if
1528 * necessary after we finish adding the new thread.
1529 *
1530 *
1531 * We have to deal with an odd race with the GC/debugger suspension
1532 * mechanism when creating a new thread. The information about whether
1533 * or not a thread should be suspended is contained entirely within
1534 * the Thread struct; this is usually cleaner to deal with than having
1535 * one or more globally-visible suspension flags. The trouble is that
1536 * we could create the thread while the VM is trying to suspend all
1537 * threads. The suspend-count won't be nonzero for the new thread,
1538 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1539 *
1540 * The easiest way to deal with this is to prevent the new thread from
1541 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001542 * following (correct) sequence of events for a "badly timed" GC
1543 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001544 *
1545 * - call pthread_create()
1546 * - lock thread list
1547 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1548 * - sleep on condition var (mutex = thread list lock) until child starts
1549 * + GC triggered by another thread
1550 * + thread list locked; suspend counts updated; thread list unlocked
1551 * + loop waiting for all runnable threads to suspend
1552 * + success, start GC
1553 * o child thread wakes, signals condition var to wake parent
1554 * o child waits for parent ack on condition variable
1555 * - we wake up, locking thread list
1556 * - add child to thread list
1557 * - unlock thread list
1558 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1559 * + GC finishes; all threads in thread list are resumed
1560 * - lock thread list
1561 * - set child to THREAD_VMWAIT, and signal it to start
1562 * - unlock thread list
1563 * o child resumes
1564 * o child changes state to THREAD_RUNNING
1565 *
1566 * The above shows the GC starting up during thread creation, but if
1567 * it starts anywhere after VMThread.create() is called it will
1568 * produce the same series of events.
1569 *
1570 * Once the child is in the thread list, it will be suspended and
1571 * resumed like any other thread. In the above scenario the resume-all
1572 * code will try to resume the new thread, which was never actually
1573 * suspended, and try to decrement the child's thread suspend count to -1.
1574 * We can catch this in the resume-all code.
1575 *
1576 * Bouncing back and forth between threads like this adds a small amount
1577 * of scheduler overhead to thread startup.
1578 *
1579 * One alternative to having the child wait for the parent would be
1580 * to have the child inherit the parents' suspension count. This
1581 * would work for a GC, since we can safely assume that the parent
1582 * thread didn't cause it, but we must only do so if the parent suspension
1583 * was caused by a suspend-all. If the parent was being asked to
1584 * suspend singly by the debugger, the child should not inherit the value.
1585 *
1586 * We could also have a global "new thread suspend count" that gets
1587 * picked up by new threads before changing state to THREAD_RUNNING.
1588 * This would be protected by the thread list lock and set by a
1589 * suspend-all.
1590 */
1591 dvmLockThreadList(self);
1592 assert(self->status == THREAD_RUNNING);
1593 self->status = THREAD_VMWAIT;
1594 while (newThread->status != THREAD_STARTING)
1595 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1596
1597 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1598 newThread->next = gDvm.threadList->next;
1599 if (newThread->next != NULL)
1600 newThread->next->prev = newThread;
1601 newThread->prev = gDvm.threadList;
1602 gDvm.threadList->next = newThread;
1603
1604 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1605 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1606
1607 dvmUnlockThreadList();
1608
1609 /* change status back to RUNNING, self-suspending if necessary */
1610 dvmChangeStatus(self, THREAD_RUNNING);
1611
1612 /*
1613 * Tell the new thread to start.
1614 *
1615 * We must hold the thread list lock before messing with another thread.
1616 * In the general case we would also need to verify that newThread was
1617 * still in the thread list, but in our case the thread has not started
1618 * executing user code and therefore has not had a chance to exit.
1619 *
1620 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1621 * comes with a suspend-pending check.
1622 */
1623 dvmLockThreadList(self);
1624
1625 assert(newThread->status == THREAD_STARTING);
1626 newThread->status = THREAD_VMWAIT;
1627 pthread_cond_broadcast(&gDvm.threadStartCond);
1628
1629 dvmUnlockThreadList();
1630
1631 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1632 return true;
1633
1634fail:
1635 freeThread(newThread);
1636 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1637 return false;
1638}
1639
1640/*
1641 * pthread entry function for threads started from interpreted code.
1642 */
1643static void* interpThreadStart(void* arg)
1644{
1645 Thread* self = (Thread*) arg;
1646
1647 char *threadName = dvmGetThreadName(self);
1648 setThreadName(threadName);
1649 free(threadName);
1650
1651 /*
1652 * Finish initializing the Thread struct.
1653 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001654 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001655 prepareThread(self);
1656
1657 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1658
1659 /*
1660 * Change our status and wake our parent, who will add us to the
1661 * thread list and advance our state to VMWAIT.
1662 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001663 self->status = THREAD_STARTING;
1664 pthread_cond_broadcast(&gDvm.threadStartCond);
1665
1666 /*
1667 * Wait until the parent says we can go. Assuming there wasn't a
1668 * suspend pending, this will happen immediately. When it completes,
1669 * we're full-fledged citizens of the VM.
1670 *
1671 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1672 * because the pthread_cond_wait below needs to reacquire a lock that
1673 * suspend-all is also interested in. If we get unlucky, the parent could
1674 * change us to THREAD_RUNNING, then a GC could start before we get
1675 * signaled, and suspend-all will grab the thread list lock and then
1676 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1677 * trying to get the lock.
1678 */
1679 while (self->status != THREAD_VMWAIT)
1680 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1681
1682 dvmUnlockThreadList();
1683
1684 /*
1685 * Add a JNI context.
1686 */
1687 self->jniEnv = dvmCreateJNIEnv(self);
1688
1689 /*
1690 * Change our state so the GC will wait for us from now on. If a GC is
1691 * in progress this call will suspend us.
1692 */
1693 dvmChangeStatus(self, THREAD_RUNNING);
1694
1695 /*
1696 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001697 * us to suspend ourselves (and others). The thread state may change
1698 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001699 */
1700 if (gDvm.debuggerConnected)
1701 dvmDbgPostThreadStart(self);
1702
1703 /*
1704 * Set the system thread priority according to the Thread object's
1705 * priority level. We don't usually need to do this, because both the
1706 * Thread object and system thread priorities inherit from parents. The
1707 * tricky case is when somebody creates a Thread object, calls
1708 * setPriority(), and then starts the thread. We could manage this with
1709 * a "needs priority update" flag to avoid the redundant call.
1710 */
Andy McFadden4879df92009-08-07 14:49:40 -07001711 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001712 gDvm.offJavaLangThread_priority);
1713 dvmChangeThreadPriority(self, priority);
1714
1715 /*
1716 * Execute the "run" method.
1717 *
1718 * At this point our stack is empty, so somebody who comes looking for
1719 * stack traces right now won't have much to look at. This is normal.
1720 */
1721 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1722 JValue unused;
1723
1724 LOGV("threadid=%d: calling run()\n", self->threadId);
1725 assert(strcmp(run->name, "run") == 0);
1726 dvmCallMethod(self, run, self->threadObj, &unused);
1727 LOGV("threadid=%d: exiting\n", self->threadId);
1728
1729 /*
1730 * Remove the thread from various lists, report its death, and free
1731 * its resources.
1732 */
1733 dvmDetachCurrentThread();
1734
1735 return NULL;
1736}
1737
1738/*
1739 * The current thread is exiting with an uncaught exception. The
1740 * Java programming language allows the application to provide a
1741 * thread-exit-uncaught-exception handler for the VM, for a specific
1742 * Thread, and for all threads in a ThreadGroup.
1743 *
1744 * Version 1.5 added the per-thread handler. We need to call
1745 * "uncaughtException" in the handler object, which is either the
1746 * ThreadGroup object or the Thread-specific handler.
1747 */
1748static void threadExitUncaughtException(Thread* self, Object* group)
1749{
1750 Object* exception;
1751 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001752 Method* uncaughtHandler = NULL;
1753 InstField* threadHandler;
1754
1755 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1756 self->threadId, group);
1757 assert(group != NULL);
1758
1759 /*
1760 * Get a pointer to the exception, then clear out the one in the
1761 * thread. We don't want to have it set when executing interpreted code.
1762 */
1763 exception = dvmGetException(self);
1764 dvmAddTrackedAlloc(exception, self);
1765 dvmClearException(self);
1766
1767 /*
1768 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1769 * else use "group" (which is an instance of UncaughtExceptionHandler).
1770 */
1771 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1772 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1773 if (threadHandler == NULL) {
1774 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1775 goto bail;
1776 }
1777 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1778 if (handlerObj == NULL)
1779 handlerObj = group;
1780
1781 /*
1782 * Find the "uncaughtHandler" field in this object.
1783 */
1784 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1785 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1786
1787 if (uncaughtHandler != NULL) {
1788 //LOGI("+++ calling %s.uncaughtException\n",
1789 // handlerObj->clazz->descriptor);
1790 JValue unused;
1791 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1792 self->threadObj, exception);
1793 } else {
1794 /* restore it and dump a stack trace */
1795 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1796 handlerObj->clazz->descriptor);
1797 dvmSetException(self, exception);
1798 dvmLogExceptionStackTrace();
1799 }
1800
1801bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001802#if defined(WITH_JIT)
1803 /* Remove this thread's suspendCount from global suspendCount sum */
1804 lockThreadSuspendCount();
1805 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1806 unlockThreadSuspendCount();
1807#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001808 dvmReleaseTrackedAlloc(exception, self);
1809}
1810
1811
1812/*
1813 * Create an internal VM thread, for things like JDWP and finalizers.
1814 *
1815 * The easiest way to do this is create a new thread and then use the
1816 * JNI AttachCurrentThread implementation.
1817 *
1818 * This does not return until after the new thread has begun executing.
1819 */
1820bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1821 InternalThreadStart func, void* funcArg)
1822{
1823 InternalStartArgs* pArgs;
1824 Object* systemGroup;
1825 pthread_attr_t threadAttr;
1826 volatile Thread* newThread = NULL;
1827 volatile int createStatus = 0;
1828
1829 systemGroup = dvmGetSystemThreadGroup();
1830 if (systemGroup == NULL)
1831 return false;
1832
1833 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1834 pArgs->func = func;
1835 pArgs->funcArg = funcArg;
1836 pArgs->name = strdup(name); // storage will be owned by new thread
1837 pArgs->group = systemGroup;
1838 pArgs->isDaemon = true;
1839 pArgs->pThread = &newThread;
1840 pArgs->pCreateStatus = &createStatus;
1841
1842 pthread_attr_init(&threadAttr);
1843 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1844
1845 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1846 pArgs) != 0)
1847 {
1848 LOGE("internal thread creation failed\n");
1849 free(pArgs->name);
1850 free(pArgs);
1851 return false;
1852 }
1853
1854 /*
1855 * Wait for the child to start. This gives us an opportunity to make
1856 * sure that the thread started correctly, and allows our caller to
1857 * assume that the thread has started running.
1858 *
1859 * Because we aren't holding a lock across the thread creation, it's
1860 * possible that the child will already have completed its
1861 * initialization. Because the child only adjusts "createStatus" while
1862 * holding the thread list lock, the initial condition on the "while"
1863 * loop will correctly avoid the wait if this occurs.
1864 *
1865 * It's also possible that we'll have to wait for the thread to finish
1866 * being created, and as part of allocating a Thread object it might
1867 * need to initiate a GC. We switch to VMWAIT while we pause.
1868 */
1869 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001870 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001871 dvmLockThreadList(self);
1872 while (createStatus == 0)
1873 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1874
1875 if (newThread == NULL) {
1876 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1877 assert(createStatus < 0);
1878 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1879 dvmUnlockThreadList();
1880 dvmChangeStatus(self, oldStatus);
1881 return false;
1882 }
1883
1884 /* thread could be in any state now (except early init states) */
1885 //assert(newThread->status == THREAD_RUNNING);
1886
1887 dvmUnlockThreadList();
1888 dvmChangeStatus(self, oldStatus);
1889
1890 return true;
1891}
1892
1893/*
1894 * pthread entry function for internally-created threads.
1895 *
1896 * We are expected to free "arg" and its contents. If we're a daemon
1897 * thread, and we get cancelled abruptly when the VM shuts down, the
1898 * storage won't be freed. If this becomes a concern we can make a copy
1899 * on the stack.
1900 */
1901static void* internalThreadStart(void* arg)
1902{
1903 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1904 JavaVMAttachArgs jniArgs;
1905
1906 jniArgs.version = JNI_VERSION_1_2;
1907 jniArgs.name = pArgs->name;
1908 jniArgs.group = pArgs->group;
1909
1910 setThreadName(pArgs->name);
1911
1912 /* use local jniArgs as stack top */
1913 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1914 /*
1915 * Tell the parent of our success.
1916 *
1917 * threadListLock is the mutex for threadStartCond.
1918 */
1919 dvmLockThreadList(dvmThreadSelf());
1920 *pArgs->pCreateStatus = 1;
1921 *pArgs->pThread = dvmThreadSelf();
1922 pthread_cond_broadcast(&gDvm.threadStartCond);
1923 dvmUnlockThreadList();
1924
1925 LOG_THREAD("threadid=%d: internal '%s'\n",
1926 dvmThreadSelf()->threadId, pArgs->name);
1927
1928 /* execute */
1929 (*pArgs->func)(pArgs->funcArg);
1930
1931 /* detach ourselves */
1932 dvmDetachCurrentThread();
1933 } else {
1934 /*
1935 * Tell the parent of our failure. We don't have a Thread struct,
1936 * so we can't be suspended, so we don't need to enter a critical
1937 * section.
1938 */
1939 dvmLockThreadList(dvmThreadSelf());
1940 *pArgs->pCreateStatus = -1;
1941 assert(*pArgs->pThread == NULL);
1942 pthread_cond_broadcast(&gDvm.threadStartCond);
1943 dvmUnlockThreadList();
1944
1945 assert(*pArgs->pThread == NULL);
1946 }
1947
1948 free(pArgs->name);
1949 free(pArgs);
1950 return NULL;
1951}
1952
1953/*
1954 * Attach the current thread to the VM.
1955 *
1956 * Used for internally-created threads and JNI's AttachCurrentThread.
1957 */
1958bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1959{
1960 Thread* self = NULL;
1961 Object* threadObj = NULL;
1962 Object* vmThreadObj = NULL;
1963 StringObject* threadNameStr = NULL;
1964 Method* init;
1965 bool ok, ret;
1966
Andy McFaddene3346d82010-06-02 15:37:21 -07001967 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001968 self = allocThread(gDvm.stackSize);
1969 if (self == NULL)
1970 goto fail;
1971 setThreadSelf(self);
1972
1973 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001974 * Finish our thread prep. We need to do this before adding ourselves
1975 * to the thread list or invoking any interpreted code. prepareThread()
1976 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001977 */
1978 dvmLockThreadList(self);
1979 ok = prepareThread(self);
1980 dvmUnlockThreadList();
1981 if (!ok)
1982 goto fail;
1983
1984 self->jniEnv = dvmCreateJNIEnv(self);
1985 if (self->jniEnv == NULL)
1986 goto fail;
1987
1988 /*
1989 * Create a "fake" JNI frame at the top of the main thread interp stack.
1990 * It isn't really necessary for the internal threads, but it gives
1991 * the debugger something to show. It is essential for the JNI-attached
1992 * threads.
1993 */
1994 if (!createFakeRunFrame(self))
1995 goto fail;
1996
1997 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001998 * The native side of the thread is ready; add it to the list. Once
1999 * it's on the list the thread is visible to the JDWP code and the GC.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002000 */
2001 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
2002
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002003 dvmLockThreadList(self);
2004
2005 self->next = gDvm.threadList->next;
2006 if (self->next != NULL)
2007 self->next->prev = self;
2008 self->prev = gDvm.threadList;
2009 gDvm.threadList->next = self;
2010 if (!isDaemon)
2011 gDvm.nonDaemonThreadCount++;
2012
2013 dvmUnlockThreadList();
2014
2015 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002016 * Switch state from initializing to running.
2017 *
2018 * It's possible that a GC began right before we added ourselves
2019 * to the thread list, and is still going. That means our thread
2020 * suspend count won't reflect the fact that we should be suspended.
2021 * To deal with this, we transition to VMWAIT, pulse the heap lock,
2022 * and then advance to RUNNING. That will ensure that we stall until
2023 * the GC completes.
2024 *
2025 * Once we're in RUNNING, we're like any other thread in the VM (except
2026 * for the lack of an initialized threadObj). We're then free to
2027 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002028 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002029 assert(self->status == THREAD_INITIALIZING);
2030 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002031 dvmLockMutex(&gDvm.gcHeapLock);
2032 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002033 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002034
2035 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002036 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002037 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002038 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2039 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2040 if (threadObj == NULL || vmThreadObj == NULL)
2041 goto fail_unlink;
2042
2043 /*
2044 * This makes threadObj visible to the GC. We still have it in the
2045 * tracked allocation table, so it can't move around on us.
2046 */
2047 self->threadObj = threadObj;
2048 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2049
2050 /*
2051 * Create a string for the thread name.
2052 */
2053 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002054 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002055 if (threadNameStr == NULL) {
2056 assert(dvmCheckException(dvmThreadSelf()));
2057 goto fail_unlink;
2058 }
2059 }
2060
2061 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2062 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2063 if (init == NULL) {
2064 assert(dvmCheckException(self));
2065 goto fail_unlink;
2066 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002067
2068 /*
2069 * Now we're ready to run some interpreted code.
2070 *
2071 * We need to construct the Thread object and set the VMThread field.
2072 * Setting VMThread tells interpreted code that we're alive.
2073 *
2074 * Call the (group, name, priority, daemon) constructor on the Thread.
2075 * This sets the thread's name and adds it to the specified group, and
2076 * provides values for priority and daemon (which are normally inherited
2077 * from the current thread).
2078 */
2079 JValue unused;
2080 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2081 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2082 if (dvmCheckException(self)) {
2083 LOGE("exception thrown while constructing attached thread object\n");
2084 goto fail_unlink;
2085 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002086
2087 /*
2088 * Set the VMThread field, which tells interpreted code that we're alive.
2089 *
2090 * The risk of a thread start collision here is very low; somebody
2091 * would have to be deliberately polling the ThreadGroup list and
2092 * trying to start threads against anything it sees, which would
2093 * generally cause problems for all thread creation. However, for
2094 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002095 *
2096 * TODO: this still has a race, it's just smaller. Not sure this is
2097 * worth putting effort into fixing. Need to hold a lock while
2098 * fiddling with the field, or maybe initialize the Thread object in a
2099 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002100 */
2101 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002102 LOGW("WOW: thread start hijack\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002103 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2104 "thread has already been started");
2105 /* We don't want to free anything associated with the thread
2106 * because someone is obviously interested in it. Just let
2107 * it go and hope it will clean itself up when its finished.
2108 * This case should never happen anyway.
2109 *
2110 * Since we're letting it live, we need to finish setting it up.
2111 * We just have to let the caller know that the intended operation
2112 * has failed.
2113 *
2114 * [ This seems strange -- stepping on the vmThread object that's
2115 * already present seems like a bad idea. TODO: figure this out. ]
2116 */
2117 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002118 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002119 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002120 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002121 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2122
Andy McFaddene3346d82010-06-02 15:37:21 -07002123 /* we can now safely un-pin these */
2124 dvmReleaseTrackedAlloc(threadObj, self);
2125 dvmReleaseTrackedAlloc(vmThreadObj, self);
2126 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002127
2128 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2129 self->threadId, pArgs->name);
2130
2131 /* tell the debugger & DDM */
2132 if (gDvm.debuggerConnected)
2133 dvmDbgPostThreadStart(self);
2134
2135 return ret;
2136
2137fail_unlink:
2138 dvmLockThreadList(self);
2139 unlinkThread(self);
2140 if (!isDaemon)
2141 gDvm.nonDaemonThreadCount--;
2142 dvmUnlockThreadList();
2143 /* fall through to "fail" */
2144fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002145 dvmReleaseTrackedAlloc(threadObj, self);
2146 dvmReleaseTrackedAlloc(vmThreadObj, self);
2147 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002148 if (self != NULL) {
2149 if (self->jniEnv != NULL) {
2150 dvmDestroyJNIEnv(self->jniEnv);
2151 self->jniEnv = NULL;
2152 }
2153 freeThread(self);
2154 }
2155 setThreadSelf(NULL);
2156 return false;
2157}
2158
2159/*
2160 * Detach the thread from the various data structures, notify other threads
2161 * that are waiting to "join" it, and free up all heap-allocated storage.
2162 *
2163 * Used for all threads.
2164 *
2165 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2166 * requires us to enforce this for the DetachCurrentThread call, probably
2167 * because it also says that DetachCurrentThread causes all monitors
2168 * associated with the thread to be released. (Because the stack is empty,
2169 * we only have to worry about explicit JNI calls to MonitorEnter.)
2170 *
2171 * THOUGHT:
2172 * We might want to avoid freeing our internal Thread structure until the
2173 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2174 * get to once the thread shuts down, but there is a small possibility of
2175 * an operation starting in another thread before this thread halts, and
2176 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2177 * We don't want something like Thread.isInterrupted() crawling through
2178 * freed storage. Can do with a Thread finalizer, or by creating a
2179 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2180 * state into that.
2181 */
2182void dvmDetachCurrentThread(void)
2183{
2184 Thread* self = dvmThreadSelf();
2185 Object* vmThread;
2186 Object* group;
2187
2188 /*
2189 * Make sure we're not detaching a thread that's still running. (This
2190 * could happen with an explicit JNI detach call.)
2191 *
2192 * A thread created by interpreted code will finish with a depth of
2193 * zero, while a JNI-attached thread will have the synthetic "stack
2194 * starter" native method at the top.
2195 */
2196 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2197 if (curDepth != 0) {
2198 bool topIsNative = false;
2199
2200 if (curDepth == 1) {
2201 /* not expecting a lingering break frame; just look at curFrame */
2202 assert(!dvmIsBreakFrame(self->curFrame));
2203 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2204 if (dvmIsNativeMethod(ssa->method))
2205 topIsNative = true;
2206 }
2207
2208 if (!topIsNative) {
2209 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2210 curDepth);
2211 dvmDumpThread(self, false);
2212 dvmAbort();
2213 }
2214 }
2215
2216 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2217 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2218
2219 /*
2220 * Release any held monitors. Since there are no interpreted stack
2221 * frames, the only thing left are the monitors held by JNI MonitorEnter
2222 * calls.
2223 */
2224 dvmReleaseJniMonitors(self);
2225
2226 /*
2227 * Do some thread-exit uncaught exception processing if necessary.
2228 */
2229 if (dvmCheckException(self))
2230 threadExitUncaughtException(self, group);
2231
2232 /*
2233 * Remove the thread from the thread group.
2234 */
2235 if (group != NULL) {
2236 Method* removeThread =
2237 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2238 JValue unused;
2239 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2240 }
2241
2242 /*
2243 * Clear the vmThread reference in the Thread object. Interpreted code
2244 * will now see that this Thread is not running. As this may be the
2245 * only reference to the VMThread object that the VM knows about, we
2246 * have to create an internal reference to it first.
2247 */
2248 vmThread = dvmGetFieldObject(self->threadObj,
2249 gDvm.offJavaLangThread_vmThread);
2250 dvmAddTrackedAlloc(vmThread, self);
2251 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2252
2253 /* clear out our struct Thread pointer, since it's going away */
2254 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2255
2256 /*
2257 * Tell the debugger & DDM. This may cause the current thread or all
2258 * threads to suspend.
2259 *
2260 * The JDWP spec is somewhat vague about when this happens, other than
2261 * that it's issued by the dying thread, which may still appear in
2262 * an "all threads" listing.
2263 */
2264 if (gDvm.debuggerConnected)
2265 dvmDbgPostThreadDeath(self);
2266
2267 /*
2268 * Thread.join() is implemented as an Object.wait() on the VMThread
2269 * object. Signal anyone who is waiting.
2270 */
2271 dvmLockObject(self, vmThread);
2272 dvmObjectNotifyAll(self, vmThread);
2273 dvmUnlockObject(self, vmThread);
2274
2275 dvmReleaseTrackedAlloc(vmThread, self);
2276 vmThread = NULL;
2277
2278 /*
2279 * We're done manipulating objects, so it's okay if the GC runs in
2280 * parallel with us from here out. It's important to do this if
2281 * profiling is enabled, since we can wait indefinitely.
2282 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002283 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002284
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002285 /*
2286 * If we're doing method trace profiling, we don't want threads to exit,
2287 * because if they do we'll end up reusing thread IDs. This complicates
2288 * analysis and makes it impossible to have reasonable output in the
2289 * "threads" section of the "key" file.
2290 *
2291 * We need to do this after Thread.join() completes, or other threads
2292 * could get wedged. Since self->threadObj is still valid, the Thread
2293 * object will not get GCed even though we're no longer in the ThreadGroup
2294 * list (which is important since the profiling thread needs to get
2295 * the thread's name).
2296 */
2297 MethodTraceState* traceState = &gDvm.methodTrace;
2298
2299 dvmLockMutex(&traceState->startStopLock);
2300 if (traceState->traceEnabled) {
2301 LOGI("threadid=%d: waiting for method trace to finish\n",
2302 self->threadId);
2303 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002304 dvmWaitCond(&traceState->threadExitCond,
2305 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002306 }
2307 }
2308 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002309
2310 dvmLockThreadList(self);
2311
2312 /*
2313 * Lose the JNI context.
2314 */
2315 dvmDestroyJNIEnv(self->jniEnv);
2316 self->jniEnv = NULL;
2317
2318 self->status = THREAD_ZOMBIE;
2319
2320 /*
2321 * Remove ourselves from the internal thread list.
2322 */
2323 unlinkThread(self);
2324
2325 /*
2326 * If we're the last one standing, signal anybody waiting in
2327 * DestroyJavaVM that it's okay to exit.
2328 */
2329 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2330 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2331
2332 if (gDvm.nonDaemonThreadCount == 0) {
2333 int cc;
2334
2335 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2336 //dvmDumpAllThreads(false);
2337 // cond var guarded by threadListLock, which we already hold
2338 cc = pthread_cond_signal(&gDvm.vmExitCond);
2339 assert(cc == 0);
2340 }
2341 }
2342
2343 LOGV("threadid=%d: bye!\n", self->threadId);
2344 releaseThreadId(self);
2345 dvmUnlockThreadList();
2346
2347 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002348
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002349 freeThread(self);
2350}
2351
2352
2353/*
2354 * Suspend a single thread. Do not use to suspend yourself.
2355 *
2356 * This is used primarily for debugger/DDMS activity. Does not return
2357 * until the thread has suspended or is in a "safe" state (e.g. executing
2358 * native code outside the VM).
2359 *
2360 * The thread list lock should be held before calling here -- it's not
2361 * entirely safe to hang on to a Thread* from another thread otherwise.
2362 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2363 */
2364void dvmSuspendThread(Thread* thread)
2365{
2366 assert(thread != NULL);
2367 assert(thread != dvmThreadSelf());
2368 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2369
2370 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002371 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002372 thread->dbgSuspendCount++;
2373
2374 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2375 thread->threadId, thread->suspendCount);
2376 unlockThreadSuspendCount();
2377
2378 waitForThreadSuspend(dvmThreadSelf(), thread);
2379}
2380
2381/*
2382 * Reduce the suspend count of a thread. If it hits zero, tell it to
2383 * resume.
2384 *
2385 * Used primarily for debugger/DDMS activity. The thread in question
2386 * might have been suspended singly or as part of a suspend-all operation.
2387 *
2388 * The thread list lock should be held before calling here -- it's not
2389 * entirely safe to hang on to a Thread* from another thread otherwise.
2390 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2391 */
2392void dvmResumeThread(Thread* thread)
2393{
2394 assert(thread != NULL);
2395 assert(thread != dvmThreadSelf());
2396 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2397
2398 lockThreadSuspendCount();
2399 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002400 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002401 thread->dbgSuspendCount--;
2402 } else {
2403 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2404 thread->threadId);
2405 }
2406
2407 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2408 thread->threadId, thread->suspendCount);
2409
2410 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002411 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002412 }
2413
2414 unlockThreadSuspendCount();
2415}
2416
2417/*
2418 * Suspend yourself, as a result of debugger activity.
2419 */
2420void dvmSuspendSelf(bool jdwpActivity)
2421{
2422 Thread* self = dvmThreadSelf();
2423
Andy McFadden6dce9962010-08-23 16:45:24 -07002424 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002425 assert(gDvm.jdwpState != NULL);
2426 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2427 assert(false);
2428 return;
2429 }
2430
2431 /*
2432 * Collisions with other suspends aren't really interesting. We want
2433 * to ensure that we're the only one fiddling with the suspend count
2434 * though.
2435 */
2436 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002437 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002438 self->dbgSuspendCount++;
2439
2440 /*
2441 * Suspend ourselves.
2442 */
2443 assert(self->suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002444 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002445 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2446
2447 /*
2448 * Tell JDWP that we've completed suspension. The JDWP thread can't
2449 * tell us to resume before we're fully asleep because we hold the
2450 * suspend count lock.
2451 *
2452 * If we got here via waitForDebugger(), don't do this part.
2453 */
2454 if (jdwpActivity) {
2455 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2456 // self->threadId, (int) self->handle);
2457 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2458 }
2459
2460 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002461 dvmWaitCond(&gDvm.threadSuspendCountCond,
2462 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002463 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002464 /*
2465 * The condition was signaled but we're still suspended. This
2466 * can happen if the debugger lets go while a SIGQUIT thread
2467 * dump event is pending (assuming SignalCatcher was resumed for
2468 * just long enough to try to grab the thread-suspend lock).
2469 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002470 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
2471 self->threadId, self->suspendCount, self->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002472 }
2473 }
2474 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002475 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002476 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2477 self->threadId, self->status);
2478
2479 unlockThreadSuspendCount();
2480}
2481
2482
2483#ifdef HAVE_GLIBC
2484# define NUM_FRAMES 20
2485# include <execinfo.h>
2486/*
2487 * glibc-only stack dump function. Requires link with "--export-dynamic".
2488 *
2489 * TODO: move this into libs/cutils and make it work for all platforms.
2490 */
2491static void printBackTrace(void)
2492{
2493 void* array[NUM_FRAMES];
2494 size_t size;
2495 char** strings;
2496 size_t i;
2497
2498 size = backtrace(array, NUM_FRAMES);
2499 strings = backtrace_symbols(array, size);
2500
2501 LOGW("Obtained %zd stack frames.\n", size);
2502
2503 for (i = 0; i < size; i++)
2504 LOGW("%s\n", strings[i]);
2505
2506 free(strings);
2507}
2508#else
2509static void printBackTrace(void) {}
2510#endif
2511
2512/*
2513 * Dump the state of the current thread and that of another thread that
2514 * we think is wedged.
2515 */
2516static void dumpWedgedThread(Thread* thread)
2517{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002518 dvmDumpThread(dvmThreadSelf(), false);
2519 printBackTrace();
2520
2521 // dumping a running thread is risky, but could be useful
2522 dvmDumpThread(thread, true);
2523
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002524 // stop now and get a core dump
2525 //abort();
2526}
2527
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002528/*
2529 * If the thread is running at below-normal priority, temporarily elevate
2530 * it to "normal".
2531 *
2532 * Returns zero if no changes were made. Otherwise, returns bit flags
2533 * indicating what was changed, storing the previous values in the
2534 * provided locations.
2535 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002536int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002537 SchedPolicy* pSavedThreadPolicy)
2538{
2539 errno = 0;
2540 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2541 if (errno != 0) {
2542 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2543 thread->threadId, thread->systemTid);
2544 return 0;
2545 }
2546 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2547 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2548 thread->threadId, thread->systemTid);
2549 return 0;
2550 }
2551
2552 int changeFlags = 0;
2553
2554 /*
2555 * Change the priority if we're in the background group.
2556 */
2557 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2558 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2559 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2560 } else {
2561 changeFlags |= kChangedPolicy;
2562 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2563 thread->systemTid, *pSavedThreadPolicy);
2564 }
2565 }
2566
2567 /*
2568 * getpriority() returns the "nice" value, so larger numbers indicate
2569 * lower priority, with 0 being normal.
2570 */
2571 if (*pSavedThreadPrio > 0) {
2572 const int kHigher = 0;
2573 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2574 LOGW("Couldn't raise priority on tid %d to %d\n",
2575 thread->systemTid, kHigher);
2576 } else {
2577 changeFlags |= kChangedPriority;
2578 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2579 thread->systemTid, *pSavedThreadPrio, kHigher);
2580 }
2581 }
2582
2583 return changeFlags;
2584}
2585
2586/*
2587 * Reset the priority values for the thread in question.
2588 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002589void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002590 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2591{
2592 if ((changeFlags & kChangedPolicy) != 0) {
2593 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2594 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2595 thread->systemTid, savedThreadPolicy);
2596 } else {
2597 LOGD("Restored policy of %d to %d\n",
2598 thread->systemTid, savedThreadPolicy);
2599 }
2600 }
2601
2602 if ((changeFlags & kChangedPriority) != 0) {
2603 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2604 {
2605 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2606 thread->systemTid, savedThreadPrio);
2607 } else {
2608 LOGD("Restored priority on %d to %d\n",
2609 thread->systemTid, savedThreadPrio);
2610 }
2611 }
2612}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002613
2614/*
2615 * Wait for another thread to see the pending suspension and stop running.
2616 * It can either suspend itself or go into a non-running state such as
2617 * VMWAIT or NATIVE in which it cannot interact with the GC.
2618 *
2619 * If we're running at a higher priority, sched_yield() may not do anything,
2620 * so we need to sleep for "long enough" to guarantee that the other
2621 * thread has a chance to finish what it's doing. Sleeping for too short
2622 * a period (e.g. less than the resolution of the sleep clock) might cause
2623 * the scheduler to return immediately, so we want to start with a
2624 * "reasonable" value and expand.
2625 *
2626 * This does not return until the other thread has stopped running.
2627 * Eventually we time out and the VM aborts.
2628 *
2629 * This does not try to detect the situation where two threads are
2630 * waiting for each other to suspend. In normal use this is part of a
2631 * suspend-all, which implies that the suspend-all lock is held, or as
2632 * part of a debugger action in which the JDWP thread is always the one
2633 * doing the suspending. (We may need to re-evaluate this now that
2634 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2635 *
2636 * TODO: track basic stats about time required to suspend VM.
2637 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002638#define FIRST_SLEEP (250*1000) /* 0.25s */
2639#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002640static void waitForThreadSuspend(Thread* self, Thread* thread)
2641{
2642 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002643 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002644 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002645 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002646 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002647 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002648
2649 int sleepIter = 0;
2650 int retryCount = 0;
2651 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002652 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002653
Andy McFadden6dce9962010-08-23 16:45:24 -07002654 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002655 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002656 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002657 if (firstStartWhen == 0) // first iteration of first attempt
2658 firstStartWhen = startWhen;
2659
2660 /*
2661 * After waiting for a bit, check to see if the target thread is
2662 * running at a reduced priority. If so, bump it up temporarily
2663 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002664 */
2665 if (retryCount == 2) {
2666 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002667 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002668 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002669 }
2670 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002671
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002672#if defined (WITH_JIT)
2673 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002674 * If we're still waiting after the first timeout, unchain all
2675 * translations iff:
2676 * 1) There are new chains formed since the last unchain
2677 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002678 */
Ben Cheng6999d842010-01-26 16:46:15 -08002679 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2680 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002681 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002682 dvmJitUnchainAll();
2683 }
2684#endif
2685
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002686 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002687 * Sleep briefly. The iterative sleep call returns false if we've
2688 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002689 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002690 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002691 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002692 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002693 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002694 thread->threadId, priChangeFlags);
2695 if (retryCount > 1) {
2696 /* stack trace logging is slow; skip on first iter */
2697 dumpWedgedThread(thread);
2698 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002699 complained = true;
2700 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002701
2702 // keep going; could be slow due to valgrind
2703 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002704 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002705
2706 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002707 LOGE("Fatal spin-on-suspend, dumping threads\n");
2708 dvmDumpAllThreads(false);
2709
2710 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002711 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2712 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002713
2714 /* try to get a debuggerd dump from the spinning thread */
2715 dvmNukeThread(thread);
2716 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002717 dvmAbort();
2718 }
2719 }
2720 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002721
2722 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002723 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2724 self->threadId,
2725 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002726 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2727 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002728 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002729 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002730 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002731 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002732}
2733
2734/*
2735 * Suspend all threads except the current one. This is used by the GC,
2736 * the debugger, and by any thread that hits a "suspend all threads"
2737 * debugger event (e.g. breakpoint or exception).
2738 *
2739 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2740 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2741 * create objects and even execute arbitrary code. The "why" argument
2742 * allows the caller to say why the suspension is taking place.
2743 *
2744 * This can be called when a global suspend has already happened, due to
2745 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2746 * doesn't work.
2747 *
2748 * DO NOT grab any locks before calling here. We grab & release the thread
2749 * lock and suspend lock here (and we're not using recursive threads), and
2750 * we might have to self-suspend if somebody else beats us here.
2751 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002752 * We know the current thread is in the thread list, because we attach the
2753 * thread before doing anything that could cause VM suspension (like object
2754 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002755 */
2756void dvmSuspendAllThreads(SuspendCause why)
2757{
2758 Thread* self = dvmThreadSelf();
2759 Thread* thread;
2760
2761 assert(why != 0);
2762
2763 /*
2764 * Start by grabbing the thread suspend lock. If we can't get it, most
2765 * likely somebody else is in the process of performing a suspend or
2766 * resume, so lockThreadSuspend() will cause us to self-suspend.
2767 *
2768 * We keep the lock until all other threads are suspended.
2769 */
2770 lockThreadSuspend("susp-all", why);
2771
2772 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2773
2774 /*
2775 * This is possible if the current thread was in VMWAIT mode when a
2776 * suspend-all happened, and then decided to do its own suspend-all.
2777 * This can happen when a couple of threads have simultaneous events
2778 * of interest to the debugger.
2779 */
2780 //assert(self->suspendCount == 0);
2781
2782 /*
2783 * Increment everybody's suspend count (except our own).
2784 */
2785 dvmLockThreadList(self);
2786
2787 lockThreadSuspendCount();
2788 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2789 if (thread == self)
2790 continue;
2791
2792 /* debugger events don't suspend JDWP thread */
2793 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2794 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2795 continue;
2796
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002797 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002798 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2799 thread->dbgSuspendCount++;
2800 }
2801 unlockThreadSuspendCount();
2802
2803 /*
2804 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2805 * indicate the code is either running natively or sleeping quietly.
2806 * Any attempt to transition back to THREAD_RUNNING will cause a check
2807 * for suspension, so it should be impossible for anything to execute
2808 * interpreted code or modify objects (assuming native code plays nicely).
2809 *
2810 * It's also okay if the thread transitions to a non-RUNNING state.
2811 *
2812 * Note we released the threadSuspendCountLock before getting here,
2813 * so if another thread is fiddling with its suspend count (perhaps
2814 * self-suspending for the debugger) it won't block while we're waiting
2815 * in here.
2816 */
2817 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2818 if (thread == self)
2819 continue;
2820
2821 /* debugger events don't suspend JDWP thread */
2822 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2823 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2824 continue;
2825
2826 /* wait for the other thread to see the pending suspend */
2827 waitForThreadSuspend(self, thread);
2828
Andy McFadden6dce9962010-08-23 16:45:24 -07002829 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002830 self->threadId,
2831 thread->threadId, thread->status, thread->suspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07002832 thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002833 }
2834
2835 dvmUnlockThreadList();
2836 unlockThreadSuspend();
2837
2838 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2839}
2840
2841/*
2842 * Resume all threads that are currently suspended.
2843 *
2844 * The "why" must match with the previous suspend.
2845 */
2846void dvmResumeAllThreads(SuspendCause why)
2847{
2848 Thread* self = dvmThreadSelf();
2849 Thread* thread;
2850 int cc;
2851
2852 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2853 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2854
2855 /*
2856 * Decrement the suspend counts for all threads. No need for atomic
2857 * writes, since nobody should be moving until we decrement the count.
2858 * We do need to hold the thread list because of JNI attaches.
2859 */
2860 dvmLockThreadList(self);
2861 lockThreadSuspendCount();
2862 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2863 if (thread == self)
2864 continue;
2865
2866 /* debugger events don't suspend JDWP thread */
2867 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2868 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002869 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002870 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002871 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002872
2873 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002874 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002875 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2876 thread->dbgSuspendCount--;
2877 } else {
2878 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2879 thread->threadId);
2880 }
2881 }
2882 unlockThreadSuspendCount();
2883 dvmUnlockThreadList();
2884
2885 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002886 * In some ways it makes sense to continue to hold the thread-suspend
2887 * lock while we issue the wakeup broadcast. It allows us to complete
2888 * one operation before moving on to the next, which simplifies the
2889 * thread activity debug traces.
2890 *
2891 * This approach caused us some difficulty under Linux, because the
2892 * condition variable broadcast not only made the threads runnable,
2893 * but actually caused them to execute, and it was a while before
2894 * the thread performing the wakeup had an opportunity to release the
2895 * thread-suspend lock.
2896 *
2897 * This is a problem because, when a thread tries to acquire that
2898 * lock, it times out after 3 seconds. If at some point the thread
2899 * is told to suspend, the clock resets; but since the VM is still
2900 * theoretically mid-resume, there's no suspend pending. If, for
2901 * example, the GC was waking threads up while the SIGQUIT handler
2902 * was trying to acquire the lock, we would occasionally time out on
2903 * a busy system and SignalCatcher would abort.
2904 *
2905 * We now perform the unlock before the wakeup broadcast. The next
2906 * suspend can't actually start until the broadcast completes and
2907 * returns, because we're holding the thread-suspend-count lock, but the
2908 * suspending thread is now able to make progress and we avoid the abort.
2909 *
2910 * (Technically there is a narrow window between when we release
2911 * the thread-suspend lock and grab the thread-suspend-count lock.
2912 * This could cause us to send a broadcast to threads with nonzero
2913 * suspend counts, but this is expected and they'll all just fall
2914 * right back to sleep. It's probably safe to grab the suspend-count
2915 * lock before releasing thread-suspend, since we're still following
2916 * the correct order of acquisition, but it feels weird.)
2917 */
2918
2919 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2920 unlockThreadSuspend();
2921
2922 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002923 * Broadcast a notification to all suspended threads, some or all of
2924 * which may choose to wake up. No need to wait for them.
2925 */
2926 lockThreadSuspendCount();
2927 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2928 assert(cc == 0);
2929 unlockThreadSuspendCount();
2930
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002931 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2932}
2933
2934/*
2935 * Undo any debugger suspensions. This is called when the debugger
2936 * disconnects.
2937 */
2938void dvmUndoDebuggerSuspensions(void)
2939{
2940 Thread* self = dvmThreadSelf();
2941 Thread* thread;
2942 int cc;
2943
2944 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2945 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2946
2947 /*
2948 * Decrement the suspend counts for all threads. No need for atomic
2949 * writes, since nobody should be moving until we decrement the count.
2950 * We do need to hold the thread list because of JNI attaches.
2951 */
2952 dvmLockThreadList(self);
2953 lockThreadSuspendCount();
2954 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2955 if (thread == self)
2956 continue;
2957
2958 /* debugger events don't suspend JDWP thread */
2959 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2960 assert(thread->dbgSuspendCount == 0);
2961 continue;
2962 }
2963
2964 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002965 dvmAddToThreadSuspendCount(&thread->suspendCount,
2966 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002967 thread->dbgSuspendCount = 0;
2968 }
2969 unlockThreadSuspendCount();
2970 dvmUnlockThreadList();
2971
2972 /*
2973 * Broadcast a notification to all suspended threads, some or all of
2974 * which may choose to wake up. No need to wait for them.
2975 */
2976 lockThreadSuspendCount();
2977 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2978 assert(cc == 0);
2979 unlockThreadSuspendCount();
2980
2981 unlockThreadSuspend();
2982
2983 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2984}
2985
2986/*
2987 * Determine if a thread is suspended.
2988 *
2989 * As with all operations on foreign threads, the caller should hold
2990 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002991 *
2992 * If the thread is suspending or waking, these fields could be changing
2993 * out from under us (or the thread could change state right after we
2994 * examine it), making this generally unreliable. This is chiefly
2995 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002996 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002997bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002998{
2999 /*
3000 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07003001 * (1) Running happily. status is RUNNING, suspendCount is zero.
3002 * Return "false".
3003 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
3004 * Return "false".
3005 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003006 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07003007 * (4) Waking up. suspendCount is zero, status is SUSPENDED
3008 * Return "false" (since it could change out from under us, unless
3009 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003010 */
3011
Andy McFadden6dce9962010-08-23 16:45:24 -07003012 return (thread->suspendCount != 0 && thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003013}
3014
3015/*
3016 * Wait until another thread self-suspends. This is specifically for
3017 * synchronization between the JDWP thread and a thread that has decided
3018 * to suspend itself after sending an event to the debugger.
3019 *
3020 * Threads that encounter "suspend all" events work as well -- the thread
3021 * in question suspends everybody else and then itself.
3022 *
3023 * We can't hold a thread lock here or in the caller, because we could
3024 * get here just before the to-be-waited-for-thread issues a "suspend all".
3025 * There's an opportunity for badness if the thread we're waiting for exits
3026 * and gets cleaned up, but since the thread in question is processing a
3027 * debugger event, that's not really a possibility. (To avoid deadlock,
3028 * it's important that we not be in THREAD_RUNNING while we wait.)
3029 */
3030void dvmWaitForSuspend(Thread* thread)
3031{
3032 Thread* self = dvmThreadSelf();
3033
3034 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3035 self->threadId, thread->threadId);
3036
3037 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3038 assert(thread != self);
3039 assert(self->status != THREAD_RUNNING);
3040
3041 waitForThreadSuspend(self, thread);
3042
3043 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3044 self->threadId, thread->threadId);
3045}
3046
3047/*
3048 * Check to see if we need to suspend ourselves. If so, go to sleep on
3049 * a condition variable.
3050 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003051 * Returns "true" if we suspended ourselves.
3052 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003053static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003054{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003055 assert(self != NULL);
3056 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003057
Andy McFadden6dce9962010-08-23 16:45:24 -07003058 /*
3059 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
3060 * access to self->suspendCount.
3061 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003062 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3063
Andy McFadden6dce9962010-08-23 16:45:24 -07003064 bool needSuspend = (self->suspendCount != 0);
3065 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07003066 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07003067 ThreadStatus oldStatus = self->status; /* should be RUNNING */
3068 self->status = THREAD_SUSPENDED;
3069
Andy McFadden3469a7e2010-08-04 16:09:10 -07003070 while (self->suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003071 /*
3072 * Wait for wakeup signal, releasing lock. The act of releasing
3073 * and re-acquiring the lock provides the memory barriers we
3074 * need for correct behavior on SMP.
3075 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07003076 dvmWaitCond(&gDvm.threadSuspendCountCond,
3077 &gDvm.threadSuspendCountLock);
3078 }
3079 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07003080 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07003081 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3082 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003083 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003084
3085 unlockThreadSuspendCount();
3086
Andy McFadden6dce9962010-08-23 16:45:24 -07003087 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003088}
3089
3090/*
Andy McFadden6dce9962010-08-23 16:45:24 -07003091 * Check to see if a suspend is pending. If so, suspend the current
3092 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003093 */
3094bool dvmCheckSuspendPending(Thread* self)
3095{
Andy McFadden6dce9962010-08-23 16:45:24 -07003096 assert(self != NULL);
3097 if (self->suspendCount == 0) {
3098 return false;
3099 } else {
3100 return fullSuspendCheck(self);
3101 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003102}
3103
3104/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003105 * Update our status.
3106 *
3107 * The "self" argument, which may be NULL, is accepted as an optimization.
3108 *
3109 * Returns the old status.
3110 */
3111ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3112{
3113 ThreadStatus oldStatus;
3114
3115 if (self == NULL)
3116 self = dvmThreadSelf();
3117
3118 LOGVV("threadid=%d: (status %d -> %d)\n",
3119 self->threadId, self->status, newStatus);
3120
3121 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07003122 if (oldStatus == newStatus)
3123 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003124
3125 if (newStatus == THREAD_RUNNING) {
3126 /*
3127 * Change our status to THREAD_RUNNING. The transition requires
3128 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003129 * us to be "asleep" in all other states, and another thread could
3130 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003131 *
Andy McFadden6dce9962010-08-23 16:45:24 -07003132 * The order of operations is very significant here. One way to
3133 * do this wrong is:
3134 *
3135 * GCing thread Our thread (in NATIVE)
3136 * ------------ ----------------------
3137 * check suspend count (== 0)
3138 * dvmSuspendAllThreads()
3139 * grab suspend-count lock
3140 * increment all suspend counts
3141 * release suspend-count lock
3142 * check thread state (== NATIVE)
3143 * all are suspended, begin GC
3144 * set state to RUNNING
3145 * (continue executing)
3146 *
3147 * We can correct this by grabbing the suspend-count lock and
3148 * performing both of our operations (check suspend count, set
3149 * state) while holding it, now we need to grab a mutex on every
3150 * transition to RUNNING.
3151 *
3152 * What we do instead is change the order of operations so that
3153 * the transition to RUNNING happens first. If we then detect
3154 * that the suspend count is nonzero, we switch to SUSPENDED.
3155 *
3156 * Appropriate compiler and memory barriers are required to ensure
3157 * that the operations are observed in the expected order.
3158 *
3159 * This does create a small window of opportunity where a GC in
3160 * progress could observe what appears to be a running thread (if
3161 * it happens to look between when we set to RUNNING and when we
3162 * switch to SUSPENDED). At worst this only affects assertions
3163 * and thread logging. (We could work around it with some sort
3164 * of intermediate "pre-running" state that is generally treated
3165 * as equivalent to running, but that doesn't seem worthwhile.)
3166 *
3167 * We can also solve this by combining the "status" and "suspend
3168 * count" fields into a single 32-bit value. This trades the
3169 * store/load barrier on transition to RUNNING for an atomic RMW
3170 * op on all transitions and all suspend count updates (also, all
3171 * accesses to status or the thread count require bit-fiddling).
3172 * It also eliminates the brief transition through RUNNING when
3173 * the thread is supposed to be suspended. This is possibly faster
3174 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003175 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003176 android_atomic_acquire_store(newStatus, &self->status);
3177 if (self->suspendCount != 0) {
3178 fullSuspendCheck(self);
3179 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003180 } else {
3181 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003182 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003183 *
3184 * We use a releasing store to ensure that, if we were RUNNING,
3185 * any updates we previously made to objects on the managed heap
3186 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003187 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003188 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003189 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003190 }
3191
3192 return oldStatus;
3193}
3194
3195/*
3196 * Get a statically defined thread group from a field in the ThreadGroup
3197 * Class object. Expected arguments are "mMain" and "mSystem".
3198 */
3199static Object* getStaticThreadGroup(const char* fieldName)
3200{
3201 StaticField* groupField;
3202 Object* groupObj;
3203
3204 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3205 fieldName, "Ljava/lang/ThreadGroup;");
3206 if (groupField == NULL) {
3207 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3208 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3209 return NULL;
3210 }
3211 groupObj = dvmGetStaticFieldObject(groupField);
3212 if (groupObj == NULL) {
3213 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3214 dvmThrowException("Ljava/lang/InternalError;", NULL);
3215 return NULL;
3216 }
3217
3218 return groupObj;
3219}
3220Object* dvmGetSystemThreadGroup(void)
3221{
3222 return getStaticThreadGroup("mSystem");
3223}
3224Object* dvmGetMainThreadGroup(void)
3225{
3226 return getStaticThreadGroup("mMain");
3227}
3228
3229/*
3230 * Given a VMThread object, return the associated Thread*.
3231 *
3232 * NOTE: if the thread detaches, the struct Thread will disappear, and
3233 * we will be touching invalid data. For safety, lock the thread list
3234 * before calling this.
3235 */
3236Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3237{
3238 int vmData;
3239
3240 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003241
3242 if (false) {
3243 Thread* thread = gDvm.threadList;
3244 while (thread != NULL) {
3245 if ((Thread*)vmData == thread)
3246 break;
3247
3248 thread = thread->next;
3249 }
3250
3251 if (thread == NULL) {
3252 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3253 vmThreadObj, (Thread*)vmData);
3254 vmData = 0;
3255 }
3256 }
3257
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003258 return (Thread*) vmData;
3259}
3260
Andy McFadden2b94b302010-03-09 16:38:36 -08003261/*
3262 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003263 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003264 *
3265 * Returns NULL if the thread was not found.
3266 */
3267Thread* dvmGetThreadByHandle(pthread_t handle)
3268{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003269 Thread* thread;
3270 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003271 if (thread->handle == handle)
3272 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003273 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003274 return thread;
3275}
Andy McFadden2b94b302010-03-09 16:38:36 -08003276
Andy McFadden0a24ef92010-03-12 13:39:59 -08003277/*
3278 * Given a threadId, return the associated Thread*.
3279 * Caller must hold the thread list lock.
3280 *
3281 * Returns NULL if the thread was not found.
3282 */
3283Thread* dvmGetThreadByThreadId(u4 threadId)
3284{
3285 Thread* thread;
3286 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3287 if (thread->threadId == threadId)
3288 break;
3289 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003290 return thread;
3291}
3292
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003293
3294/*
3295 * Conversion map for "nice" values.
3296 *
3297 * We use Android thread priority constants to be consistent with the rest
3298 * of the system. In some cases adjacent entries may overlap.
3299 */
3300static const int kNiceValues[10] = {
3301 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3302 ANDROID_PRIORITY_BACKGROUND + 6,
3303 ANDROID_PRIORITY_BACKGROUND + 3,
3304 ANDROID_PRIORITY_BACKGROUND,
3305 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3306 ANDROID_PRIORITY_NORMAL - 2,
3307 ANDROID_PRIORITY_NORMAL - 4,
3308 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3309 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3310 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3311};
3312
3313/*
3314 * Change the priority of a system thread to match that of the Thread object.
3315 *
3316 * We map a priority value from 1-10 to Linux "nice" values, where lower
3317 * numbers indicate higher priority.
3318 */
3319void dvmChangeThreadPriority(Thread* thread, int newPriority)
3320{
3321 pid_t pid = thread->systemTid;
3322 int newNice;
3323
3324 if (newPriority < 1 || newPriority > 10) {
3325 LOGW("bad priority %d\n", newPriority);
3326 newPriority = 5;
3327 }
3328 newNice = kNiceValues[newPriority-1];
3329
Andy McFaddend62c0b52009-08-04 15:02:12 -07003330 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003331 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003332 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003333 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003334 }
3335
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003336 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3337 char* str = dvmGetThreadName(thread);
3338 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3339 pid, str, newPriority, newNice, strerror(errno));
3340 free(str);
3341 } else {
3342 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3343 pid, newPriority, newNice);
3344 }
3345}
3346
3347/*
3348 * Get the thread priority for the current thread by querying the system.
3349 * This is useful when attaching a thread through JNI.
3350 *
3351 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3352 */
3353static int getThreadPriorityFromSystem(void)
3354{
3355 int i, sysprio, jprio;
3356
3357 errno = 0;
3358 sysprio = getpriority(PRIO_PROCESS, 0);
3359 if (sysprio == -1 && errno != 0) {
3360 LOGW("getpriority() failed: %s\n", strerror(errno));
3361 return THREAD_NORM_PRIORITY;
3362 }
3363
3364 jprio = THREAD_MIN_PRIORITY;
3365 for (i = 0; i < NELEM(kNiceValues); i++) {
3366 if (sysprio >= kNiceValues[i])
3367 break;
3368 jprio++;
3369 }
3370 if (jprio > THREAD_MAX_PRIORITY)
3371 jprio = THREAD_MAX_PRIORITY;
3372
3373 return jprio;
3374}
3375
3376
3377/*
3378 * Return true if the thread is on gDvm.threadList.
3379 * Caller should not hold gDvm.threadListLock.
3380 */
3381bool dvmIsOnThreadList(const Thread* thread)
3382{
3383 bool ret = false;
3384
3385 dvmLockThreadList(NULL);
3386 if (thread == gDvm.threadList) {
3387 ret = true;
3388 } else {
3389 ret = thread->prev != NULL || thread->next != NULL;
3390 }
3391 dvmUnlockThreadList();
3392
3393 return ret;
3394}
3395
3396/*
3397 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3398 * output target.
3399 */
3400void dvmDumpThread(Thread* thread, bool isRunning)
3401{
3402 DebugOutputTarget target;
3403
3404 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3405 dvmDumpThreadEx(&target, thread, isRunning);
3406}
3407
3408/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003409 * Try to get the scheduler group.
3410 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003411 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003412 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003413 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003414 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003415 * We return the part on the "cpu" line after the '/', which will be an
3416 * empty string for the default cgroup. If the string is longer than
3417 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003418 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003419 * On error, -1 is returned, and an error description will be stored in
3420 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003421 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003422static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003423{
3424#ifdef HAVE_ANDROID_OS
3425 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003426 char lineBuf[256];
3427 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003428
Andy McFadden7f64ede2010-03-03 15:37:10 -08003429 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003430 if ((fp = fopen(pathBuf, "r")) == NULL) {
3431 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003432 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003433 }
3434
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003435 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3436 char* subsys;
3437 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003438 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003439
Andy McFadden7f64ede2010-03-03 15:37:10 -08003440 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003441 subsys = strchr(lineBuf, ':');
3442 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003443 goto out_bad_data;
3444 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003445
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003446 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003447 /* Not the subsys we're looking for */
3448 continue;
3449 }
3450
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003451 grp = strchr(subsys, '/');
3452 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003453 goto out_bad_data;
3454 }
3455 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003456
Andy McFadden7f64ede2010-03-03 15:37:10 -08003457 len = strlen(grp);
3458 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3459
3460 if (bufLen <= len) {
3461 len = bufLen - 1;
3462 }
3463 strncpy(buf, grp, len);
3464 buf[len] = '\0';
3465 fclose(fp);
3466 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003467 }
3468
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003469 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003470 fclose(fp);
3471 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003472
3473out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003474 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003475 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003476 fclose(fp);
3477 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003478
Andy McFaddend62c0b52009-08-04 15:02:12 -07003479#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003480 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003481 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003482#endif
3483}
3484
3485/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003486 * Convert ThreadStatus to a string.
3487 */
3488const char* dvmGetThreadStatusStr(ThreadStatus status)
3489{
3490 switch (status) {
3491 case THREAD_ZOMBIE: return "ZOMBIE";
3492 case THREAD_RUNNING: return "RUNNABLE";
3493 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3494 case THREAD_MONITOR: return "MONITOR";
3495 case THREAD_WAIT: return "WAIT";
3496 case THREAD_INITIALIZING: return "INITIALIZING";
3497 case THREAD_STARTING: return "STARTING";
3498 case THREAD_NATIVE: return "NATIVE";
3499 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003500 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003501 default: return "UNKNOWN";
3502 }
3503}
3504
3505/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003506 * Print information about the specified thread.
3507 *
3508 * Works best when the thread in question is "self" or has been suspended.
3509 * When dumping a separate thread that's still running, set "isRunning" to
3510 * use a more cautious thread dump function.
3511 */
3512void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3513 bool isRunning)
3514{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003515 Object* threadObj;
3516 Object* groupObj;
3517 StringObject* nameStr;
3518 char* threadName = NULL;
3519 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003520 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003521 bool isDaemon;
3522 int priority; // java.lang.Thread priority
3523 int policy; // pthread policy
3524 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003525 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003526
Andy McFaddene3346d82010-06-02 15:37:21 -07003527 /*
3528 * Get the java.lang.Thread object. This function gets called from
3529 * some weird debug contexts, so it's possible that there's a GC in
3530 * progress on some other thread. To decrease the chances of the
3531 * thread object being moved out from under us, we add the reference
3532 * to the tracked allocation list, which pins it in place.
3533 *
3534 * If threadObj is NULL, the thread is still in the process of being
3535 * attached to the VM, and there's really nothing interesting to
3536 * say about it yet.
3537 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003538 threadObj = thread->threadObj;
3539 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003540 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003541 return;
3542 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003543 dvmAddTrackedAlloc(threadObj, NULL);
3544
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003545 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3546 gDvm.offJavaLangThread_name);
3547 threadName = dvmCreateCstrFromString(nameStr);
3548
3549 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3550 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3551
3552 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3553 LOGW("Warning: pthread_getschedparam failed\n");
3554 policy = -1;
3555 sp.sched_priority = -1;
3556 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003557 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003558 sizeof(schedulerGroupBuf)) == 0 &&
3559 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003560 strcpy(schedulerGroupBuf, "default");
3561 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003562
3563 /* a null value for group is not expected, but deal with it anyway */
3564 groupObj = (Object*) dvmGetFieldObject(threadObj,
3565 gDvm.offJavaLangThread_group);
3566 if (groupObj != NULL) {
3567 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3568 "name", "Ljava/lang/String;");
3569 if (offset < 0) {
3570 LOGW("Unable to find 'name' field in ThreadGroup\n");
3571 } else {
3572 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3573 groupName = dvmCreateCstrFromString(nameStr);
3574 }
3575 }
3576 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003577 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003578
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003579 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003580 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003581 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003582 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3583#if defined(WITH_JIT)
3584 thread->inJitCodeCache ? " JIT" : ""
3585#else
3586 ""
3587#endif
3588 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003589 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003590 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003591 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07003592 thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003593 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003594 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003595 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003596 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003597
Andy McFadden0a3f6982010-08-31 13:50:08 -07003598 /* get some bits from /proc/self/stat */
3599 ProcStatData procStatData;
3600 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3601 /* failed, use zeroed values */
3602 memset(&procStatData, 0, sizeof(procStatData));
3603 }
3604
3605 /* grab the scheduler stats for this thread */
3606 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3607 thread->systemTid);
3608 int schedstatFd = open(schedstatBuf, O_RDONLY);
3609 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003610 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003611 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003612 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3613 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003614 if (bytes >= 1) {
3615 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003616 }
3617 }
3618
Andy McFadden0a3f6982010-08-31 13:50:08 -07003619 /* show what we got */
3620 dvmPrintDebugMessage(target,
3621 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3622 schedstatBuf, procStatData.utime, procStatData.stime,
3623 procStatData.processor);
3624
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003625#ifdef WITH_MONITOR_TRACKING
3626 if (!isRunning) {
3627 LockedObjectData* lod = thread->pLockedObjects;
3628 if (lod != NULL)
3629 dvmPrintDebugMessage(target, " | monitors held:\n");
3630 else
3631 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3632 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003633 Object* obj = lod->obj;
3634 if (obj->clazz == gDvm.classJavaLangClass) {
3635 ClassObject* clazz = (ClassObject*) obj;
3636 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3637 obj, lod->recursionCount, obj->clazz->descriptor,
3638 clazz->descriptor);
3639 } else {
3640 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3641 obj, lod->recursionCount, obj->clazz->descriptor);
3642 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003643 lod = lod->next;
3644 }
3645 }
3646#endif
3647
3648 if (isRunning)
3649 dvmDumpRunningThreadStack(target, thread);
3650 else
3651 dvmDumpThreadStack(target, thread);
3652
Andy McFaddene3346d82010-06-02 15:37:21 -07003653 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003654 free(threadName);
3655 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003656}
3657
3658/*
3659 * Get the name of a thread.
3660 *
3661 * For correctness, the caller should hold the thread list lock to ensure
3662 * that the thread doesn't go away mid-call.
3663 *
3664 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3665 */
3666char* dvmGetThreadName(Thread* thread)
3667{
3668 StringObject* nameObj;
3669
3670 if (thread->threadObj == NULL) {
3671 LOGW("threadObj is NULL, name not available\n");
3672 return strdup("-unknown-");
3673 }
3674
3675 nameObj = (StringObject*)
3676 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3677 return dvmCreateCstrFromString(nameObj);
3678}
3679
3680/*
3681 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3682 * an output target.
3683 */
3684void dvmDumpAllThreads(bool grabLock)
3685{
3686 DebugOutputTarget target;
3687
3688 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3689 dvmDumpAllThreadsEx(&target, grabLock);
3690}
3691
3692/*
3693 * Print information about all known threads. Assumes they have been
3694 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3695 *
3696 * If "grabLock" is true, we grab the thread lock list. This is important
3697 * to do unless the caller already holds the lock.
3698 */
3699void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3700{
3701 Thread* thread;
3702
3703 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3704
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003705#ifdef HAVE_ANDROID_OS
3706 dvmPrintDebugMessage(target,
3707 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3708 gDvm.threadListLock.value,
3709 gDvm._threadSuspendLock.value,
3710 gDvm.threadSuspendCountLock.value,
3711 gDvm.gcHeapLock.value,
3712 gDvm.heapWorkerLock.value,
3713 gDvm.heapWorkerListLock.value);
3714#endif
3715
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003716 if (grabLock)
3717 dvmLockThreadList(dvmThreadSelf());
3718
3719 thread = gDvm.threadList;
3720 while (thread != NULL) {
3721 dvmDumpThreadEx(target, thread, false);
3722
3723 /* verify link */
3724 assert(thread->next == NULL || thread->next->prev == thread);
3725
3726 thread = thread->next;
3727 }
3728
3729 if (grabLock)
3730 dvmUnlockThreadList();
3731}
3732
Andy McFadden384ef6b2010-03-15 17:24:55 -07003733/*
3734 * Nuke the target thread from orbit.
3735 *
3736 * The idea is to send a "crash" signal to the target thread so that
3737 * debuggerd will take notice and dump an appropriate stack trace.
3738 * Because of the way debuggerd works, we have to throw the same signal
3739 * at it twice.
3740 *
3741 * This does not necessarily cause the entire process to stop, but once a
3742 * thread has been nuked the rest of the system is likely to be unstable.
3743 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003744 * performed, but it's advisable (and expected) to call dvmAbort soon.
3745 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003746 */
3747void dvmNukeThread(Thread* thread)
3748{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003749 int killResult;
3750
Andy McFaddena388a162010-03-18 16:27:14 -07003751 /* suppress the heapworker watchdog to assist anyone using a debugger */
3752 gDvm.nativeDebuggerActive = true;
3753
Andy McFadden384ef6b2010-03-15 17:24:55 -07003754 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003755 * Send the signals, separated by a brief interval to allow debuggerd
3756 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3757 * can be used instead of SIGSEGV to avoid making it look like the
3758 * code actually crashed at the current point of execution.
3759 *
3760 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3761 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3762 * you don't get the second stack trace; possibly something in the
3763 * kernel decides that a signal has already been sent and it's time
3764 * to just kill the process. The position in the current thread is
3765 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003766 *
Andy McFaddena388a162010-03-18 16:27:14 -07003767 * The target thread can continue to execute between the two signals.
3768 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003769 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003770 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3771 " cause debuggerd dump\n",
3772 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003773 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3774 if (killResult != 0) {
3775 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3776 }
Andy McFaddena388a162010-03-18 16:27:14 -07003777 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003778 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3779 if (killResult != 0) {
3780 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3781 }
Andy McFadden7122d862010-03-19 15:18:57 -07003782 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003783 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003784
3785 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3786 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003787 LOGD("Continuing\n");
3788}
3789
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003790#ifdef WITH_MONITOR_TRACKING
3791/*
3792 * Count up the #of locked objects in the current thread.
3793 */
3794static int getThreadObjectCount(const Thread* self)
3795{
3796 LockedObjectData* lod;
3797 int count = 0;
3798
3799 lod = self->pLockedObjects;
3800 while (lod != NULL) {
3801 count++;
3802 lod = lod->next;
3803 }
3804 return count;
3805}
3806
3807/*
3808 * Add the object to the thread's locked object list if it doesn't already
3809 * exist. The most recently added object is the most likely to be released
3810 * next, so we insert at the head of the list.
3811 *
3812 * If it already exists, we increase the recursive lock count.
3813 *
3814 * The object's lock may be thin or fat.
3815 */
3816void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3817{
3818 LockedObjectData* newLod;
3819 LockedObjectData* lod;
3820 int* trace;
3821 int depth;
3822
3823 lod = self->pLockedObjects;
3824 while (lod != NULL) {
3825 if (lod->obj == obj) {
3826 lod->recursionCount++;
3827 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3828 return;
3829 }
3830 lod = lod->next;
3831 }
3832
3833 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3834 if (newLod == NULL) {
3835 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3836 return;
3837 }
3838 newLod->obj = obj;
3839 newLod->recursionCount = 0;
3840
3841 if (withTrace) {
3842 trace = dvmFillInStackTraceRaw(self, &depth);
3843 newLod->rawStackTrace = trace;
3844 newLod->stackDepth = depth;
3845 }
3846
3847 newLod->next = self->pLockedObjects;
3848 self->pLockedObjects = newLod;
3849
3850 LOGV("+++ threadid=%d: added %p, now %d\n",
3851 self->threadId, newLod, getThreadObjectCount(self));
3852}
3853
3854/*
3855 * Remove the object from the thread's locked object list. If the entry
3856 * has a nonzero recursion count, we just decrement the count instead.
3857 */
3858void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3859{
3860 LockedObjectData* lod;
3861 LockedObjectData* prevLod;
3862
3863 lod = self->pLockedObjects;
3864 prevLod = NULL;
3865 while (lod != NULL) {
3866 if (lod->obj == obj) {
3867 if (lod->recursionCount > 0) {
3868 lod->recursionCount--;
3869 LOGV("+++ -recursive lock %p -> %d\n",
3870 obj, lod->recursionCount);
3871 return;
3872 } else {
3873 break;
3874 }
3875 }
3876 prevLod = lod;
3877 lod = lod->next;
3878 }
3879
3880 if (lod == NULL) {
3881 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3882 return;
3883 }
3884 if (prevLod == NULL) {
3885 /* first item in list */
3886 assert(self->pLockedObjects == lod);
3887 self->pLockedObjects = lod->next;
3888 } else {
3889 /* middle/end of list */
3890 prevLod->next = lod->next;
3891 }
3892
3893 LOGV("+++ threadid=%d: removed %p, now %d\n",
3894 self->threadId, lod, getThreadObjectCount(self));
3895 free(lod->rawStackTrace);
3896 free(lod);
3897}
3898
3899/*
3900 * If the specified object is already in the thread's locked object list,
3901 * return the LockedObjectData struct. Otherwise return NULL.
3902 */
3903LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3904{
3905 LockedObjectData* lod;
3906
3907 lod = self->pLockedObjects;
3908 while (lod != NULL) {
3909 if (lod->obj == obj)
3910 return lod;
3911 lod = lod->next;
3912 }
3913 return NULL;
3914}
3915#endif /*WITH_MONITOR_TRACKING*/
3916
3917
3918/*
3919 * GC helper functions
3920 */
3921
The Android Open Source Project99409882009-03-18 22:20:24 -07003922/*
3923 * Add the contents of the registers from the interpreted call stack.
3924 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003925static void gcScanInterpStackReferences(Thread *thread)
3926{
3927 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003928#if WITH_EXTRA_GC_CHECKS > 1
3929 bool first = true;
3930#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003931
3932 framePtr = (const u4 *)thread->curFrame;
3933 while (framePtr != NULL) {
3934 const StackSaveArea *saveArea;
3935 const Method *method;
3936
3937 saveArea = SAVEAREA_FROM_FP(framePtr);
3938 method = saveArea->method;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003939 if (method != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003940#ifdef COUNT_PRECISE_METHODS
3941 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003942 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3943 LOGI("PGC: added %s.%s %p\n",
3944 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003945#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003946#if WITH_EXTRA_GC_CHECKS > 1
3947 /*
3948 * May also want to enable the memset() in the "invokeMethod"
3949 * goto target in the portable interpreter. That sets the stack
3950 * to a pattern that makes referring to uninitialized data
3951 * very obvious.
3952 */
3953
3954 if (first) {
3955 /*
3956 * First frame, isn't native, check the "alternate" saved PC
3957 * as a sanity check.
3958 *
3959 * It seems like we could check the second frame if the first
3960 * is native, since the PCs should be the same. It turns out
3961 * this doesn't always work. The problem is that we could
3962 * have calls in the sequence:
3963 * interp method #2
3964 * native method
3965 * interp method #1
3966 *
3967 * and then GC while in the native method after returning
3968 * from interp method #2. The currentPc on the stack is
3969 * for interp method #1, but thread->currentPc2 is still
3970 * set for the last thing interp method #2 did.
3971 *
3972 * This can also happen in normal execution:
3973 * - sget-object on not-yet-loaded class
3974 * - class init updates currentPc2
3975 * - static field init is handled by parsing annotations;
3976 * static String init requires creation of a String object,
3977 * which can cause a GC
3978 *
3979 * Essentially, any pattern that involves executing
3980 * interpreted code and then causes an allocation without
3981 * executing instructions in the original method will hit
3982 * this. These are rare enough that the test still has
3983 * some value.
3984 */
3985 if (saveArea->xtra.currentPc != thread->currentPc2) {
3986 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3987 saveArea->xtra.currentPc, thread->currentPc2,
3988 method->clazz->descriptor, method->name, method->insns);
3989 if (saveArea->xtra.currentPc != NULL)
3990 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3991 if (thread->currentPc2 != NULL)
3992 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3993 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003994 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003995 } else {
3996 /*
3997 * It's unusual, but not impossible, for a non-first frame
3998 * to be at something other than a method invocation. For
3999 * example, if we do a new-instance on a nonexistent class,
4000 * we'll have a lot of class loader activity on the stack
4001 * above the frame with the "new" operation. Could also
4002 * happen while we initialize a Throwable when an instruction
4003 * fails.
4004 *
4005 * So there's not much we can do here to verify the PC,
4006 * except to verify that it's a GC point.
4007 */
4008 }
4009 assert(saveArea->xtra.currentPc != NULL);
4010#endif
4011
4012 const RegisterMap* pMap;
4013 const u1* regVector;
4014 int i;
4015
Andy McFaddencf8b55c2009-04-13 15:26:03 -07004016 Method* nonConstMethod = (Method*) method; // quiet gcc
4017 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07004018 if (pMap != NULL) {
4019 /* found map, get registers for this address */
4020 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07004021 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07004022 if (regVector == NULL) {
4023 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
4024 method->clazz->descriptor, method->name, addr);
4025 } else {
4026 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
4027 method->clazz->descriptor, method->name, addr,
4028 thread->threadId);
4029 }
4030 } else {
4031 /*
4032 * No map found. If precise GC is disabled this is
4033 * expected -- we don't create pointers to the map data even
4034 * if it's present -- but if it's enabled it means we're
4035 * unexpectedly falling back on a conservative scan, so it's
4036 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07004037 */
4038 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07004039 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07004040 method->clazz->descriptor, method->name);
4041 }
4042 regVector = NULL;
4043 }
4044
4045 if (regVector == NULL) {
4046 /* conservative scan */
4047 for (i = method->registersSize - 1; i >= 0; i--) {
4048 u4 rval = *framePtr++;
4049 if (rval != 0 && (rval & 0x3) == 0) {
4050 dvmMarkIfObject((Object *)rval);
4051 }
4052 }
4053 } else {
4054 /*
4055 * Precise scan. v0 is at the lowest address on the
4056 * interpreted stack, and is the first bit in the register
4057 * vector, so we can walk through the register map and
4058 * memory in the same direction.
4059 *
4060 * A '1' bit indicates a live reference.
4061 */
4062 u2 bits = 1 << 1;
4063 for (i = method->registersSize - 1; i >= 0; i--) {
4064 u4 rval = *framePtr++;
4065
4066 bits >>= 1;
4067 if (bits == 1) {
4068 /* set bit 9 so we can tell when we're empty */
4069 bits = *regVector++ | 0x0100;
4070 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
4071 }
4072
4073 if (rval != 0 && (bits & 0x01) != 0) {
4074 /*
4075 * Non-null, register marked as live reference. This
4076 * should always be a valid object.
4077 */
4078#if WITH_EXTRA_GC_CHECKS > 0
4079 if ((rval & 0x3) != 0 ||
4080 !dvmIsValidObject((Object*) rval))
4081 {
4082 /* this is very bad */
4083 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
4084 method->registersSize-1 - i, rval);
Andy McFaddenbe420e72010-10-18 13:28:31 -07004085 LOGE("PGC: %s.%s addr 0x%04x\n",
4086 method->clazz->descriptor, method->name,
4087 saveArea->xtra.currentPc - method->insns);
The Android Open Source Project99409882009-03-18 22:20:24 -07004088 } else
4089#endif
4090 {
4091 dvmMarkObjectNonNull((Object *)rval);
4092 }
4093 } else {
4094 /*
4095 * Null or non-reference, do nothing at all.
4096 */
4097#if WITH_EXTRA_GC_CHECKS > 1
4098 if (dvmIsValidObject((Object*) rval)) {
4099 /* this is normal, but we feel chatty */
4100 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
4101 method->registersSize-1 - i, rval);
4102 }
4103#endif
4104 }
4105 }
4106 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004107 }
4108 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004109
The Android Open Source Project99409882009-03-18 22:20:24 -07004110#if WITH_EXTRA_GC_CHECKS > 1
4111 first = false;
4112#endif
4113
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004114 /* Don't fall into an infinite loop if things get corrupted.
4115 */
4116 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
4117 saveArea->prevFrame == NULL);
4118 framePtr = saveArea->prevFrame;
4119 }
4120}
4121
4122static void gcScanReferenceTable(ReferenceTable *refTable)
4123{
4124 Object **op;
4125
4126 //TODO: these asserts are overkill; turn them off when things stablize.
4127 assert(refTable != NULL);
4128 assert(refTable->table != NULL);
4129 assert(refTable->nextEntry != NULL);
4130 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
4131 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
4132
4133 op = refTable->table;
4134 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
4135 dvmMarkObjectNonNull(*(op++));
4136 }
4137}
4138
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004139#ifdef USE_INDIRECT_REF
Andy McFaddend5ab7262009-08-25 07:19:34 -07004140static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
4141{
4142 Object** op = pRefTable->table;
4143 int numEntries = dvmIndirectRefTableEntries(pRefTable);
4144 int i;
4145
4146 for (i = 0; i < numEntries; i++) {
4147 Object* obj = *op;
4148 if (obj != NULL)
4149 dvmMarkObjectNonNull(obj);
4150 op++;
4151 }
4152}
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004153#endif
Andy McFaddend5ab7262009-08-25 07:19:34 -07004154
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004155/*
4156 * Scan a Thread and mark any objects it references.
4157 */
4158static void gcScanThread(Thread *thread)
4159{
4160 assert(thread != NULL);
4161
4162 /*
4163 * The target thread must be suspended or in a state where it can't do
4164 * any harm (e.g. in Object.wait()). The only exception is the current
4165 * thread, which will still be active and in the "running" state.
4166 *
Andy McFadden6dce9962010-08-23 16:45:24 -07004167 * It's possible to encounter a false-positive here because a thread
4168 * transitioning to running from (say) vmwait or native will briefly
4169 * set their status to running before switching to suspended. This
4170 * is highly unlikely, but does mean that we don't want to abort if
4171 * the situation arises.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004172 */
Andy McFadden6dce9962010-08-23 16:45:24 -07004173 if (thread->status == THREAD_RUNNING && thread != dvmThreadSelf()) {
Andy McFaddend40223e2009-12-07 15:35:51 -08004174 Thread* self = dvmThreadSelf();
Andy McFadden6dce9962010-08-23 16:45:24 -07004175 LOGW("threadid=%d: Warning: GC scanning a running thread (%d)\n",
Andy McFaddend40223e2009-12-07 15:35:51 -08004176 self->threadId, thread->threadId);
4177 dvmDumpThread(thread, true);
4178 LOGW("Found by:\n");
4179 dvmDumpThread(self, false);
4180
Andy McFadden6dce9962010-08-23 16:45:24 -07004181 /* continue anyway */
Andy McFaddend40223e2009-12-07 15:35:51 -08004182 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004183
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004184 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
4185
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004186 dvmMarkObject(thread->exception); // usually NULL
4187 gcScanReferenceTable(&thread->internalLocalRefTable);
4188
Andy McFaddend5ab7262009-08-25 07:19:34 -07004189#ifdef USE_INDIRECT_REF
4190 gcScanIndirectRefTable(&thread->jniLocalRefTable);
4191#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004192 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07004193#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004194
4195 if (thread->jniMonitorRefTable.table != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004196 gcScanReferenceTable(&thread->jniMonitorRefTable);
4197 }
4198
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004199 gcScanInterpStackReferences(thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004200}
4201
4202static void gcScanAllThreads()
4203{
4204 Thread *thread;
4205
4206 /* Lock the thread list so we can safely use the
4207 * next/prev pointers.
4208 */
4209 dvmLockThreadList(dvmThreadSelf());
4210
4211 for (thread = gDvm.threadList; thread != NULL;
4212 thread = thread->next)
4213 {
4214 /* We need to scan our own stack, so don't special-case
4215 * the current thread.
4216 */
4217 gcScanThread(thread);
4218 }
4219
4220 dvmUnlockThreadList();
4221}
4222
4223void dvmGcScanRootThreadGroups()
4224{
4225 /* We scan the VM's list of threads instead of going
4226 * through the actual ThreadGroups, but it should be
4227 * equivalent.
4228 *
Jeff Hao97319a82009-08-12 16:57:15 -07004229 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004230 * the root set, which should always be true; it's
4231 * loaded by the built-in class loader, which is part
4232 * of the root set.
4233 */
4234 gcScanAllThreads();
4235}