blob: 389021f13e2a1ceb024c71f25d58d267576730f0 [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"
Bob Lee2fe146a2009-09-10 00:36:29 +020021#include "native/SystemThread.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080022
23#include "utils/threads.h" // need Android thread priorities
24
25#include <stdlib.h>
26#include <unistd.h>
27#include <sys/time.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070028#include <sys/types.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080029#include <sys/resource.h>
30#include <sys/mman.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070031#include <signal.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080032#include <errno.h>
Andy McFaddend62c0b52009-08-04 15:02:12 -070033#include <fcntl.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080034
35#if defined(HAVE_PRCTL)
36#include <sys/prctl.h>
37#endif
38
Ben Chengfe1be872009-08-21 16:18:46 -070039#if defined(WITH_SELF_VERIFICATION)
40#include "interp/Jit.h" // need for self verification
41#endif
42
43
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080044/* desktop Linux needs a little help with gettid() */
45#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
46#define __KERNEL__
47# include <linux/unistd.h>
48#ifdef _syscall0
49_syscall0(pid_t,gettid)
50#else
51pid_t gettid() { return syscall(__NR_gettid);}
52#endif
53#undef __KERNEL__
54#endif
55
San Mehat256fc152009-04-21 14:03:06 -070056// Change this to enable logging on cgroup errors
57#define ENABLE_CGROUP_ERR_LOGGING 0
58
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080059// change this to LOGV/LOGD to debug thread activity
60#define LOG_THREAD LOGVV
61
62/*
63Notes on Threading
64
65All threads are native pthreads. All threads, except the JDWP debugger
66thread, are visible to code running in the VM and to the debugger. (We
67don't want the debugger to try to manipulate the thread that listens for
68instructions from the debugger.) Internal VM threads are in the "system"
69ThreadGroup, all others are in the "main" ThreadGroup, per convention.
70
71The GC only runs when all threads have been suspended. Threads are
72expected to suspend themselves, using a "safe point" mechanism. We check
73for a suspend request at certain points in the main interpreter loop,
74and on requests coming in from native code (e.g. all JNI functions).
75Certain debugger events may inspire threads to self-suspend.
76
77Native methods must use JNI calls to modify object references to avoid
78clashes with the GC. JNI doesn't provide a way for native code to access
79arrays of objects as such -- code must always get/set individual entries --
80so it should be possible to fully control access through JNI.
81
82Internal native VM threads, such as the finalizer thread, must explicitly
83check for suspension periodically. In most cases they will be sound
84asleep on a condition variable, and won't notice the suspension anyway.
85
86Threads may be suspended by the GC, debugger, or the SIGQUIT listener
87thread. The debugger may suspend or resume individual threads, while the
88GC always suspends all threads. Each thread has a "suspend count" that
89is incremented on suspend requests and decremented on resume requests.
90When the count is zero, the thread is runnable. This allows us to fulfill
91a debugger requirement: if the debugger suspends a thread, the thread is
92not allowed to run again until the debugger resumes it (or disconnects,
93in which case we must resume all debugger-suspended threads).
94
95Paused threads sleep on a condition variable, and are awoken en masse.
96Certain "slow" VM operations, such as starting up a new thread, will be
97done in a separate "VMWAIT" state, so that the rest of the VM doesn't
98freeze up waiting for the operation to finish. Threads must check for
99pending suspension when leaving VMWAIT.
100
101Because threads suspend themselves while interpreting code or when native
102code makes JNI calls, there is no risk of suspending while holding internal
103VM locks. All threads can enter a suspended (or native-code-only) state.
104Also, we don't have to worry about object references existing solely
105in hardware registers.
106
107We do, however, have to worry about objects that were allocated internally
108and aren't yet visible to anything else in the VM. If we allocate an
109object, and then go to sleep on a mutex after changing to a non-RUNNING
110state (e.g. while trying to allocate a second object), the first object
111could be garbage-collected out from under us while we sleep. To manage
112this, we automatically add all allocated objects to an internal object
113tracking list, and only remove them when we know we won't be suspended
114before the object appears in the GC root set.
115
116The debugger may choose to suspend or resume a single thread, which can
117lead to application-level deadlocks; this is expected behavior. The VM
118will only check for suspension of single threads when the debugger is
119active (the java.lang.Thread calls for this are deprecated and hence are
120not supported). Resumption of a single thread is handled by decrementing
121the thread's suspend count and sending a broadcast signal to the condition
122variable. (This will cause all threads to wake up and immediately go back
123to sleep, which isn't tremendously efficient, but neither is having the
124debugger attached.)
125
126The debugger is not allowed to resume threads suspended by the GC. This
127is trivially enforced by ignoring debugger requests while the GC is running
128(the JDWP thread is suspended during GC).
129
130The VM maintains a Thread struct for every pthread known to the VM. There
131is a java/lang/Thread object associated with every Thread. At present,
132there is no safe way to go from a Thread object to a Thread struct except by
133locking and scanning the list; this is necessary because the lifetimes of
134the two are not closely coupled. We may want to change this behavior,
135though at present the only performance impact is on the debugger (see
136threadObjToThread()). See also notes about dvmDetachCurrentThread().
137*/
138/*
139Alternate implementation (signal-based):
140
141Threads run without safe points -- zero overhead. The VM uses a signal
142(e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
143
144The trouble with using signals to suspend threads is that it means a thread
145can be in the middle of an operation when garbage collection starts.
146To prevent some sticky situations, we have to introduce critical sections
147to the VM code.
148
149Critical sections temporarily block suspension for a given thread.
150The thread must move to a non-blocked state (and self-suspend) after
151finishing its current task. If the thread blocks on a resource held
152by a suspended thread, we're hosed.
153
154One approach is to require that no blocking operations, notably
155acquisition of mutexes, can be performed within a critical section.
156This is too limiting. For example, if thread A gets suspended while
157holding the thread list lock, it will prevent the GC or debugger from
158being able to safely access the thread list. We need to wrap the critical
159section around the entire operation (enter critical, get lock, do stuff,
160release lock, exit critical).
161
162A better approach is to declare that certain resources can only be held
163within critical sections. A thread that enters a critical section and
164then gets blocked on the thread list lock knows that the thread it is
165waiting for is also in a critical section, and will release the lock
166before suspending itself. Eventually all threads will complete their
167operations and self-suspend. For this to work, the VM must:
168
169 (1) Determine the set of resources that may be accessed from the GC or
170 debugger threads. The mutexes guarding those go into the "critical
171 resource set" (CRS).
172 (2) Ensure that no resource in the CRS can be acquired outside of a
173 critical section. This can be verified with an assert().
174 (3) Ensure that only resources in the CRS can be held while in a critical
175 section. This is harder to enforce.
176
177If any of these conditions are not met, deadlock can ensue when grabbing
178resources in the GC or debugger (#1) or waiting for threads to suspend
179(#2,#3). (You won't actually deadlock in the GC, because if the semantics
180above are followed you don't need to lock anything in the GC. The risk is
181rather that the GC will access data structures in an intermediate state.)
182
183This approach requires more care and awareness in the VM than
184safe-pointing. Because the GC and debugger are fairly intrusive, there
185really aren't any internal VM resources that aren't shared. Thus, the
186enter/exit critical calls can be added to internal mutex wrappers, which
187makes it easy to get #1 and #2 right.
188
189An ordering should be established for all locks to avoid deadlocks.
190
191Monitor locks, which are also implemented with pthread calls, should not
192cause any problems here. Threads fighting over such locks will not be in
193critical sections and can be suspended freely.
194
195This can get tricky if we ever need exclusive access to VM and non-VM
196resources at the same time. It's not clear if this is a real concern.
197
198There are (at least) two ways to handle the incoming signals:
199
200 (a) Always accept signals. If we're in a critical section, the signal
201 handler just returns without doing anything (the "suspend level"
202 should have been incremented before the signal was sent). Otherwise,
203 if the "suspend level" is nonzero, we go to sleep.
204 (b) Block signals in critical sections. This ensures that we can't be
205 interrupted in a critical section, but requires pthread_sigmask()
206 calls on entry and exit.
207
208This is a choice between blocking the message and blocking the messenger.
209Because UNIX signals are unreliable (you can only know that you have been
210signaled, not whether you were signaled once or 10 times), the choice is
211not significant for correctness. The choice depends on the efficiency
212of pthread_sigmask() and the desire to actually block signals. Either way,
213it is best to ensure that there is only one indication of "blocked";
214having two (i.e. block signals and set a flag, then only send a signal
215if the flag isn't set) can lead to race conditions.
216
217The signal handler must take care to copy registers onto the stack (via
218setjmp), so that stack scans find all references. Because we have to scan
219native stacks, "exact" GC is not possible with this approach.
220
221Some other concerns with flinging signals around:
222 - Odd interactions with some debuggers (e.g. gdb on the Mac)
223 - Restrictions on some standard library calls during GC (e.g. don't
224 use printf on stdout to print GC debug messages)
225*/
226
Carl Shapiro59a93122010-01-26 17:12:51 -0800227#define kMaxThreadId ((1 << 16) - 1)
228#define kMainThreadId 1
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800229
230
231static Thread* allocThread(int interpStackSize);
232static bool prepareThread(Thread* thread);
233static void setThreadSelf(Thread* thread);
234static void unlinkThread(Thread* thread);
235static void freeThread(Thread* thread);
236static void assignThreadId(Thread* thread);
237static bool createFakeEntryFrame(Thread* thread);
238static bool createFakeRunFrame(Thread* thread);
239static void* interpThreadStart(void* arg);
240static void* internalThreadStart(void* arg);
241static void threadExitUncaughtException(Thread* thread, Object* group);
242static void threadExitCheck(void* arg);
243static void waitForThreadSuspend(Thread* self, Thread* thread);
244static int getThreadPriorityFromSystem(void);
245
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700246/*
247 * The JIT needs to know if any thread is suspended. We do this by
248 * maintaining a global sum of all threads' suspend counts. All suspendCount
249 * updates should go through this after aquiring threadSuspendCountLock.
250 */
251static inline void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
252{
253 *pSuspendCount += delta;
254 gDvm.sumThreadSuspendCount += delta;
255}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800256
257/*
258 * Initialize thread list and main thread's environment. We need to set
259 * up some basic stuff so that dvmThreadSelf() will work when we start
260 * loading classes (e.g. to check for exceptions).
261 */
262bool dvmThreadStartup(void)
263{
264 Thread* thread;
265
266 /* allocate a TLS slot */
267 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
268 LOGE("ERROR: pthread_key_create failed\n");
269 return false;
270 }
271
272 /* test our pthread lib */
273 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
274 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
275
276 /* prep thread-related locks and conditions */
277 dvmInitMutex(&gDvm.threadListLock);
278 pthread_cond_init(&gDvm.threadStartCond, NULL);
279 //dvmInitMutex(&gDvm.vmExitLock);
280 pthread_cond_init(&gDvm.vmExitCond, NULL);
281 dvmInitMutex(&gDvm._threadSuspendLock);
282 dvmInitMutex(&gDvm.threadSuspendCountLock);
283 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
284#ifdef WITH_DEADLOCK_PREDICTION
285 dvmInitMutex(&gDvm.deadlockHistoryLock);
286#endif
287
288 /*
289 * Dedicated monitor for Thread.sleep().
290 * TODO: change this to an Object* so we don't have to expose this
291 * call, and we interact better with JDWP monitor calls. Requires
292 * deferring the object creation to much later (e.g. final "main"
293 * thread prep) or until first use.
294 */
295 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
296
297 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
298
299 thread = allocThread(gDvm.stackSize);
300 if (thread == NULL)
301 return false;
302
303 /* switch mode for when we run initializers */
304 thread->status = THREAD_RUNNING;
305
306 /*
307 * We need to assign the threadId early so we can lock/notify
308 * object monitors. We'll set the "threadObj" field later.
309 */
310 prepareThread(thread);
311 gDvm.threadList = thread;
312
313#ifdef COUNT_PRECISE_METHODS
314 gDvm.preciseMethods = dvmPointerSetAlloc(200);
315#endif
316
317 return true;
318}
319
320/*
321 * We're a little farther up now, and can load some basic classes.
322 *
323 * We're far enough along that we can poke at java.lang.Thread and friends,
324 * but should not assume that static initializers have run (or cause them
325 * to do so). That means no object allocations yet.
326 */
327bool dvmThreadObjStartup(void)
328{
329 /*
330 * Cache the locations of these classes. It's likely that we're the
331 * first to reference them, so they're being loaded now.
332 */
333 gDvm.classJavaLangThread =
334 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
335 gDvm.classJavaLangVMThread =
336 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
337 gDvm.classJavaLangThreadGroup =
338 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
339 if (gDvm.classJavaLangThread == NULL ||
340 gDvm.classJavaLangThreadGroup == NULL ||
341 gDvm.classJavaLangThreadGroup == NULL)
342 {
343 LOGE("Could not find one or more essential thread classes\n");
344 return false;
345 }
346
347 /*
348 * Cache field offsets. This makes things a little faster, at the
349 * expense of hard-coding non-public field names into the VM.
350 */
351 gDvm.offJavaLangThread_vmThread =
352 dvmFindFieldOffset(gDvm.classJavaLangThread,
353 "vmThread", "Ljava/lang/VMThread;");
354 gDvm.offJavaLangThread_group =
355 dvmFindFieldOffset(gDvm.classJavaLangThread,
356 "group", "Ljava/lang/ThreadGroup;");
357 gDvm.offJavaLangThread_daemon =
358 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
359 gDvm.offJavaLangThread_name =
360 dvmFindFieldOffset(gDvm.classJavaLangThread,
361 "name", "Ljava/lang/String;");
362 gDvm.offJavaLangThread_priority =
363 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
364
365 if (gDvm.offJavaLangThread_vmThread < 0 ||
366 gDvm.offJavaLangThread_group < 0 ||
367 gDvm.offJavaLangThread_daemon < 0 ||
368 gDvm.offJavaLangThread_name < 0 ||
369 gDvm.offJavaLangThread_priority < 0)
370 {
371 LOGE("Unable to find all fields in java.lang.Thread\n");
372 return false;
373 }
374
375 gDvm.offJavaLangVMThread_thread =
376 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
377 "thread", "Ljava/lang/Thread;");
378 gDvm.offJavaLangVMThread_vmData =
379 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
380 if (gDvm.offJavaLangVMThread_thread < 0 ||
381 gDvm.offJavaLangVMThread_vmData < 0)
382 {
383 LOGE("Unable to find all fields in java.lang.VMThread\n");
384 return false;
385 }
386
387 /*
388 * Cache the vtable offset for "run()".
389 *
390 * We don't want to keep the Method* because then we won't find see
391 * methods defined in subclasses.
392 */
393 Method* meth;
394 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
395 if (meth == NULL) {
396 LOGE("Unable to find run() in java.lang.Thread\n");
397 return false;
398 }
399 gDvm.voffJavaLangThread_run = meth->methodIndex;
400
401 /*
402 * Cache vtable offsets for ThreadGroup methods.
403 */
404 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
405 "removeThread", "(Ljava/lang/Thread;)V");
406 if (meth == NULL) {
407 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
408 return false;
409 }
410 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
411
412 return true;
413}
414
415/*
416 * All threads should be stopped by now. Clean up some thread globals.
417 */
418void dvmThreadShutdown(void)
419{
420 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700421 /*
422 * If we walk through the thread list and try to free the
423 * lingering thread structures (which should only be for daemon
424 * threads), the daemon threads may crash if they execute before
425 * the process dies. Let them leak.
426 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800427 freeThread(gDvm.threadList);
428 gDvm.threadList = NULL;
429 }
430
431 dvmFreeBitVector(gDvm.threadIdMap);
432
433 dvmFreeMonitorList();
434
435 pthread_key_delete(gDvm.pthreadKeySelf);
436}
437
438
439/*
440 * Grab the suspend count global lock.
441 */
442static inline void lockThreadSuspendCount(void)
443{
444 /*
445 * Don't try to change to VMWAIT here. When we change back to RUNNING
446 * we have to check for a pending suspend, which results in grabbing
447 * this lock recursively. Doesn't work with "fast" pthread mutexes.
448 *
449 * This lock is always held for very brief periods, so as long as
450 * mutex ordering is respected we shouldn't stall.
451 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700452 dvmLockMutex(&gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800453}
454
455/*
456 * Release the suspend count global lock.
457 */
458static inline void unlockThreadSuspendCount(void)
459{
460 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
461}
462
463/*
464 * Grab the thread list global lock.
465 *
466 * This is held while "suspend all" is trying to make everybody stop. If
467 * the shutdown is in progress, and somebody tries to grab the lock, they'll
468 * have to wait for the GC to finish. Therefore it's important that the
469 * thread not be in RUNNING mode.
470 *
471 * We don't have to check to see if we should be suspended once we have
472 * the lock. Nobody can suspend all threads without holding the thread list
473 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700474 *
475 * TODO: consider checking for suspend after acquiring the lock, and
476 * backing off if set. As stated above, it can't happen during normal
477 * execution, but it *can* happen during shutdown when daemon threads
478 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800479 */
480void dvmLockThreadList(Thread* self)
481{
482 ThreadStatus oldStatus;
483
484 if (self == NULL) /* try to get it from TLS */
485 self = dvmThreadSelf();
486
487 if (self != NULL) {
488 oldStatus = self->status;
489 self->status = THREAD_VMWAIT;
490 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700491 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800492 //LOGW("NULL self in dvmLockThreadList\n");
493 oldStatus = -1; // shut up gcc
494 }
495
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700496 dvmLockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800497
498 if (self != NULL)
499 self->status = oldStatus;
500}
501
502/*
503 * Release the thread list global lock.
504 */
505void dvmUnlockThreadList(void)
506{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700507 dvmUnlockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800508}
509
The Android Open Source Project99409882009-03-18 22:20:24 -0700510/*
511 * Convert SuspendCause to a string.
512 */
513static const char* getSuspendCauseStr(SuspendCause why)
514{
515 switch (why) {
516 case SUSPEND_NOT: return "NOT?";
517 case SUSPEND_FOR_GC: return "gc";
518 case SUSPEND_FOR_DEBUG: return "debug";
519 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
520 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700521 case SUSPEND_FOR_VERIFY: return "verify";
Ben Chenga8e64a72009-10-20 13:01:36 -0700522#if defined(WITH_JIT)
523 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
524 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800525 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800526 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700527#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700528 default: return "UNKNOWN";
529 }
530}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800531
532/*
533 * Grab the "thread suspend" lock. This is required to prevent the
534 * GC and the debugger from simultaneously suspending all threads.
535 *
536 * If we fail to get the lock, somebody else is trying to suspend all
537 * threads -- including us. If we go to sleep on the lock we'll deadlock
538 * the VM. Loop until we get it or somebody puts us to sleep.
539 */
540static void lockThreadSuspend(const char* who, SuspendCause why)
541{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800542 const int kSpinSleepTime = 3*1000*1000; /* 3s */
543 u8 startWhen = 0; // init req'd to placate gcc
544 int sleepIter = 0;
545 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700546
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800547 do {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700548 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800549 if (cc != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700550 Thread* self = dvmThreadSelf();
551
552 if (!dvmCheckSuspendPending(self)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800553 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700554 * Could be that a resume-all is in progress, and something
555 * grabbed the CPU when the wakeup was broadcast. The thread
556 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700557 * thread suspend lock. (We release before the broadcast,
558 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700559 *
560 * Could be we hit the window as a suspend was started,
561 * and the lock has been grabbed but the suspend counts
562 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700563 *
564 * Could be an unusual JNI thread-attach thing.
565 *
566 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800567 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700568 *
569 * Could be two app threads both want to patch predicted
570 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800571 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700572 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
573 " it's held, no suspend pending\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700574 self->threadId, who, getSuspendCauseStr(why));
The Android Open Source Project99409882009-03-18 22:20:24 -0700575 } else {
576 /* we suspended; reset timeout */
577 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800578 }
579
580 /* give the lock-holder a chance to do some work */
581 if (sleepIter == 0)
582 startWhen = dvmGetRelativeTimeUsec();
583 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700584 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800585 " bailing\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700586 self->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700587 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800588 dvmDumpAllThreads(false);
589 dvmAbort();
590 }
591 }
592 } while (cc != 0);
593 assert(cc == 0);
594}
595
596/*
597 * Release the "thread suspend" lock.
598 */
599static inline void unlockThreadSuspend(void)
600{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700601 dvmUnlockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800602}
603
604
605/*
606 * Kill any daemon threads that still exist. All of ours should be
607 * stopped, so these should be Thread objects or JNI-attached threads
608 * started by the application. Actively-running threads are likely
609 * to crash the process if they continue to execute while the VM
610 * shuts down, so we really need to kill or suspend them. (If we want
611 * the VM to restart within this process, we need to kill them, but that
612 * leaves open the possibility of orphaned resources.)
613 *
614 * Waiting for the thread to suspend may be unwise at this point, but
615 * if one of these is wedged in a critical section then we probably
616 * would've locked up on the last GC attempt.
617 *
618 * It's possible for this function to get called after a failed
619 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700620 *
621 * This will be called from whatever thread calls DestroyJavaVM, usually
622 * but not necessarily the main thread. It's likely, but not guaranteed,
623 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800624 */
625void dvmSlayDaemons(void)
626{
Andy McFadden44860362009-08-06 17:56:14 -0700627 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800628 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700629 int threadId = 0;
630 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800631
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800632 dvmLockThreadList(self);
633
Andy McFadden44860362009-08-06 17:56:14 -0700634 if (self != NULL)
635 threadId = self->threadId;
636
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800637 target = gDvm.threadList;
638 while (target != NULL) {
639 if (target == self) {
640 target = target->next;
641 continue;
642 }
643
644 if (!dvmGetFieldBoolean(target->threadObj,
645 gDvm.offJavaLangThread_daemon))
646 {
Andy McFadden44860362009-08-06 17:56:14 -0700647 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800648 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700649 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800650 }
651
Andy McFadden44860362009-08-06 17:56:14 -0700652 char* threadName = dvmGetThreadName(target);
653 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
654 threadId, target->threadId, threadName);
655 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800656
Andy McFadden44860362009-08-06 17:56:14 -0700657 /* mark as suspended */
658 lockThreadSuspendCount();
659 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
660 unlockThreadSuspendCount();
661 doWait = true;
662
663 target = target->next;
664 }
665
666 //dvmDumpAllThreads(false);
667
668 /*
669 * Unlock the thread list, relocking it later if necessary. It's
670 * possible a thread is in VMWAIT after calling dvmLockThreadList,
671 * and that function *doesn't* check for pending suspend after
672 * acquiring the lock. We want to let them finish their business
673 * and see the pending suspend before we continue here.
674 *
675 * There's no guarantee of mutex fairness, so this might not work.
676 * (The alternative is to have dvmLockThreadList check for suspend
677 * after acquiring the lock and back off, something we should consider.)
678 */
679 dvmUnlockThreadList();
680
681 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800682 bool complained = false;
683
Andy McFadden44860362009-08-06 17:56:14 -0700684 usleep(200 * 1000);
685
686 dvmLockThreadList(self);
687
688 /*
689 * Sleep for a bit until the threads have suspended. We're trying
690 * to exit, so don't wait for too long.
691 */
692 int i;
693 for (i = 0; i < 10; i++) {
694 bool allSuspended = true;
695
696 target = gDvm.threadList;
697 while (target != NULL) {
698 if (target == self) {
699 target = target->next;
700 continue;
701 }
702
703 if (target->status == THREAD_RUNNING && !target->isSuspended) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800704 if (!complained)
705 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700706 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800707 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700708 }
709
710 target = target->next;
711 }
712
713 if (allSuspended) {
714 LOGD("threadid=%d: all daemons have suspended\n", threadId);
715 break;
716 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800717 if (!complained) {
718 complained = true;
719 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
720 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800721 }
Andy McFadden44860362009-08-06 17:56:14 -0700722 }
723
724 usleep(200 * 1000);
725 }
726 dvmUnlockThreadList();
727 }
728
729#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
730 /*
731 * Abandon the threads and recover their resources.
732 */
733 target = gDvm.threadList;
734 while (target != NULL) {
735 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800736 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800737 freeThread(target);
738 target = nextTarget;
739 }
Andy McFadden44860362009-08-06 17:56:14 -0700740#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800741
Andy McFadden44860362009-08-06 17:56:14 -0700742 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800743}
744
745
746/*
747 * Finish preparing the parts of the Thread struct required to support
748 * JNI registration.
749 */
750bool dvmPrepMainForJni(JNIEnv* pEnv)
751{
752 Thread* self;
753
754 /* main thread is always first in list at this point */
755 self = gDvm.threadList;
756 assert(self->threadId == kMainThreadId);
757
758 /* create a "fake" JNI frame at the top of the main thread interp stack */
759 if (!createFakeEntryFrame(self))
760 return false;
761
762 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
763 dvmSetJniEnvThreadId(pEnv, self);
764 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
765
766 return true;
767}
768
769
770/*
771 * Finish preparing the main thread, allocating some objects to represent
772 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700773 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800774 */
775bool dvmPrepMainThread(void)
776{
777 Thread* thread;
778 Object* groupObj;
779 Object* threadObj;
780 Object* vmThreadObj;
781 StringObject* threadNameStr;
782 Method* init;
783 JValue unused;
784
785 LOGV("+++ finishing prep on main VM thread\n");
786
787 /* main thread is always first in list at this point */
788 thread = gDvm.threadList;
789 assert(thread->threadId == kMainThreadId);
790
791 /*
792 * Make sure the classes are initialized. We have to do this before
793 * we create an instance of them.
794 */
795 if (!dvmInitClass(gDvm.classJavaLangClass)) {
796 LOGE("'Class' class failed to initialize\n");
797 return false;
798 }
799 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
800 !dvmInitClass(gDvm.classJavaLangThread) ||
801 !dvmInitClass(gDvm.classJavaLangVMThread))
802 {
803 LOGE("thread classes failed to initialize\n");
804 return false;
805 }
806
807 groupObj = dvmGetMainThreadGroup();
808 if (groupObj == NULL)
809 return false;
810
811 /*
812 * Allocate and construct a Thread with the internal-creation
813 * constructor.
814 */
815 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
816 if (threadObj == NULL) {
817 LOGE("unable to allocate main thread object\n");
818 return false;
819 }
820 dvmReleaseTrackedAlloc(threadObj, NULL);
821
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700822 threadNameStr = dvmCreateStringFromCstr("main");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800823 if (threadNameStr == NULL)
824 return false;
825 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
826
827 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
828 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
829 assert(init != NULL);
830 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
831 THREAD_NORM_PRIORITY, false);
832 if (dvmCheckException(thread)) {
833 LOGE("exception thrown while constructing main thread object\n");
834 return false;
835 }
836
837 /*
838 * Allocate and construct a VMThread.
839 */
840 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
841 if (vmThreadObj == NULL) {
842 LOGE("unable to allocate main vmthread object\n");
843 return false;
844 }
845 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
846
847 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
848 "(Ljava/lang/Thread;)V");
849 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
850 if (dvmCheckException(thread)) {
851 LOGE("exception thrown while constructing main vmthread object\n");
852 return false;
853 }
854
855 /* set the VMThread.vmData field to our Thread struct */
856 assert(gDvm.offJavaLangVMThread_vmData != 0);
857 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
858
859 /*
860 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700861 * Threads will see that this Thread is running (at least, they would,
862 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800863 */
864 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
865 vmThreadObj);
866
867 thread->threadObj = threadObj;
868
869 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700870 * Set the context class loader. This invokes a ClassLoader method,
871 * which could conceivably call Thread.currentThread(), so we want the
872 * Thread to be fully configured before we do this.
873 */
874 Object* systemLoader = dvmGetSystemClassLoader();
875 if (systemLoader == NULL) {
876 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
877 /* keep going */
878 }
879 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
880 "contextClassLoader", "Ljava/lang/ClassLoader;");
881 if (ctxtClassLoaderOffset < 0) {
882 LOGE("Unable to find contextClassLoader field in Thread\n");
883 return false;
884 }
885 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
886
887 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800888 * Finish our thread prep.
889 */
890
891 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
892 gDvm.nonDaemonThreadCount++;
893
894 return true;
895}
896
897
898/*
899 * Alloc and initialize a Thread struct.
900 *
Andy McFaddene3346d82010-06-02 15:37:21 -0700901 * Does not create any objects, just stuff on the system (malloc) heap.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800902 */
903static Thread* allocThread(int interpStackSize)
904{
905 Thread* thread;
906 u1* stackBottom;
907
908 thread = (Thread*) calloc(1, sizeof(Thread));
909 if (thread == NULL)
910 return NULL;
911
Jeff Hao97319a82009-08-12 16:57:15 -0700912#if defined(WITH_SELF_VERIFICATION)
913 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
914 return NULL;
915#endif
916
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800917 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
918
919 thread->status = THREAD_INITIALIZING;
920 thread->suspendCount = 0;
921
922#ifdef WITH_ALLOC_LIMITS
923 thread->allocLimit = -1;
924#endif
925
926 /*
927 * Allocate and initialize the interpreted code stack. We essentially
928 * "lose" the alloc pointer, which points at the bottom of the stack,
929 * but we can get it back later because we know how big the stack is.
930 *
931 * The stack must be aligned on a 4-byte boundary.
932 */
933#ifdef MALLOC_INTERP_STACK
934 stackBottom = (u1*) malloc(interpStackSize);
935 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700936#if defined(WITH_SELF_VERIFICATION)
937 dvmSelfVerificationShadowSpaceFree(thread);
938#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800939 free(thread);
940 return NULL;
941 }
942 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
943#else
944 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
945 MAP_PRIVATE | MAP_ANON, -1, 0);
946 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700947#if defined(WITH_SELF_VERIFICATION)
948 dvmSelfVerificationShadowSpaceFree(thread);
949#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800950 free(thread);
951 return NULL;
952 }
953#endif
954
955 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
956 thread->interpStackSize = interpStackSize;
957 thread->interpStackStart = stackBottom + interpStackSize;
958 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
959
960 /* give the thread code a chance to set things up */
961 dvmInitInterpStack(thread, interpStackSize);
962
963 return thread;
964}
965
966/*
967 * Get a meaningful thread ID. At present this only has meaning under Linux,
968 * where getpid() and gettid() sometimes agree and sometimes don't depending
969 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
970 */
971pid_t dvmGetSysThreadId(void)
972{
973#ifdef HAVE_GETTID
974 return gettid();
975#else
976 return getpid();
977#endif
978}
979
980/*
981 * Finish initialization of a Thread struct.
982 *
983 * This must be called while executing in the new thread, but before the
984 * thread is added to the thread list.
985 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700986 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800987 * assignThreadId()).
988 */
989static bool prepareThread(Thread* thread)
990{
991 assignThreadId(thread);
992 thread->handle = pthread_self();
993 thread->systemTid = dvmGetSysThreadId();
994
995 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
996 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700997 /*
998 * If we were called by dvmAttachCurrentThread, the self value is
999 * already correctly established as "thread".
1000 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001001 setThreadSelf(thread);
1002
1003 LOGV("threadid=%d: interp stack at %p\n",
1004 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1005
1006 /*
1007 * Initialize invokeReq.
1008 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001009 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001010 pthread_cond_init(&thread->invokeReq.cv, NULL);
1011
1012 /*
1013 * Initialize our reference tracking tables.
1014 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001015 * Most threads won't use jniMonitorRefTable, so we clear out the
1016 * structure but don't call the init function (which allocs storage).
1017 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001018#ifdef USE_INDIRECT_REF
1019 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1020 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1021 return false;
1022#else
1023 /*
1024 * The JNI local ref table *must* be fixed-size because we keep pointers
1025 * into the table in our stack frames.
1026 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001027 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1028 kJniLocalRefMax, kJniLocalRefMax))
1029 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001030#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001031 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1032 kInternalRefDefault, kInternalRefMax))
1033 return false;
1034
1035 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1036
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001037 pthread_cond_init(&thread->waitCond, NULL);
1038 dvmInitMutex(&thread->waitMutex);
1039
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001040 return true;
1041}
1042
1043/*
1044 * Remove a thread from the internal list.
1045 * Clear out the links to make it obvious that the thread is
1046 * no longer on the list. Caller must hold gDvm.threadListLock.
1047 */
1048static void unlinkThread(Thread* thread)
1049{
1050 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1051 if (thread == gDvm.threadList) {
1052 assert(thread->prev == NULL);
1053 gDvm.threadList = thread->next;
1054 } else {
1055 assert(thread->prev != NULL);
1056 thread->prev->next = thread->next;
1057 }
1058 if (thread->next != NULL)
1059 thread->next->prev = thread->prev;
1060 thread->prev = thread->next = NULL;
1061}
1062
1063/*
1064 * Free a Thread struct, and all the stuff allocated within.
1065 */
1066static void freeThread(Thread* thread)
1067{
1068 if (thread == NULL)
1069 return;
1070
1071 /* thread->threadId is zero at this point */
1072 LOGVV("threadid=%d: freeing\n", thread->threadId);
1073
1074 if (thread->interpStackStart != NULL) {
1075 u1* interpStackBottom;
1076
1077 interpStackBottom = thread->interpStackStart;
1078 interpStackBottom -= thread->interpStackSize;
1079#ifdef MALLOC_INTERP_STACK
1080 free(interpStackBottom);
1081#else
1082 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1083 LOGW("munmap(thread stack) failed\n");
1084#endif
1085 }
1086
Andy McFaddend5ab7262009-08-25 07:19:34 -07001087#ifdef USE_INDIRECT_REF
1088 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1089#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001090 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001091#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001092 dvmClearReferenceTable(&thread->internalLocalRefTable);
1093 if (&thread->jniMonitorRefTable.table != NULL)
1094 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1095
Jeff Hao97319a82009-08-12 16:57:15 -07001096#if defined(WITH_SELF_VERIFICATION)
1097 dvmSelfVerificationShadowSpaceFree(thread);
1098#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001099 free(thread);
1100}
1101
1102/*
1103 * Like pthread_self(), but on a Thread*.
1104 */
1105Thread* dvmThreadSelf(void)
1106{
1107 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1108}
1109
1110/*
1111 * Explore our sense of self. Stuffs the thread pointer into TLS.
1112 */
1113static void setThreadSelf(Thread* thread)
1114{
1115 int cc;
1116
1117 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1118 if (cc != 0) {
1119 /*
1120 * Sometimes this fails under Bionic with EINVAL during shutdown.
1121 * This can happen if the timing is just right, e.g. a thread
1122 * fails to attach during shutdown, but the "fail" path calls
1123 * here to ensure we clean up after ourselves.
1124 */
1125 if (thread != NULL) {
1126 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1127 dvmAbort(); /* the world is fundamentally hosed */
1128 }
1129 }
1130}
1131
1132/*
1133 * This is associated with the pthreadKeySelf key. It's called by the
1134 * pthread library when a thread is exiting and the "self" pointer in TLS
1135 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001136 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001137 *
1138 * This is mainly of use to ensure that we don't leak resources if, for
1139 * example, a thread attaches itself to us with AttachCurrentThread and
1140 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001141 *
1142 * We could do the detach here instead of aborting, but this will lead to
1143 * portability problems. Other implementations do not do this check and
1144 * will simply be unaware that the thread has exited, leading to resource
1145 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1146 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001147 *
1148 * Because some implementations may want to use the pthread destructor
1149 * to initiate the detach, and the ordering of destructors is not defined,
1150 * 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 -08001151 */
1152static void threadExitCheck(void* arg)
1153{
Andy McFadden909ce242009-12-10 16:38:30 -08001154 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001155
Andy McFadden909ce242009-12-10 16:38:30 -08001156 Thread* self = (Thread*) arg;
1157 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001158
Andy McFadden909ce242009-12-10 16:38:30 -08001159 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1160 self->threadId, arg, self->threadExitCheckCount);
1161
1162 if (self->status == THREAD_ZOMBIE) {
1163 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1164 self->threadId);
1165 return;
1166 }
1167
1168 if (self->threadExitCheckCount < kMaxCount) {
1169 /*
1170 * Spin a couple of times to let other destructors fire.
1171 */
1172 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1173 self->threadId, self->threadExitCheckCount);
1174 self->threadExitCheckCount++;
1175 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1176 if (cc != 0) {
1177 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1178 self->threadId);
1179 dvmAbort();
1180 }
1181 } else {
1182 LOGE("threadid=%d: native thread exited without detaching\n",
1183 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001184 dvmAbort();
1185 }
1186}
1187
1188
1189/*
1190 * Assign the threadId. This needs to be a small integer so that our
1191 * "thin" locks fit in a small number of bits.
1192 *
1193 * We reserve zero for use as an invalid ID.
1194 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001195 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001196 */
1197static void assignThreadId(Thread* thread)
1198{
Carl Shapiro59a93122010-01-26 17:12:51 -08001199 /*
1200 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001201 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1202 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001203 */
1204 int num = dvmAllocBit(gDvm.threadIdMap);
1205 if (num < 0) {
1206 LOGE("Ran out of thread IDs\n");
1207 dvmAbort(); // TODO: make this a non-fatal error result
1208 }
1209
Carl Shapiro59a93122010-01-26 17:12:51 -08001210 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001211
1212 assert(thread->threadId != 0);
1213 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1214}
1215
1216/*
1217 * Give back the thread ID.
1218 */
1219static void releaseThreadId(Thread* thread)
1220{
1221 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001222 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001223 thread->threadId = 0;
1224}
1225
1226
1227/*
1228 * Add a stack frame that makes it look like the native code in the main
1229 * thread was originally invoked from interpreted code. This gives us a
1230 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1231 * VM begins by executing "main" in a class, so in a way this brings us
1232 * closer to the spec.
1233 */
1234static bool createFakeEntryFrame(Thread* thread)
1235{
1236 assert(thread->threadId == kMainThreadId); // main thread only
1237
1238 /* find the method on first use */
1239 if (gDvm.methFakeNativeEntry == NULL) {
1240 ClassObject* nativeStart;
1241 Method* mainMeth;
1242
1243 nativeStart = dvmFindSystemClassNoInit(
1244 "Ldalvik/system/NativeStart;");
1245 if (nativeStart == NULL) {
1246 LOGE("Unable to find dalvik.system.NativeStart class\n");
1247 return false;
1248 }
1249
1250 /*
1251 * Because we are creating a frame that represents application code, we
1252 * want to stuff the application class loader into the method's class
1253 * loader field, even though we're using the system class loader to
1254 * load it. This makes life easier over in JNI FindClass (though it
1255 * could bite us in other ways).
1256 *
1257 * Unfortunately this is occurring too early in the initialization,
1258 * of necessity coming before JNI is initialized, and we're not quite
1259 * ready to set up the application class loader.
1260 *
1261 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1262 * and check it in FindClass. The method is private so nobody else
1263 * can call it.
1264 */
1265 //nativeStart->classLoader = dvmGetSystemClassLoader();
1266
1267 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1268 "main", "([Ljava/lang/String;)V");
1269 if (mainMeth == NULL) {
1270 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1271 return false;
1272 }
1273
1274 gDvm.methFakeNativeEntry = mainMeth;
1275 }
1276
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001277 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1278 return false;
1279
1280 /*
1281 * Null out the "String[] args" argument.
1282 */
1283 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1284 u4* framePtr = (u4*) thread->curFrame;
1285 framePtr[0] = 0;
1286
1287 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001288}
1289
1290
1291/*
1292 * Add a stack frame that makes it look like the native thread has been
1293 * executing interpreted code. This gives us a place to hang JNI local
1294 * references.
1295 */
1296static bool createFakeRunFrame(Thread* thread)
1297{
1298 ClassObject* nativeStart;
1299 Method* runMeth;
1300
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001301 /*
1302 * TODO: cache this result so we don't have to dig for it every time
1303 * somebody attaches a thread to the VM. Also consider changing this
1304 * to a static method so we don't have a null "this" pointer in the
1305 * "ins" on the stack. (Does it really need to look like a Runnable?)
1306 */
1307 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001308 if (nativeStart == NULL) {
1309 LOGE("Unable to find dalvik.system.NativeStart class\n");
1310 return false;
1311 }
1312
1313 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1314 if (runMeth == NULL) {
1315 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1316 return false;
1317 }
1318
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001319 if (!dvmPushJNIFrame(thread, runMeth))
1320 return false;
1321
1322 /*
1323 * Provide a NULL 'this' argument. The method we've put at the top of
1324 * the stack looks like a virtual call to run() in a Runnable class.
1325 * (If we declared the method static, it wouldn't take any arguments
1326 * and we wouldn't have to do this.)
1327 */
1328 assert(runMeth->registersSize == 1);
1329 u4* framePtr = (u4*) thread->curFrame;
1330 framePtr[0] = 0;
1331
1332 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001333}
1334
1335/*
1336 * Helper function to set the name of the current thread
1337 */
1338static void setThreadName(const char *threadName)
1339{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001340 int hasAt = 0;
1341 int hasDot = 0;
1342 const char *s = threadName;
1343 while (*s) {
1344 if (*s == '.') hasDot = 1;
1345 else if (*s == '@') hasAt = 1;
1346 s++;
1347 }
1348 int len = s - threadName;
1349 if (len < 15 || hasAt || !hasDot) {
1350 s = threadName;
1351 } else {
1352 s = threadName + len - 15;
1353 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001354#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001355 if (pthread_setname_np(pthread_self(), s) != 0)
1356 LOGW("Unable to set the name of the current thread\n");
1357#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001358 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001359#else
1360 LOGD("Unable to set current thread's name: %s\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001361#endif
1362}
1363
1364/*
1365 * Create a thread as a result of java.lang.Thread.start().
1366 *
1367 * We do have to worry about some concurrency problems, e.g. programs
1368 * that try to call Thread.start() on the same object from multiple threads.
1369 * (This will fail for all but one, but we have to make sure that it succeeds
1370 * for exactly one.)
1371 *
1372 * Some of the complexity here arises from our desire to mimic the
1373 * Thread vs. VMThread class decomposition we inherited. We've been given
1374 * a Thread, and now we need to create a VMThread and then populate both
1375 * objects. We also need to create one of our internal Thread objects.
1376 *
1377 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001378 *
1379 * The "threadObj" reference must be pinned by the caller to prevent the GC
1380 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001381 */
1382bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1383{
1384 pthread_attr_t threadAttr;
1385 pthread_t threadHandle;
1386 Thread* self;
1387 Thread* newThread = NULL;
1388 Object* vmThreadObj = NULL;
1389 int stackSize;
1390
1391 assert(threadObj != NULL);
1392
1393 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001394 // Allow the sampling profiler thread. We shut it down before forking.
1395 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1396 gDvm.offJavaLangThread_name);
1397 char* threadName = dvmCreateCstrFromString(nameStr);
1398 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1399 free(threadName);
1400 if (!profilerThread) {
1401 dvmThrowException("Ljava/lang/IllegalStateException;",
1402 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001403
Bob Lee9dc72a32009-09-04 18:28:16 -07001404 goto fail;
1405 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001406 }
1407
1408 self = dvmThreadSelf();
1409 if (reqStackSize == 0)
1410 stackSize = gDvm.stackSize;
1411 else if (reqStackSize < kMinStackSize)
1412 stackSize = kMinStackSize;
1413 else if (reqStackSize > kMaxStackSize)
1414 stackSize = kMaxStackSize;
1415 else
1416 stackSize = reqStackSize;
1417
1418 pthread_attr_init(&threadAttr);
1419 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1420
1421 /*
1422 * To minimize the time spent in the critical section, we allocate the
1423 * vmThread object here.
1424 */
1425 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1426 if (vmThreadObj == NULL)
1427 goto fail;
1428
1429 newThread = allocThread(stackSize);
1430 if (newThread == NULL)
1431 goto fail;
1432 newThread->threadObj = threadObj;
1433
1434 assert(newThread->status == THREAD_INITIALIZING);
1435
1436 /*
1437 * We need to lock out other threads while we test and set the
1438 * "vmThread" field in java.lang.Thread, because we use that to determine
1439 * if this thread has been started before. We use the thread list lock
1440 * because it's handy and we're going to need to grab it again soon
1441 * anyway.
1442 */
1443 dvmLockThreadList(self);
1444
1445 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1446 dvmUnlockThreadList();
1447 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1448 "thread has already been started");
1449 goto fail;
1450 }
1451
1452 /*
1453 * There are actually three data structures: Thread (object), VMThread
1454 * (object), and Thread (C struct). All of them point to at least one
1455 * other.
1456 *
1457 * As soon as "VMThread.vmData" is assigned, other threads can start
1458 * making calls into us (e.g. setPriority).
1459 */
1460 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1461 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1462
1463 /*
1464 * Thread creation might take a while, so release the lock.
1465 */
1466 dvmUnlockThreadList();
1467
Andy McFadden2aa43612009-06-17 16:29:30 -07001468 int cc, oldStatus;
1469 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1470 cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1471 newThread);
1472 oldStatus = dvmChangeStatus(self, oldStatus);
1473
1474 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001475 /*
1476 * Failure generally indicates that we have exceeded system
1477 * resource limits. VirtualMachineError is probably too severe,
1478 * so use OutOfMemoryError.
1479 */
1480 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1481
1482 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1483
1484 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1485 "thread creation failed");
1486 goto fail;
1487 }
1488
1489 /*
1490 * We need to wait for the thread to start. Otherwise, depending on
1491 * the whims of the OS scheduler, we could return and the code in our
1492 * thread could try to do operations on the new thread before it had
1493 * finished starting.
1494 *
1495 * The new thread will lock the thread list, change its state to
1496 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1497 * on gDvm.threadStartCond (which uses the thread list lock). This
1498 * thread (the parent) will either see that the thread is already ready
1499 * after we grab the thread list lock, or will be awakened from the
1500 * condition variable on the broadcast.
1501 *
1502 * We don't want to stall the rest of the VM while the new thread
1503 * starts, which can happen if the GC wakes up at the wrong moment.
1504 * So, we change our own status to VMWAIT, and self-suspend if
1505 * necessary after we finish adding the new thread.
1506 *
1507 *
1508 * We have to deal with an odd race with the GC/debugger suspension
1509 * mechanism when creating a new thread. The information about whether
1510 * or not a thread should be suspended is contained entirely within
1511 * the Thread struct; this is usually cleaner to deal with than having
1512 * one or more globally-visible suspension flags. The trouble is that
1513 * we could create the thread while the VM is trying to suspend all
1514 * threads. The suspend-count won't be nonzero for the new thread,
1515 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1516 *
1517 * The easiest way to deal with this is to prevent the new thread from
1518 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001519 * following (correct) sequence of events for a "badly timed" GC
1520 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001521 *
1522 * - call pthread_create()
1523 * - lock thread list
1524 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1525 * - sleep on condition var (mutex = thread list lock) until child starts
1526 * + GC triggered by another thread
1527 * + thread list locked; suspend counts updated; thread list unlocked
1528 * + loop waiting for all runnable threads to suspend
1529 * + success, start GC
1530 * o child thread wakes, signals condition var to wake parent
1531 * o child waits for parent ack on condition variable
1532 * - we wake up, locking thread list
1533 * - add child to thread list
1534 * - unlock thread list
1535 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1536 * + GC finishes; all threads in thread list are resumed
1537 * - lock thread list
1538 * - set child to THREAD_VMWAIT, and signal it to start
1539 * - unlock thread list
1540 * o child resumes
1541 * o child changes state to THREAD_RUNNING
1542 *
1543 * The above shows the GC starting up during thread creation, but if
1544 * it starts anywhere after VMThread.create() is called it will
1545 * produce the same series of events.
1546 *
1547 * Once the child is in the thread list, it will be suspended and
1548 * resumed like any other thread. In the above scenario the resume-all
1549 * code will try to resume the new thread, which was never actually
1550 * suspended, and try to decrement the child's thread suspend count to -1.
1551 * We can catch this in the resume-all code.
1552 *
1553 * Bouncing back and forth between threads like this adds a small amount
1554 * of scheduler overhead to thread startup.
1555 *
1556 * One alternative to having the child wait for the parent would be
1557 * to have the child inherit the parents' suspension count. This
1558 * would work for a GC, since we can safely assume that the parent
1559 * thread didn't cause it, but we must only do so if the parent suspension
1560 * was caused by a suspend-all. If the parent was being asked to
1561 * suspend singly by the debugger, the child should not inherit the value.
1562 *
1563 * We could also have a global "new thread suspend count" that gets
1564 * picked up by new threads before changing state to THREAD_RUNNING.
1565 * This would be protected by the thread list lock and set by a
1566 * suspend-all.
1567 */
1568 dvmLockThreadList(self);
1569 assert(self->status == THREAD_RUNNING);
1570 self->status = THREAD_VMWAIT;
1571 while (newThread->status != THREAD_STARTING)
1572 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1573
1574 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1575 newThread->next = gDvm.threadList->next;
1576 if (newThread->next != NULL)
1577 newThread->next->prev = newThread;
1578 newThread->prev = gDvm.threadList;
1579 gDvm.threadList->next = newThread;
1580
1581 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1582 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1583
1584 dvmUnlockThreadList();
1585
1586 /* change status back to RUNNING, self-suspending if necessary */
1587 dvmChangeStatus(self, THREAD_RUNNING);
1588
1589 /*
1590 * Tell the new thread to start.
1591 *
1592 * We must hold the thread list lock before messing with another thread.
1593 * In the general case we would also need to verify that newThread was
1594 * still in the thread list, but in our case the thread has not started
1595 * executing user code and therefore has not had a chance to exit.
1596 *
1597 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1598 * comes with a suspend-pending check.
1599 */
1600 dvmLockThreadList(self);
1601
1602 assert(newThread->status == THREAD_STARTING);
1603 newThread->status = THREAD_VMWAIT;
1604 pthread_cond_broadcast(&gDvm.threadStartCond);
1605
1606 dvmUnlockThreadList();
1607
1608 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1609 return true;
1610
1611fail:
1612 freeThread(newThread);
1613 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1614 return false;
1615}
1616
1617/*
1618 * pthread entry function for threads started from interpreted code.
1619 */
1620static void* interpThreadStart(void* arg)
1621{
1622 Thread* self = (Thread*) arg;
1623
1624 char *threadName = dvmGetThreadName(self);
1625 setThreadName(threadName);
1626 free(threadName);
1627
1628 /*
1629 * Finish initializing the Thread struct.
1630 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001631 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001632 prepareThread(self);
1633
1634 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1635
1636 /*
1637 * Change our status and wake our parent, who will add us to the
1638 * thread list and advance our state to VMWAIT.
1639 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001640 self->status = THREAD_STARTING;
1641 pthread_cond_broadcast(&gDvm.threadStartCond);
1642
1643 /*
1644 * Wait until the parent says we can go. Assuming there wasn't a
1645 * suspend pending, this will happen immediately. When it completes,
1646 * we're full-fledged citizens of the VM.
1647 *
1648 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1649 * because the pthread_cond_wait below needs to reacquire a lock that
1650 * suspend-all is also interested in. If we get unlucky, the parent could
1651 * change us to THREAD_RUNNING, then a GC could start before we get
1652 * signaled, and suspend-all will grab the thread list lock and then
1653 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1654 * trying to get the lock.
1655 */
1656 while (self->status != THREAD_VMWAIT)
1657 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1658
1659 dvmUnlockThreadList();
1660
1661 /*
1662 * Add a JNI context.
1663 */
1664 self->jniEnv = dvmCreateJNIEnv(self);
1665
1666 /*
1667 * Change our state so the GC will wait for us from now on. If a GC is
1668 * in progress this call will suspend us.
1669 */
1670 dvmChangeStatus(self, THREAD_RUNNING);
1671
1672 /*
1673 * Notify the debugger & DDM. The debugger notification may cause
1674 * us to suspend ourselves (and others).
1675 */
1676 if (gDvm.debuggerConnected)
1677 dvmDbgPostThreadStart(self);
1678
1679 /*
1680 * Set the system thread priority according to the Thread object's
1681 * priority level. We don't usually need to do this, because both the
1682 * Thread object and system thread priorities inherit from parents. The
1683 * tricky case is when somebody creates a Thread object, calls
1684 * setPriority(), and then starts the thread. We could manage this with
1685 * a "needs priority update" flag to avoid the redundant call.
1686 */
Andy McFadden4879df92009-08-07 14:49:40 -07001687 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001688 gDvm.offJavaLangThread_priority);
1689 dvmChangeThreadPriority(self, priority);
1690
1691 /*
1692 * Execute the "run" method.
1693 *
1694 * At this point our stack is empty, so somebody who comes looking for
1695 * stack traces right now won't have much to look at. This is normal.
1696 */
1697 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1698 JValue unused;
1699
1700 LOGV("threadid=%d: calling run()\n", self->threadId);
1701 assert(strcmp(run->name, "run") == 0);
1702 dvmCallMethod(self, run, self->threadObj, &unused);
1703 LOGV("threadid=%d: exiting\n", self->threadId);
1704
1705 /*
1706 * Remove the thread from various lists, report its death, and free
1707 * its resources.
1708 */
1709 dvmDetachCurrentThread();
1710
1711 return NULL;
1712}
1713
1714/*
1715 * The current thread is exiting with an uncaught exception. The
1716 * Java programming language allows the application to provide a
1717 * thread-exit-uncaught-exception handler for the VM, for a specific
1718 * Thread, and for all threads in a ThreadGroup.
1719 *
1720 * Version 1.5 added the per-thread handler. We need to call
1721 * "uncaughtException" in the handler object, which is either the
1722 * ThreadGroup object or the Thread-specific handler.
1723 */
1724static void threadExitUncaughtException(Thread* self, Object* group)
1725{
1726 Object* exception;
1727 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001728 Method* uncaughtHandler = NULL;
1729 InstField* threadHandler;
1730
1731 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1732 self->threadId, group);
1733 assert(group != NULL);
1734
1735 /*
1736 * Get a pointer to the exception, then clear out the one in the
1737 * thread. We don't want to have it set when executing interpreted code.
1738 */
1739 exception = dvmGetException(self);
1740 dvmAddTrackedAlloc(exception, self);
1741 dvmClearException(self);
1742
1743 /*
1744 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1745 * else use "group" (which is an instance of UncaughtExceptionHandler).
1746 */
1747 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1748 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1749 if (threadHandler == NULL) {
1750 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1751 goto bail;
1752 }
1753 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1754 if (handlerObj == NULL)
1755 handlerObj = group;
1756
1757 /*
1758 * Find the "uncaughtHandler" field in this object.
1759 */
1760 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1761 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1762
1763 if (uncaughtHandler != NULL) {
1764 //LOGI("+++ calling %s.uncaughtException\n",
1765 // handlerObj->clazz->descriptor);
1766 JValue unused;
1767 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1768 self->threadObj, exception);
1769 } else {
1770 /* restore it and dump a stack trace */
1771 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1772 handlerObj->clazz->descriptor);
1773 dvmSetException(self, exception);
1774 dvmLogExceptionStackTrace();
1775 }
1776
1777bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001778#if defined(WITH_JIT)
1779 /* Remove this thread's suspendCount from global suspendCount sum */
1780 lockThreadSuspendCount();
1781 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1782 unlockThreadSuspendCount();
1783#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001784 dvmReleaseTrackedAlloc(exception, self);
1785}
1786
1787
1788/*
1789 * Create an internal VM thread, for things like JDWP and finalizers.
1790 *
1791 * The easiest way to do this is create a new thread and then use the
1792 * JNI AttachCurrentThread implementation.
1793 *
1794 * This does not return until after the new thread has begun executing.
1795 */
1796bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1797 InternalThreadStart func, void* funcArg)
1798{
1799 InternalStartArgs* pArgs;
1800 Object* systemGroup;
1801 pthread_attr_t threadAttr;
1802 volatile Thread* newThread = NULL;
1803 volatile int createStatus = 0;
1804
1805 systemGroup = dvmGetSystemThreadGroup();
1806 if (systemGroup == NULL)
1807 return false;
1808
1809 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1810 pArgs->func = func;
1811 pArgs->funcArg = funcArg;
1812 pArgs->name = strdup(name); // storage will be owned by new thread
1813 pArgs->group = systemGroup;
1814 pArgs->isDaemon = true;
1815 pArgs->pThread = &newThread;
1816 pArgs->pCreateStatus = &createStatus;
1817
1818 pthread_attr_init(&threadAttr);
1819 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1820
1821 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1822 pArgs) != 0)
1823 {
1824 LOGE("internal thread creation failed\n");
1825 free(pArgs->name);
1826 free(pArgs);
1827 return false;
1828 }
1829
1830 /*
1831 * Wait for the child to start. This gives us an opportunity to make
1832 * sure that the thread started correctly, and allows our caller to
1833 * assume that the thread has started running.
1834 *
1835 * Because we aren't holding a lock across the thread creation, it's
1836 * possible that the child will already have completed its
1837 * initialization. Because the child only adjusts "createStatus" while
1838 * holding the thread list lock, the initial condition on the "while"
1839 * loop will correctly avoid the wait if this occurs.
1840 *
1841 * It's also possible that we'll have to wait for the thread to finish
1842 * being created, and as part of allocating a Thread object it might
1843 * need to initiate a GC. We switch to VMWAIT while we pause.
1844 */
1845 Thread* self = dvmThreadSelf();
1846 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1847 dvmLockThreadList(self);
1848 while (createStatus == 0)
1849 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1850
1851 if (newThread == NULL) {
1852 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1853 assert(createStatus < 0);
1854 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1855 dvmUnlockThreadList();
1856 dvmChangeStatus(self, oldStatus);
1857 return false;
1858 }
1859
1860 /* thread could be in any state now (except early init states) */
1861 //assert(newThread->status == THREAD_RUNNING);
1862
1863 dvmUnlockThreadList();
1864 dvmChangeStatus(self, oldStatus);
1865
1866 return true;
1867}
1868
1869/*
1870 * pthread entry function for internally-created threads.
1871 *
1872 * We are expected to free "arg" and its contents. If we're a daemon
1873 * thread, and we get cancelled abruptly when the VM shuts down, the
1874 * storage won't be freed. If this becomes a concern we can make a copy
1875 * on the stack.
1876 */
1877static void* internalThreadStart(void* arg)
1878{
1879 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1880 JavaVMAttachArgs jniArgs;
1881
1882 jniArgs.version = JNI_VERSION_1_2;
1883 jniArgs.name = pArgs->name;
1884 jniArgs.group = pArgs->group;
1885
1886 setThreadName(pArgs->name);
1887
1888 /* use local jniArgs as stack top */
1889 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1890 /*
1891 * Tell the parent of our success.
1892 *
1893 * threadListLock is the mutex for threadStartCond.
1894 */
1895 dvmLockThreadList(dvmThreadSelf());
1896 *pArgs->pCreateStatus = 1;
1897 *pArgs->pThread = dvmThreadSelf();
1898 pthread_cond_broadcast(&gDvm.threadStartCond);
1899 dvmUnlockThreadList();
1900
1901 LOG_THREAD("threadid=%d: internal '%s'\n",
1902 dvmThreadSelf()->threadId, pArgs->name);
1903
1904 /* execute */
1905 (*pArgs->func)(pArgs->funcArg);
1906
1907 /* detach ourselves */
1908 dvmDetachCurrentThread();
1909 } else {
1910 /*
1911 * Tell the parent of our failure. We don't have a Thread struct,
1912 * so we can't be suspended, so we don't need to enter a critical
1913 * section.
1914 */
1915 dvmLockThreadList(dvmThreadSelf());
1916 *pArgs->pCreateStatus = -1;
1917 assert(*pArgs->pThread == NULL);
1918 pthread_cond_broadcast(&gDvm.threadStartCond);
1919 dvmUnlockThreadList();
1920
1921 assert(*pArgs->pThread == NULL);
1922 }
1923
1924 free(pArgs->name);
1925 free(pArgs);
1926 return NULL;
1927}
1928
1929/*
1930 * Attach the current thread to the VM.
1931 *
1932 * Used for internally-created threads and JNI's AttachCurrentThread.
1933 */
1934bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1935{
1936 Thread* self = NULL;
1937 Object* threadObj = NULL;
1938 Object* vmThreadObj = NULL;
1939 StringObject* threadNameStr = NULL;
1940 Method* init;
1941 bool ok, ret;
1942
Andy McFaddene3346d82010-06-02 15:37:21 -07001943 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001944 self = allocThread(gDvm.stackSize);
1945 if (self == NULL)
1946 goto fail;
1947 setThreadSelf(self);
1948
1949 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001950 * Finish our thread prep. We need to do this before adding ourselves
1951 * to the thread list or invoking any interpreted code. prepareThread()
1952 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001953 */
1954 dvmLockThreadList(self);
1955 ok = prepareThread(self);
1956 dvmUnlockThreadList();
1957 if (!ok)
1958 goto fail;
1959
1960 self->jniEnv = dvmCreateJNIEnv(self);
1961 if (self->jniEnv == NULL)
1962 goto fail;
1963
1964 /*
1965 * Create a "fake" JNI frame at the top of the main thread interp stack.
1966 * It isn't really necessary for the internal threads, but it gives
1967 * the debugger something to show. It is essential for the JNI-attached
1968 * threads.
1969 */
1970 if (!createFakeRunFrame(self))
1971 goto fail;
1972
1973 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001974 * The native side of the thread is ready; add it to the list. Once
1975 * 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 -08001976 */
1977 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1978
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001979 dvmLockThreadList(self);
1980
1981 self->next = gDvm.threadList->next;
1982 if (self->next != NULL)
1983 self->next->prev = self;
1984 self->prev = gDvm.threadList;
1985 gDvm.threadList->next = self;
1986 if (!isDaemon)
1987 gDvm.nonDaemonThreadCount++;
1988
1989 dvmUnlockThreadList();
1990
1991 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001992 * Switch state from initializing to running.
1993 *
1994 * It's possible that a GC began right before we added ourselves
1995 * to the thread list, and is still going. That means our thread
1996 * suspend count won't reflect the fact that we should be suspended.
1997 * To deal with this, we transition to VMWAIT, pulse the heap lock,
1998 * and then advance to RUNNING. That will ensure that we stall until
1999 * the GC completes.
2000 *
2001 * Once we're in RUNNING, we're like any other thread in the VM (except
2002 * for the lack of an initialized threadObj). We're then free to
2003 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002004 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002005 assert(self->status == THREAD_INITIALIZING);
2006 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002007 dvmLockMutex(&gDvm.gcHeapLock);
2008 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002009 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002010
2011 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002012 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002013 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002014 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2015 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2016 if (threadObj == NULL || vmThreadObj == NULL)
2017 goto fail_unlink;
2018
2019 /*
2020 * This makes threadObj visible to the GC. We still have it in the
2021 * tracked allocation table, so it can't move around on us.
2022 */
2023 self->threadObj = threadObj;
2024 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2025
2026 /*
2027 * Create a string for the thread name.
2028 */
2029 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002030 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002031 if (threadNameStr == NULL) {
2032 assert(dvmCheckException(dvmThreadSelf()));
2033 goto fail_unlink;
2034 }
2035 }
2036
2037 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2038 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2039 if (init == NULL) {
2040 assert(dvmCheckException(self));
2041 goto fail_unlink;
2042 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002043
2044 /*
2045 * Now we're ready to run some interpreted code.
2046 *
2047 * We need to construct the Thread object and set the VMThread field.
2048 * Setting VMThread tells interpreted code that we're alive.
2049 *
2050 * Call the (group, name, priority, daemon) constructor on the Thread.
2051 * This sets the thread's name and adds it to the specified group, and
2052 * provides values for priority and daemon (which are normally inherited
2053 * from the current thread).
2054 */
2055 JValue unused;
2056 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2057 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2058 if (dvmCheckException(self)) {
2059 LOGE("exception thrown while constructing attached thread object\n");
2060 goto fail_unlink;
2061 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002062
2063 /*
2064 * Set the VMThread field, which tells interpreted code that we're alive.
2065 *
2066 * The risk of a thread start collision here is very low; somebody
2067 * would have to be deliberately polling the ThreadGroup list and
2068 * trying to start threads against anything it sees, which would
2069 * generally cause problems for all thread creation. However, for
2070 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002071 *
2072 * TODO: this still has a race, it's just smaller. Not sure this is
2073 * worth putting effort into fixing. Need to hold a lock while
2074 * fiddling with the field, or maybe initialize the Thread object in a
2075 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002076 */
2077 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002078 LOGW("WOW: thread start hijack\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002079 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2080 "thread has already been started");
2081 /* We don't want to free anything associated with the thread
2082 * because someone is obviously interested in it. Just let
2083 * it go and hope it will clean itself up when its finished.
2084 * This case should never happen anyway.
2085 *
2086 * Since we're letting it live, we need to finish setting it up.
2087 * We just have to let the caller know that the intended operation
2088 * has failed.
2089 *
2090 * [ This seems strange -- stepping on the vmThread object that's
2091 * already present seems like a bad idea. TODO: figure this out. ]
2092 */
2093 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002094 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002095 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002096 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002097 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2098
Andy McFaddene3346d82010-06-02 15:37:21 -07002099 /* we can now safely un-pin these */
2100 dvmReleaseTrackedAlloc(threadObj, self);
2101 dvmReleaseTrackedAlloc(vmThreadObj, self);
2102 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002103
2104 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2105 self->threadId, pArgs->name);
2106
2107 /* tell the debugger & DDM */
2108 if (gDvm.debuggerConnected)
2109 dvmDbgPostThreadStart(self);
2110
2111 return ret;
2112
2113fail_unlink:
2114 dvmLockThreadList(self);
2115 unlinkThread(self);
2116 if (!isDaemon)
2117 gDvm.nonDaemonThreadCount--;
2118 dvmUnlockThreadList();
2119 /* fall through to "fail" */
2120fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002121 dvmReleaseTrackedAlloc(threadObj, self);
2122 dvmReleaseTrackedAlloc(vmThreadObj, self);
2123 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002124 if (self != NULL) {
2125 if (self->jniEnv != NULL) {
2126 dvmDestroyJNIEnv(self->jniEnv);
2127 self->jniEnv = NULL;
2128 }
2129 freeThread(self);
2130 }
2131 setThreadSelf(NULL);
2132 return false;
2133}
2134
2135/*
2136 * Detach the thread from the various data structures, notify other threads
2137 * that are waiting to "join" it, and free up all heap-allocated storage.
2138 *
2139 * Used for all threads.
2140 *
2141 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2142 * requires us to enforce this for the DetachCurrentThread call, probably
2143 * because it also says that DetachCurrentThread causes all monitors
2144 * associated with the thread to be released. (Because the stack is empty,
2145 * we only have to worry about explicit JNI calls to MonitorEnter.)
2146 *
2147 * THOUGHT:
2148 * We might want to avoid freeing our internal Thread structure until the
2149 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2150 * get to once the thread shuts down, but there is a small possibility of
2151 * an operation starting in another thread before this thread halts, and
2152 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2153 * We don't want something like Thread.isInterrupted() crawling through
2154 * freed storage. Can do with a Thread finalizer, or by creating a
2155 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2156 * state into that.
2157 */
2158void dvmDetachCurrentThread(void)
2159{
2160 Thread* self = dvmThreadSelf();
2161 Object* vmThread;
2162 Object* group;
2163
2164 /*
2165 * Make sure we're not detaching a thread that's still running. (This
2166 * could happen with an explicit JNI detach call.)
2167 *
2168 * A thread created by interpreted code will finish with a depth of
2169 * zero, while a JNI-attached thread will have the synthetic "stack
2170 * starter" native method at the top.
2171 */
2172 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2173 if (curDepth != 0) {
2174 bool topIsNative = false;
2175
2176 if (curDepth == 1) {
2177 /* not expecting a lingering break frame; just look at curFrame */
2178 assert(!dvmIsBreakFrame(self->curFrame));
2179 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2180 if (dvmIsNativeMethod(ssa->method))
2181 topIsNative = true;
2182 }
2183
2184 if (!topIsNative) {
2185 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2186 curDepth);
2187 dvmDumpThread(self, false);
2188 dvmAbort();
2189 }
2190 }
2191
2192 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2193 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2194
2195 /*
2196 * Release any held monitors. Since there are no interpreted stack
2197 * frames, the only thing left are the monitors held by JNI MonitorEnter
2198 * calls.
2199 */
2200 dvmReleaseJniMonitors(self);
2201
2202 /*
2203 * Do some thread-exit uncaught exception processing if necessary.
2204 */
2205 if (dvmCheckException(self))
2206 threadExitUncaughtException(self, group);
2207
2208 /*
2209 * Remove the thread from the thread group.
2210 */
2211 if (group != NULL) {
2212 Method* removeThread =
2213 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2214 JValue unused;
2215 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2216 }
2217
2218 /*
2219 * Clear the vmThread reference in the Thread object. Interpreted code
2220 * will now see that this Thread is not running. As this may be the
2221 * only reference to the VMThread object that the VM knows about, we
2222 * have to create an internal reference to it first.
2223 */
2224 vmThread = dvmGetFieldObject(self->threadObj,
2225 gDvm.offJavaLangThread_vmThread);
2226 dvmAddTrackedAlloc(vmThread, self);
2227 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2228
2229 /* clear out our struct Thread pointer, since it's going away */
2230 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2231
2232 /*
2233 * Tell the debugger & DDM. This may cause the current thread or all
2234 * threads to suspend.
2235 *
2236 * The JDWP spec is somewhat vague about when this happens, other than
2237 * that it's issued by the dying thread, which may still appear in
2238 * an "all threads" listing.
2239 */
2240 if (gDvm.debuggerConnected)
2241 dvmDbgPostThreadDeath(self);
2242
2243 /*
2244 * Thread.join() is implemented as an Object.wait() on the VMThread
2245 * object. Signal anyone who is waiting.
2246 */
2247 dvmLockObject(self, vmThread);
2248 dvmObjectNotifyAll(self, vmThread);
2249 dvmUnlockObject(self, vmThread);
2250
2251 dvmReleaseTrackedAlloc(vmThread, self);
2252 vmThread = NULL;
2253
2254 /*
2255 * We're done manipulating objects, so it's okay if the GC runs in
2256 * parallel with us from here out. It's important to do this if
2257 * profiling is enabled, since we can wait indefinitely.
2258 */
2259 self->status = THREAD_VMWAIT;
2260
2261#ifdef WITH_PROFILER
2262 /*
2263 * If we're doing method trace profiling, we don't want threads to exit,
2264 * because if they do we'll end up reusing thread IDs. This complicates
2265 * analysis and makes it impossible to have reasonable output in the
2266 * "threads" section of the "key" file.
2267 *
2268 * We need to do this after Thread.join() completes, or other threads
2269 * could get wedged. Since self->threadObj is still valid, the Thread
2270 * object will not get GCed even though we're no longer in the ThreadGroup
2271 * list (which is important since the profiling thread needs to get
2272 * the thread's name).
2273 */
2274 MethodTraceState* traceState = &gDvm.methodTrace;
2275
2276 dvmLockMutex(&traceState->startStopLock);
2277 if (traceState->traceEnabled) {
2278 LOGI("threadid=%d: waiting for method trace to finish\n",
2279 self->threadId);
2280 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002281 dvmWaitCond(&traceState->threadExitCond,
2282 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002283 }
2284 }
2285 dvmUnlockMutex(&traceState->startStopLock);
2286#endif
2287
2288 dvmLockThreadList(self);
2289
2290 /*
2291 * Lose the JNI context.
2292 */
2293 dvmDestroyJNIEnv(self->jniEnv);
2294 self->jniEnv = NULL;
2295
2296 self->status = THREAD_ZOMBIE;
2297
2298 /*
2299 * Remove ourselves from the internal thread list.
2300 */
2301 unlinkThread(self);
2302
2303 /*
2304 * If we're the last one standing, signal anybody waiting in
2305 * DestroyJavaVM that it's okay to exit.
2306 */
2307 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2308 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2309
2310 if (gDvm.nonDaemonThreadCount == 0) {
2311 int cc;
2312
2313 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2314 //dvmDumpAllThreads(false);
2315 // cond var guarded by threadListLock, which we already hold
2316 cc = pthread_cond_signal(&gDvm.vmExitCond);
2317 assert(cc == 0);
2318 }
2319 }
2320
2321 LOGV("threadid=%d: bye!\n", self->threadId);
2322 releaseThreadId(self);
2323 dvmUnlockThreadList();
2324
2325 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002326
Bob Lee2fe146a2009-09-10 00:36:29 +02002327 dvmDetachSystemThread(self);
Bob Lee9dc72a32009-09-04 18:28:16 -07002328
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002329 freeThread(self);
2330}
2331
2332
2333/*
2334 * Suspend a single thread. Do not use to suspend yourself.
2335 *
2336 * This is used primarily for debugger/DDMS activity. Does not return
2337 * until the thread has suspended or is in a "safe" state (e.g. executing
2338 * native code outside the VM).
2339 *
2340 * The thread list lock should be held before calling here -- it's not
2341 * entirely safe to hang on to a Thread* from another thread otherwise.
2342 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2343 */
2344void dvmSuspendThread(Thread* thread)
2345{
2346 assert(thread != NULL);
2347 assert(thread != dvmThreadSelf());
2348 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2349
2350 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002351 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002352 thread->dbgSuspendCount++;
2353
2354 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2355 thread->threadId, thread->suspendCount);
2356 unlockThreadSuspendCount();
2357
2358 waitForThreadSuspend(dvmThreadSelf(), thread);
2359}
2360
2361/*
2362 * Reduce the suspend count of a thread. If it hits zero, tell it to
2363 * resume.
2364 *
2365 * Used primarily for debugger/DDMS activity. The thread in question
2366 * might have been suspended singly or as part of a suspend-all operation.
2367 *
2368 * The thread list lock should be held before calling here -- it's not
2369 * entirely safe to hang on to a Thread* from another thread otherwise.
2370 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2371 */
2372void dvmResumeThread(Thread* thread)
2373{
2374 assert(thread != NULL);
2375 assert(thread != dvmThreadSelf());
2376 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2377
2378 lockThreadSuspendCount();
2379 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002380 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002381 thread->dbgSuspendCount--;
2382 } else {
2383 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2384 thread->threadId);
2385 }
2386
2387 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2388 thread->threadId, thread->suspendCount);
2389
2390 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002391 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002392 }
2393
2394 unlockThreadSuspendCount();
2395}
2396
2397/*
2398 * Suspend yourself, as a result of debugger activity.
2399 */
2400void dvmSuspendSelf(bool jdwpActivity)
2401{
2402 Thread* self = dvmThreadSelf();
2403
2404 /* debugger thread may not suspend itself due to debugger activity! */
2405 assert(gDvm.jdwpState != NULL);
2406 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2407 assert(false);
2408 return;
2409 }
2410
2411 /*
2412 * Collisions with other suspends aren't really interesting. We want
2413 * to ensure that we're the only one fiddling with the suspend count
2414 * though.
2415 */
2416 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002417 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002418 self->dbgSuspendCount++;
2419
2420 /*
2421 * Suspend ourselves.
2422 */
2423 assert(self->suspendCount > 0);
2424 self->isSuspended = true;
2425 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2426
2427 /*
2428 * Tell JDWP that we've completed suspension. The JDWP thread can't
2429 * tell us to resume before we're fully asleep because we hold the
2430 * suspend count lock.
2431 *
2432 * If we got here via waitForDebugger(), don't do this part.
2433 */
2434 if (jdwpActivity) {
2435 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2436 // self->threadId, (int) self->handle);
2437 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2438 }
2439
2440 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002441 dvmWaitCond(&gDvm.threadSuspendCountCond,
2442 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002443 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002444 /*
2445 * The condition was signaled but we're still suspended. This
2446 * can happen if the debugger lets go while a SIGQUIT thread
2447 * dump event is pending (assuming SignalCatcher was resumed for
2448 * just long enough to try to grab the thread-suspend lock).
2449 */
2450 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
2451 self->threadId, self->suspendCount, self->dbgSuspendCount,
2452 self->isSuspended ? 'Y' : 'N');
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002453 }
2454 }
2455 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2456 self->isSuspended = false;
2457 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2458 self->threadId, self->status);
2459
2460 unlockThreadSuspendCount();
2461}
2462
2463
2464#ifdef HAVE_GLIBC
2465# define NUM_FRAMES 20
2466# include <execinfo.h>
2467/*
2468 * glibc-only stack dump function. Requires link with "--export-dynamic".
2469 *
2470 * TODO: move this into libs/cutils and make it work for all platforms.
2471 */
2472static void printBackTrace(void)
2473{
2474 void* array[NUM_FRAMES];
2475 size_t size;
2476 char** strings;
2477 size_t i;
2478
2479 size = backtrace(array, NUM_FRAMES);
2480 strings = backtrace_symbols(array, size);
2481
2482 LOGW("Obtained %zd stack frames.\n", size);
2483
2484 for (i = 0; i < size; i++)
2485 LOGW("%s\n", strings[i]);
2486
2487 free(strings);
2488}
2489#else
2490static void printBackTrace(void) {}
2491#endif
2492
2493/*
2494 * Dump the state of the current thread and that of another thread that
2495 * we think is wedged.
2496 */
2497static void dumpWedgedThread(Thread* thread)
2498{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002499 dvmDumpThread(dvmThreadSelf(), false);
2500 printBackTrace();
2501
2502 // dumping a running thread is risky, but could be useful
2503 dvmDumpThread(thread, true);
2504
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002505 // stop now and get a core dump
2506 //abort();
2507}
2508
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002509/*
2510 * If the thread is running at below-normal priority, temporarily elevate
2511 * it to "normal".
2512 *
2513 * Returns zero if no changes were made. Otherwise, returns bit flags
2514 * indicating what was changed, storing the previous values in the
2515 * provided locations.
2516 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002517int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002518 SchedPolicy* pSavedThreadPolicy)
2519{
2520 errno = 0;
2521 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2522 if (errno != 0) {
2523 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2524 thread->threadId, thread->systemTid);
2525 return 0;
2526 }
2527 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2528 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2529 thread->threadId, thread->systemTid);
2530 return 0;
2531 }
2532
2533 int changeFlags = 0;
2534
2535 /*
2536 * Change the priority if we're in the background group.
2537 */
2538 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2539 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2540 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2541 } else {
2542 changeFlags |= kChangedPolicy;
2543 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2544 thread->systemTid, *pSavedThreadPolicy);
2545 }
2546 }
2547
2548 /*
2549 * getpriority() returns the "nice" value, so larger numbers indicate
2550 * lower priority, with 0 being normal.
2551 */
2552 if (*pSavedThreadPrio > 0) {
2553 const int kHigher = 0;
2554 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2555 LOGW("Couldn't raise priority on tid %d to %d\n",
2556 thread->systemTid, kHigher);
2557 } else {
2558 changeFlags |= kChangedPriority;
2559 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2560 thread->systemTid, *pSavedThreadPrio, kHigher);
2561 }
2562 }
2563
2564 return changeFlags;
2565}
2566
2567/*
2568 * Reset the priority values for the thread in question.
2569 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002570void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002571 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2572{
2573 if ((changeFlags & kChangedPolicy) != 0) {
2574 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2575 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2576 thread->systemTid, savedThreadPolicy);
2577 } else {
2578 LOGD("Restored policy of %d to %d\n",
2579 thread->systemTid, savedThreadPolicy);
2580 }
2581 }
2582
2583 if ((changeFlags & kChangedPriority) != 0) {
2584 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2585 {
2586 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2587 thread->systemTid, savedThreadPrio);
2588 } else {
2589 LOGD("Restored priority on %d to %d\n",
2590 thread->systemTid, savedThreadPrio);
2591 }
2592 }
2593}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002594
2595/*
2596 * Wait for another thread to see the pending suspension and stop running.
2597 * It can either suspend itself or go into a non-running state such as
2598 * VMWAIT or NATIVE in which it cannot interact with the GC.
2599 *
2600 * If we're running at a higher priority, sched_yield() may not do anything,
2601 * so we need to sleep for "long enough" to guarantee that the other
2602 * thread has a chance to finish what it's doing. Sleeping for too short
2603 * a period (e.g. less than the resolution of the sleep clock) might cause
2604 * the scheduler to return immediately, so we want to start with a
2605 * "reasonable" value and expand.
2606 *
2607 * This does not return until the other thread has stopped running.
2608 * Eventually we time out and the VM aborts.
2609 *
2610 * This does not try to detect the situation where two threads are
2611 * waiting for each other to suspend. In normal use this is part of a
2612 * suspend-all, which implies that the suspend-all lock is held, or as
2613 * part of a debugger action in which the JDWP thread is always the one
2614 * doing the suspending. (We may need to re-evaluate this now that
2615 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2616 *
2617 * TODO: track basic stats about time required to suspend VM.
2618 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002619#define FIRST_SLEEP (250*1000) /* 0.25s */
2620#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002621static void waitForThreadSuspend(Thread* self, Thread* thread)
2622{
2623 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002624 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002625 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002626 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002627 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002628 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002629
2630 int sleepIter = 0;
2631 int retryCount = 0;
2632 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002633 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002634
2635 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002636 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002637 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002638 if (firstStartWhen == 0) // first iteration of first attempt
2639 firstStartWhen = startWhen;
2640
2641 /*
2642 * After waiting for a bit, check to see if the target thread is
2643 * running at a reduced priority. If so, bump it up temporarily
2644 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002645 */
2646 if (retryCount == 2) {
2647 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002648 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002649 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002650 }
2651 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002652
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002653#if defined (WITH_JIT)
2654 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002655 * If we're still waiting after the first timeout, unchain all
2656 * translations iff:
2657 * 1) There are new chains formed since the last unchain
2658 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002659 */
Ben Cheng6999d842010-01-26 16:46:15 -08002660 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2661 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002662 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002663 dvmJitUnchainAll();
2664 }
2665#endif
2666
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002667 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002668 * Sleep briefly. The iterative sleep call returns false if we've
2669 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002670 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002671 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002672 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002673 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002674 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002675 thread->threadId, priChangeFlags);
2676 if (retryCount > 1) {
2677 /* stack trace logging is slow; skip on first iter */
2678 dumpWedgedThread(thread);
2679 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002680 complained = true;
2681 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002682
2683 // keep going; could be slow due to valgrind
2684 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002685 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002686
2687 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002688 LOGE("Fatal spin-on-suspend, dumping threads\n");
2689 dvmDumpAllThreads(false);
2690
2691 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002692 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2693 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002694
2695 /* try to get a debuggerd dump from the spinning thread */
2696 dvmNukeThread(thread);
2697 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002698 dvmAbort();
2699 }
2700 }
2701 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002702
2703 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002704 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2705 self->threadId,
2706 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002707 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2708 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002709 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002710 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002711 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002712 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002713}
2714
2715/*
2716 * Suspend all threads except the current one. This is used by the GC,
2717 * the debugger, and by any thread that hits a "suspend all threads"
2718 * debugger event (e.g. breakpoint or exception).
2719 *
2720 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2721 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2722 * create objects and even execute arbitrary code. The "why" argument
2723 * allows the caller to say why the suspension is taking place.
2724 *
2725 * This can be called when a global suspend has already happened, due to
2726 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2727 * doesn't work.
2728 *
2729 * DO NOT grab any locks before calling here. We grab & release the thread
2730 * lock and suspend lock here (and we're not using recursive threads), and
2731 * we might have to self-suspend if somebody else beats us here.
2732 *
2733 * The current thread may not be attached to the VM. This can happen if
2734 * we happen to GC as the result of an allocation of a Thread object.
2735 */
2736void dvmSuspendAllThreads(SuspendCause why)
2737{
2738 Thread* self = dvmThreadSelf();
2739 Thread* thread;
2740
2741 assert(why != 0);
2742
2743 /*
2744 * Start by grabbing the thread suspend lock. If we can't get it, most
2745 * likely somebody else is in the process of performing a suspend or
2746 * resume, so lockThreadSuspend() will cause us to self-suspend.
2747 *
2748 * We keep the lock until all other threads are suspended.
2749 */
2750 lockThreadSuspend("susp-all", why);
2751
2752 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2753
2754 /*
2755 * This is possible if the current thread was in VMWAIT mode when a
2756 * suspend-all happened, and then decided to do its own suspend-all.
2757 * This can happen when a couple of threads have simultaneous events
2758 * of interest to the debugger.
2759 */
2760 //assert(self->suspendCount == 0);
2761
2762 /*
2763 * Increment everybody's suspend count (except our own).
2764 */
2765 dvmLockThreadList(self);
2766
2767 lockThreadSuspendCount();
2768 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2769 if (thread == self)
2770 continue;
2771
2772 /* debugger events don't suspend JDWP thread */
2773 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2774 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2775 continue;
2776
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002777 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002778 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2779 thread->dbgSuspendCount++;
2780 }
2781 unlockThreadSuspendCount();
2782
2783 /*
2784 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2785 * indicate the code is either running natively or sleeping quietly.
2786 * Any attempt to transition back to THREAD_RUNNING will cause a check
2787 * for suspension, so it should be impossible for anything to execute
2788 * interpreted code or modify objects (assuming native code plays nicely).
2789 *
2790 * It's also okay if the thread transitions to a non-RUNNING state.
2791 *
2792 * Note we released the threadSuspendCountLock before getting here,
2793 * so if another thread is fiddling with its suspend count (perhaps
2794 * self-suspending for the debugger) it won't block while we're waiting
2795 * in here.
2796 */
2797 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2798 if (thread == self)
2799 continue;
2800
2801 /* debugger events don't suspend JDWP thread */
2802 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2803 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2804 continue;
2805
2806 /* wait for the other thread to see the pending suspend */
2807 waitForThreadSuspend(self, thread);
2808
Jeff Hao97319a82009-08-12 16:57:15 -07002809 LOG_THREAD("threadid=%d: threadid=%d status=%d c=%d dc=%d isSusp=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002810 self->threadId,
2811 thread->threadId, thread->status, thread->suspendCount,
2812 thread->dbgSuspendCount, thread->isSuspended);
2813 }
2814
2815 dvmUnlockThreadList();
2816 unlockThreadSuspend();
2817
2818 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2819}
2820
2821/*
2822 * Resume all threads that are currently suspended.
2823 *
2824 * The "why" must match with the previous suspend.
2825 */
2826void dvmResumeAllThreads(SuspendCause why)
2827{
2828 Thread* self = dvmThreadSelf();
2829 Thread* thread;
2830 int cc;
2831
2832 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2833 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2834
2835 /*
2836 * Decrement the suspend counts for all threads. No need for atomic
2837 * writes, since nobody should be moving until we decrement the count.
2838 * We do need to hold the thread list because of JNI attaches.
2839 */
2840 dvmLockThreadList(self);
2841 lockThreadSuspendCount();
2842 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2843 if (thread == self)
2844 continue;
2845
2846 /* debugger events don't suspend JDWP thread */
2847 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2848 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002849 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002850 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002851 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002852
2853 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002854 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002855 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2856 thread->dbgSuspendCount--;
2857 } else {
2858 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2859 thread->threadId);
2860 }
2861 }
2862 unlockThreadSuspendCount();
2863 dvmUnlockThreadList();
2864
2865 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002866 * In some ways it makes sense to continue to hold the thread-suspend
2867 * lock while we issue the wakeup broadcast. It allows us to complete
2868 * one operation before moving on to the next, which simplifies the
2869 * thread activity debug traces.
2870 *
2871 * This approach caused us some difficulty under Linux, because the
2872 * condition variable broadcast not only made the threads runnable,
2873 * but actually caused them to execute, and it was a while before
2874 * the thread performing the wakeup had an opportunity to release the
2875 * thread-suspend lock.
2876 *
2877 * This is a problem because, when a thread tries to acquire that
2878 * lock, it times out after 3 seconds. If at some point the thread
2879 * is told to suspend, the clock resets; but since the VM is still
2880 * theoretically mid-resume, there's no suspend pending. If, for
2881 * example, the GC was waking threads up while the SIGQUIT handler
2882 * was trying to acquire the lock, we would occasionally time out on
2883 * a busy system and SignalCatcher would abort.
2884 *
2885 * We now perform the unlock before the wakeup broadcast. The next
2886 * suspend can't actually start until the broadcast completes and
2887 * returns, because we're holding the thread-suspend-count lock, but the
2888 * suspending thread is now able to make progress and we avoid the abort.
2889 *
2890 * (Technically there is a narrow window between when we release
2891 * the thread-suspend lock and grab the thread-suspend-count lock.
2892 * This could cause us to send a broadcast to threads with nonzero
2893 * suspend counts, but this is expected and they'll all just fall
2894 * right back to sleep. It's probably safe to grab the suspend-count
2895 * lock before releasing thread-suspend, since we're still following
2896 * the correct order of acquisition, but it feels weird.)
2897 */
2898
2899 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2900 unlockThreadSuspend();
2901
2902 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002903 * Broadcast a notification to all suspended threads, some or all of
2904 * which may choose to wake up. No need to wait for them.
2905 */
2906 lockThreadSuspendCount();
2907 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2908 assert(cc == 0);
2909 unlockThreadSuspendCount();
2910
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002911 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2912}
2913
2914/*
2915 * Undo any debugger suspensions. This is called when the debugger
2916 * disconnects.
2917 */
2918void dvmUndoDebuggerSuspensions(void)
2919{
2920 Thread* self = dvmThreadSelf();
2921 Thread* thread;
2922 int cc;
2923
2924 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2925 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2926
2927 /*
2928 * Decrement the suspend counts for all threads. No need for atomic
2929 * writes, since nobody should be moving until we decrement the count.
2930 * We do need to hold the thread list because of JNI attaches.
2931 */
2932 dvmLockThreadList(self);
2933 lockThreadSuspendCount();
2934 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2935 if (thread == self)
2936 continue;
2937
2938 /* debugger events don't suspend JDWP thread */
2939 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2940 assert(thread->dbgSuspendCount == 0);
2941 continue;
2942 }
2943
2944 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002945 dvmAddToThreadSuspendCount(&thread->suspendCount,
2946 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002947 thread->dbgSuspendCount = 0;
2948 }
2949 unlockThreadSuspendCount();
2950 dvmUnlockThreadList();
2951
2952 /*
2953 * Broadcast a notification to all suspended threads, some or all of
2954 * which may choose to wake up. No need to wait for them.
2955 */
2956 lockThreadSuspendCount();
2957 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2958 assert(cc == 0);
2959 unlockThreadSuspendCount();
2960
2961 unlockThreadSuspend();
2962
2963 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2964}
2965
2966/*
2967 * Determine if a thread is suspended.
2968 *
2969 * As with all operations on foreign threads, the caller should hold
2970 * the thread list lock before calling.
2971 */
2972bool dvmIsSuspended(Thread* thread)
2973{
2974 /*
2975 * The thread could be:
2976 * (1) Running happily. status is RUNNING, isSuspended is false,
2977 * suspendCount is zero. Return "false".
2978 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2979 * suspendCount is nonzero. Return "false".
2980 * (3) Suspended. suspendCount is nonzero, and either (status is
2981 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2982 * Return "true".
2983 * (4) Waking up. suspendCount is zero, status is RUNNING and
2984 * isSuspended is true. Return "false" (since it could change
2985 * out from under us, unless we hold suspendCountLock).
2986 */
2987
2988 return (thread->suspendCount != 0 &&
2989 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2990 (thread->status != THREAD_RUNNING)));
2991}
2992
2993/*
2994 * Wait until another thread self-suspends. This is specifically for
2995 * synchronization between the JDWP thread and a thread that has decided
2996 * to suspend itself after sending an event to the debugger.
2997 *
2998 * Threads that encounter "suspend all" events work as well -- the thread
2999 * in question suspends everybody else and then itself.
3000 *
3001 * We can't hold a thread lock here or in the caller, because we could
3002 * get here just before the to-be-waited-for-thread issues a "suspend all".
3003 * There's an opportunity for badness if the thread we're waiting for exits
3004 * and gets cleaned up, but since the thread in question is processing a
3005 * debugger event, that's not really a possibility. (To avoid deadlock,
3006 * it's important that we not be in THREAD_RUNNING while we wait.)
3007 */
3008void dvmWaitForSuspend(Thread* thread)
3009{
3010 Thread* self = dvmThreadSelf();
3011
3012 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3013 self->threadId, thread->threadId);
3014
3015 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3016 assert(thread != self);
3017 assert(self->status != THREAD_RUNNING);
3018
3019 waitForThreadSuspend(self, thread);
3020
3021 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3022 self->threadId, thread->threadId);
3023}
3024
3025/*
3026 * Check to see if we need to suspend ourselves. If so, go to sleep on
3027 * a condition variable.
3028 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003029 * If "newStatus" is not THREAD_UNDEFINED, we change to that state before
3030 * we release the thread suspend count lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003031 *
3032 * Returns "true" if we suspended ourselves.
3033 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003034static bool checkSuspendAndChangeStatus(Thread* self, ThreadStatus newStatus)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003035{
3036 bool didSuspend;
3037
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003038 assert(self != NULL);
3039 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003040
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003041 /* fast path: if count is zero and no state change, bail immediately */
3042 if (self->suspendCount == 0 && newStatus == THREAD_UNDEFINED) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003043 return false;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003044 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003045
3046 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3047
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003048 didSuspend = (self->suspendCount != 0);
3049 self->isSuspended = true;
3050 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
3051 while (self->suspendCount != 0) {
3052 /* wait for wakeup signal; releases lock */
3053 int cc;
3054 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
3055 &gDvm.threadSuspendCountLock);
3056 assert(cc == 0);
3057 }
3058 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
3059 self->isSuspended = false;
3060 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3061 self->threadId, self->status);
3062
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003063 /*
3064 * The status change needs to happen while the suspend count lock is
3065 * held. Otherwise we could switch to RUNNING after another thread
3066 * increases our suspend count, which isn't a "bad" state for us
3067 * (we'll suspend on the next check) but could be a problem for the
3068 * other thread (which thinks we're safely in VMWAIT or NATIVE with
3069 * a nonzero suspend count, and proceeds to initate GC).
3070 */
3071 if (newStatus != THREAD_UNDEFINED)
3072 self->status = newStatus;
3073
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003074 unlockThreadSuspendCount();
3075
3076 return didSuspend;
3077}
3078
3079/*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003080 * One-argument wrapper for checkSuspendAndChangeStatus().
3081 */
3082bool dvmCheckSuspendPending(Thread* self)
3083{
3084 return checkSuspendAndChangeStatus(self, THREAD_UNDEFINED);
3085}
3086
3087/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003088 * Update our status.
3089 *
3090 * The "self" argument, which may be NULL, is accepted as an optimization.
3091 *
3092 * Returns the old status.
3093 */
3094ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3095{
3096 ThreadStatus oldStatus;
3097
3098 if (self == NULL)
3099 self = dvmThreadSelf();
3100
3101 LOGVV("threadid=%d: (status %d -> %d)\n",
3102 self->threadId, self->status, newStatus);
3103
3104 oldStatus = self->status;
3105
3106 if (newStatus == THREAD_RUNNING) {
3107 /*
3108 * Change our status to THREAD_RUNNING. The transition requires
3109 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003110 * us to be "asleep" in all other states, and another thread could
3111 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003112 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003113 * The check for suspension requires holding the thread suspend
3114 * count lock, which the suspend-all code also grabs. We want to
3115 * check our suspension status and change to RUNNING atomically
3116 * to avoid a situation where suspend-all thinks we're safe
3117 * (e.g. VMWAIT or NATIVE with suspendCount=1) but we've actually
3118 * switched to RUNNING and are executing code.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003119 */
3120 assert(self->status != THREAD_RUNNING);
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003121 checkSuspendAndChangeStatus(self, newStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003122 } else {
3123 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003124 * Not changing to THREAD_RUNNING. No additional work required.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003125 */
3126 self->status = newStatus;
3127 }
3128
3129 return oldStatus;
3130}
3131
3132/*
3133 * Get a statically defined thread group from a field in the ThreadGroup
3134 * Class object. Expected arguments are "mMain" and "mSystem".
3135 */
3136static Object* getStaticThreadGroup(const char* fieldName)
3137{
3138 StaticField* groupField;
3139 Object* groupObj;
3140
3141 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3142 fieldName, "Ljava/lang/ThreadGroup;");
3143 if (groupField == NULL) {
3144 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3145 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3146 return NULL;
3147 }
3148 groupObj = dvmGetStaticFieldObject(groupField);
3149 if (groupObj == NULL) {
3150 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3151 dvmThrowException("Ljava/lang/InternalError;", NULL);
3152 return NULL;
3153 }
3154
3155 return groupObj;
3156}
3157Object* dvmGetSystemThreadGroup(void)
3158{
3159 return getStaticThreadGroup("mSystem");
3160}
3161Object* dvmGetMainThreadGroup(void)
3162{
3163 return getStaticThreadGroup("mMain");
3164}
3165
3166/*
3167 * Given a VMThread object, return the associated Thread*.
3168 *
3169 * NOTE: if the thread detaches, the struct Thread will disappear, and
3170 * we will be touching invalid data. For safety, lock the thread list
3171 * before calling this.
3172 */
3173Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3174{
3175 int vmData;
3176
3177 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003178
3179 if (false) {
3180 Thread* thread = gDvm.threadList;
3181 while (thread != NULL) {
3182 if ((Thread*)vmData == thread)
3183 break;
3184
3185 thread = thread->next;
3186 }
3187
3188 if (thread == NULL) {
3189 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3190 vmThreadObj, (Thread*)vmData);
3191 vmData = 0;
3192 }
3193 }
3194
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003195 return (Thread*) vmData;
3196}
3197
Andy McFadden2b94b302010-03-09 16:38:36 -08003198/*
3199 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003200 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003201 *
3202 * Returns NULL if the thread was not found.
3203 */
3204Thread* dvmGetThreadByHandle(pthread_t handle)
3205{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003206 Thread* thread;
3207 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003208 if (thread->handle == handle)
3209 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003210 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003211 return thread;
3212}
Andy McFadden2b94b302010-03-09 16:38:36 -08003213
Andy McFadden0a24ef92010-03-12 13:39:59 -08003214/*
3215 * Given a threadId, return the associated Thread*.
3216 * Caller must hold the thread list lock.
3217 *
3218 * Returns NULL if the thread was not found.
3219 */
3220Thread* dvmGetThreadByThreadId(u4 threadId)
3221{
3222 Thread* thread;
3223 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3224 if (thread->threadId == threadId)
3225 break;
3226 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003227 return thread;
3228}
3229
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003230
3231/*
3232 * Conversion map for "nice" values.
3233 *
3234 * We use Android thread priority constants to be consistent with the rest
3235 * of the system. In some cases adjacent entries may overlap.
3236 */
3237static const int kNiceValues[10] = {
3238 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3239 ANDROID_PRIORITY_BACKGROUND + 6,
3240 ANDROID_PRIORITY_BACKGROUND + 3,
3241 ANDROID_PRIORITY_BACKGROUND,
3242 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3243 ANDROID_PRIORITY_NORMAL - 2,
3244 ANDROID_PRIORITY_NORMAL - 4,
3245 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3246 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3247 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3248};
3249
3250/*
3251 * Change the priority of a system thread to match that of the Thread object.
3252 *
3253 * We map a priority value from 1-10 to Linux "nice" values, where lower
3254 * numbers indicate higher priority.
3255 */
3256void dvmChangeThreadPriority(Thread* thread, int newPriority)
3257{
3258 pid_t pid = thread->systemTid;
3259 int newNice;
3260
3261 if (newPriority < 1 || newPriority > 10) {
3262 LOGW("bad priority %d\n", newPriority);
3263 newPriority = 5;
3264 }
3265 newNice = kNiceValues[newPriority-1];
3266
Andy McFaddend62c0b52009-08-04 15:02:12 -07003267 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003268 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003269 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003270 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003271 }
3272
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003273 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3274 char* str = dvmGetThreadName(thread);
3275 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3276 pid, str, newPriority, newNice, strerror(errno));
3277 free(str);
3278 } else {
3279 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3280 pid, newPriority, newNice);
3281 }
3282}
3283
3284/*
3285 * Get the thread priority for the current thread by querying the system.
3286 * This is useful when attaching a thread through JNI.
3287 *
3288 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3289 */
3290static int getThreadPriorityFromSystem(void)
3291{
3292 int i, sysprio, jprio;
3293
3294 errno = 0;
3295 sysprio = getpriority(PRIO_PROCESS, 0);
3296 if (sysprio == -1 && errno != 0) {
3297 LOGW("getpriority() failed: %s\n", strerror(errno));
3298 return THREAD_NORM_PRIORITY;
3299 }
3300
3301 jprio = THREAD_MIN_PRIORITY;
3302 for (i = 0; i < NELEM(kNiceValues); i++) {
3303 if (sysprio >= kNiceValues[i])
3304 break;
3305 jprio++;
3306 }
3307 if (jprio > THREAD_MAX_PRIORITY)
3308 jprio = THREAD_MAX_PRIORITY;
3309
3310 return jprio;
3311}
3312
3313
3314/*
3315 * Return true if the thread is on gDvm.threadList.
3316 * Caller should not hold gDvm.threadListLock.
3317 */
3318bool dvmIsOnThreadList(const Thread* thread)
3319{
3320 bool ret = false;
3321
3322 dvmLockThreadList(NULL);
3323 if (thread == gDvm.threadList) {
3324 ret = true;
3325 } else {
3326 ret = thread->prev != NULL || thread->next != NULL;
3327 }
3328 dvmUnlockThreadList();
3329
3330 return ret;
3331}
3332
3333/*
3334 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3335 * output target.
3336 */
3337void dvmDumpThread(Thread* thread, bool isRunning)
3338{
3339 DebugOutputTarget target;
3340
3341 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3342 dvmDumpThreadEx(&target, thread, isRunning);
3343}
3344
3345/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003346 * Try to get the scheduler group.
3347 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003348 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003349 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003350 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003351 *
3352 * We return the part after the "/", which will be an empty string for
3353 * the default cgroup. If the string is longer than "bufLen", the string
3354 * will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003355 *
3356 * TODO: this is cloned from a static function in libcutils; expose that?
Andy McFaddend62c0b52009-08-04 15:02:12 -07003357 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003358static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003359{
3360#ifdef HAVE_ANDROID_OS
3361 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003362 char lineBuf[256];
3363 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003364
Andy McFadden7f64ede2010-03-03 15:37:10 -08003365 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
3366 if (!(fp = fopen(pathBuf, "r"))) {
3367 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003368 }
3369
Andy McFadden7f64ede2010-03-03 15:37:10 -08003370 while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
3371 char *next = lineBuf;
3372 char *subsys;
3373 char *grp;
3374 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003375
Andy McFadden7f64ede2010-03-03 15:37:10 -08003376 /* Junk the first field */
3377 if (!strsep(&next, ":")) {
3378 goto out_bad_data;
3379 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003380
Andy McFadden7f64ede2010-03-03 15:37:10 -08003381 if (!(subsys = strsep(&next, ":"))) {
3382 goto out_bad_data;
3383 }
3384
3385 if (strcmp(subsys, "cpu")) {
3386 /* Not the subsys we're looking for */
3387 continue;
3388 }
3389
3390 if (!(grp = strsep(&next, ":"))) {
3391 goto out_bad_data;
3392 }
3393 grp++; /* Drop the leading '/' */
3394 len = strlen(grp);
3395 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3396
3397 if (bufLen <= len) {
3398 len = bufLen - 1;
3399 }
3400 strncpy(buf, grp, len);
3401 buf[len] = '\0';
3402 fclose(fp);
3403 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003404 }
3405
Andy McFadden7f64ede2010-03-03 15:37:10 -08003406 LOGE("Failed to find cpu subsys");
3407 fclose(fp);
3408 return -1;
3409 out_bad_data:
3410 LOGE("Bad cgroup data {%s}", lineBuf);
3411 fclose(fp);
3412 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003413#else
Andy McFadden7f64ede2010-03-03 15:37:10 -08003414 errno = ENOSYS;
3415 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003416#endif
3417}
3418
3419/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003420 * Convert ThreadStatus to a string.
3421 */
3422const char* dvmGetThreadStatusStr(ThreadStatus status)
3423{
3424 switch (status) {
3425 case THREAD_ZOMBIE: return "ZOMBIE";
3426 case THREAD_RUNNING: return "RUNNABLE";
3427 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3428 case THREAD_MONITOR: return "MONITOR";
3429 case THREAD_WAIT: return "WAIT";
3430 case THREAD_INITIALIZING: return "INITIALIZING";
3431 case THREAD_STARTING: return "STARTING";
3432 case THREAD_NATIVE: return "NATIVE";
3433 case THREAD_VMWAIT: return "VMWAIT";
3434 default: return "UNKNOWN";
3435 }
3436}
3437
3438/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003439 * Print information about the specified thread.
3440 *
3441 * Works best when the thread in question is "self" or has been suspended.
3442 * When dumping a separate thread that's still running, set "isRunning" to
3443 * use a more cautious thread dump function.
3444 */
3445void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3446 bool isRunning)
3447{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003448 Object* threadObj;
3449 Object* groupObj;
3450 StringObject* nameStr;
3451 char* threadName = NULL;
3452 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003453 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003454 bool isDaemon;
3455 int priority; // java.lang.Thread priority
3456 int policy; // pthread policy
3457 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003458 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
3459 int schedstatFd;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003460
Andy McFaddene3346d82010-06-02 15:37:21 -07003461 /*
3462 * Get the java.lang.Thread object. This function gets called from
3463 * some weird debug contexts, so it's possible that there's a GC in
3464 * progress on some other thread. To decrease the chances of the
3465 * thread object being moved out from under us, we add the reference
3466 * to the tracked allocation list, which pins it in place.
3467 *
3468 * If threadObj is NULL, the thread is still in the process of being
3469 * attached to the VM, and there's really nothing interesting to
3470 * say about it yet.
3471 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003472 threadObj = thread->threadObj;
3473 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003474 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003475 return;
3476 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003477 dvmAddTrackedAlloc(threadObj, NULL);
3478
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003479 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3480 gDvm.offJavaLangThread_name);
3481 threadName = dvmCreateCstrFromString(nameStr);
3482
3483 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3484 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3485
3486 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3487 LOGW("Warning: pthread_getschedparam failed\n");
3488 policy = -1;
3489 sp.sched_priority = -1;
3490 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003491 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
3492 sizeof(schedulerGroupBuf)) != 0)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003493 {
3494 strcpy(schedulerGroupBuf, "unknown");
3495 } else if (schedulerGroupBuf[0] == '\0') {
3496 strcpy(schedulerGroupBuf, "default");
3497 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003498
3499 /* a null value for group is not expected, but deal with it anyway */
3500 groupObj = (Object*) dvmGetFieldObject(threadObj,
3501 gDvm.offJavaLangThread_group);
3502 if (groupObj != NULL) {
3503 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3504 "name", "Ljava/lang/String;");
3505 if (offset < 0) {
3506 LOGW("Unable to find 'name' field in ThreadGroup\n");
3507 } else {
3508 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3509 groupName = dvmCreateCstrFromString(nameStr);
3510 }
3511 }
3512 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003513 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003514
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003515 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003516 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003517 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003518 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3519#if defined(WITH_JIT)
3520 thread->inJitCodeCache ? " JIT" : ""
3521#else
3522 ""
3523#endif
3524 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003525 dvmPrintDebugMessage(target,
Andy McFadden2aa43612009-06-17 16:29:30 -07003526 " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003527 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden2aa43612009-06-17 16:29:30 -07003528 thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003529 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003530 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003531 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003532 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003533
Christopher Tate962f8962010-06-02 16:17:46 -07003534 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/%d/task/%d/schedstat",
3535 getpid(), thread->systemTid);
3536 schedstatFd = open(schedstatBuf, O_RDONLY);
3537 if (schedstatFd >= 0) {
3538 int bytes;
3539 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3540 close(schedstatFd);
3541 if (bytes > 1) {
3542 schedstatBuf[bytes-1] = 0; // trailing newline
3543 dvmPrintDebugMessage(target, " | schedstat=( %s )\n", schedstatBuf);
3544 }
3545 }
3546
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003547#ifdef WITH_MONITOR_TRACKING
3548 if (!isRunning) {
3549 LockedObjectData* lod = thread->pLockedObjects;
3550 if (lod != NULL)
3551 dvmPrintDebugMessage(target, " | monitors held:\n");
3552 else
3553 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3554 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003555 Object* obj = lod->obj;
3556 if (obj->clazz == gDvm.classJavaLangClass) {
3557 ClassObject* clazz = (ClassObject*) obj;
3558 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3559 obj, lod->recursionCount, obj->clazz->descriptor,
3560 clazz->descriptor);
3561 } else {
3562 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3563 obj, lod->recursionCount, obj->clazz->descriptor);
3564 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003565 lod = lod->next;
3566 }
3567 }
3568#endif
3569
3570 if (isRunning)
3571 dvmDumpRunningThreadStack(target, thread);
3572 else
3573 dvmDumpThreadStack(target, thread);
3574
Andy McFaddene3346d82010-06-02 15:37:21 -07003575 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003576 free(threadName);
3577 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003578}
3579
3580/*
3581 * Get the name of a thread.
3582 *
3583 * For correctness, the caller should hold the thread list lock to ensure
3584 * that the thread doesn't go away mid-call.
3585 *
3586 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3587 */
3588char* dvmGetThreadName(Thread* thread)
3589{
3590 StringObject* nameObj;
3591
3592 if (thread->threadObj == NULL) {
3593 LOGW("threadObj is NULL, name not available\n");
3594 return strdup("-unknown-");
3595 }
3596
3597 nameObj = (StringObject*)
3598 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3599 return dvmCreateCstrFromString(nameObj);
3600}
3601
3602/*
3603 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3604 * an output target.
3605 */
3606void dvmDumpAllThreads(bool grabLock)
3607{
3608 DebugOutputTarget target;
3609
3610 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3611 dvmDumpAllThreadsEx(&target, grabLock);
3612}
3613
3614/*
3615 * Print information about all known threads. Assumes they have been
3616 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3617 *
3618 * If "grabLock" is true, we grab the thread lock list. This is important
3619 * to do unless the caller already holds the lock.
3620 */
3621void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3622{
3623 Thread* thread;
3624
3625 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3626
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003627#ifdef HAVE_ANDROID_OS
3628 dvmPrintDebugMessage(target,
3629 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3630 gDvm.threadListLock.value,
3631 gDvm._threadSuspendLock.value,
3632 gDvm.threadSuspendCountLock.value,
3633 gDvm.gcHeapLock.value,
3634 gDvm.heapWorkerLock.value,
3635 gDvm.heapWorkerListLock.value);
3636#endif
3637
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003638 if (grabLock)
3639 dvmLockThreadList(dvmThreadSelf());
3640
3641 thread = gDvm.threadList;
3642 while (thread != NULL) {
3643 dvmDumpThreadEx(target, thread, false);
3644
3645 /* verify link */
3646 assert(thread->next == NULL || thread->next->prev == thread);
3647
3648 thread = thread->next;
3649 }
3650
3651 if (grabLock)
3652 dvmUnlockThreadList();
3653}
3654
Andy McFadden384ef6b2010-03-15 17:24:55 -07003655/*
3656 * Nuke the target thread from orbit.
3657 *
3658 * The idea is to send a "crash" signal to the target thread so that
3659 * debuggerd will take notice and dump an appropriate stack trace.
3660 * Because of the way debuggerd works, we have to throw the same signal
3661 * at it twice.
3662 *
3663 * This does not necessarily cause the entire process to stop, but once a
3664 * thread has been nuked the rest of the system is likely to be unstable.
3665 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003666 * performed, but it's advisable (and expected) to call dvmAbort soon.
3667 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003668 */
3669void dvmNukeThread(Thread* thread)
3670{
Andy McFaddena388a162010-03-18 16:27:14 -07003671 /* suppress the heapworker watchdog to assist anyone using a debugger */
3672 gDvm.nativeDebuggerActive = true;
3673
Andy McFadden384ef6b2010-03-15 17:24:55 -07003674 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003675 * Send the signals, separated by a brief interval to allow debuggerd
3676 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3677 * can be used instead of SIGSEGV to avoid making it look like the
3678 * code actually crashed at the current point of execution.
3679 *
3680 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3681 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3682 * you don't get the second stack trace; possibly something in the
3683 * kernel decides that a signal has already been sent and it's time
3684 * to just kill the process. The position in the current thread is
3685 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003686 *
Andy McFaddena388a162010-03-18 16:27:14 -07003687 * The target thread can continue to execute between the two signals.
3688 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003689 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003690 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3691 " cause debuggerd dump\n",
3692 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
3693 pthread_kill(thread->handle, SIGSTKFLT);
Andy McFaddena388a162010-03-18 16:27:14 -07003694 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddend4e09522010-03-23 12:34:43 -07003695 pthread_kill(thread->handle, SIGSTKFLT);
Andy McFadden7122d862010-03-19 15:18:57 -07003696 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003697 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003698
3699 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3700 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003701 LOGD("Continuing\n");
3702}
3703
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003704#ifdef WITH_MONITOR_TRACKING
3705/*
3706 * Count up the #of locked objects in the current thread.
3707 */
3708static int getThreadObjectCount(const Thread* self)
3709{
3710 LockedObjectData* lod;
3711 int count = 0;
3712
3713 lod = self->pLockedObjects;
3714 while (lod != NULL) {
3715 count++;
3716 lod = lod->next;
3717 }
3718 return count;
3719}
3720
3721/*
3722 * Add the object to the thread's locked object list if it doesn't already
3723 * exist. The most recently added object is the most likely to be released
3724 * next, so we insert at the head of the list.
3725 *
3726 * If it already exists, we increase the recursive lock count.
3727 *
3728 * The object's lock may be thin or fat.
3729 */
3730void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3731{
3732 LockedObjectData* newLod;
3733 LockedObjectData* lod;
3734 int* trace;
3735 int depth;
3736
3737 lod = self->pLockedObjects;
3738 while (lod != NULL) {
3739 if (lod->obj == obj) {
3740 lod->recursionCount++;
3741 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3742 return;
3743 }
3744 lod = lod->next;
3745 }
3746
3747 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3748 if (newLod == NULL) {
3749 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3750 return;
3751 }
3752 newLod->obj = obj;
3753 newLod->recursionCount = 0;
3754
3755 if (withTrace) {
3756 trace = dvmFillInStackTraceRaw(self, &depth);
3757 newLod->rawStackTrace = trace;
3758 newLod->stackDepth = depth;
3759 }
3760
3761 newLod->next = self->pLockedObjects;
3762 self->pLockedObjects = newLod;
3763
3764 LOGV("+++ threadid=%d: added %p, now %d\n",
3765 self->threadId, newLod, getThreadObjectCount(self));
3766}
3767
3768/*
3769 * Remove the object from the thread's locked object list. If the entry
3770 * has a nonzero recursion count, we just decrement the count instead.
3771 */
3772void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3773{
3774 LockedObjectData* lod;
3775 LockedObjectData* prevLod;
3776
3777 lod = self->pLockedObjects;
3778 prevLod = NULL;
3779 while (lod != NULL) {
3780 if (lod->obj == obj) {
3781 if (lod->recursionCount > 0) {
3782 lod->recursionCount--;
3783 LOGV("+++ -recursive lock %p -> %d\n",
3784 obj, lod->recursionCount);
3785 return;
3786 } else {
3787 break;
3788 }
3789 }
3790 prevLod = lod;
3791 lod = lod->next;
3792 }
3793
3794 if (lod == NULL) {
3795 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3796 return;
3797 }
3798 if (prevLod == NULL) {
3799 /* first item in list */
3800 assert(self->pLockedObjects == lod);
3801 self->pLockedObjects = lod->next;
3802 } else {
3803 /* middle/end of list */
3804 prevLod->next = lod->next;
3805 }
3806
3807 LOGV("+++ threadid=%d: removed %p, now %d\n",
3808 self->threadId, lod, getThreadObjectCount(self));
3809 free(lod->rawStackTrace);
3810 free(lod);
3811}
3812
3813/*
3814 * If the specified object is already in the thread's locked object list,
3815 * return the LockedObjectData struct. Otherwise return NULL.
3816 */
3817LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3818{
3819 LockedObjectData* lod;
3820
3821 lod = self->pLockedObjects;
3822 while (lod != NULL) {
3823 if (lod->obj == obj)
3824 return lod;
3825 lod = lod->next;
3826 }
3827 return NULL;
3828}
3829#endif /*WITH_MONITOR_TRACKING*/
3830
3831
3832/*
3833 * GC helper functions
3834 */
3835
The Android Open Source Project99409882009-03-18 22:20:24 -07003836/*
3837 * Add the contents of the registers from the interpreted call stack.
3838 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003839static void gcScanInterpStackReferences(Thread *thread)
3840{
3841 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003842#if WITH_EXTRA_GC_CHECKS > 1
3843 bool first = true;
3844#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003845
3846 framePtr = (const u4 *)thread->curFrame;
3847 while (framePtr != NULL) {
3848 const StackSaveArea *saveArea;
3849 const Method *method;
3850
3851 saveArea = SAVEAREA_FROM_FP(framePtr);
3852 method = saveArea->method;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003853 if (method != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003854#ifdef COUNT_PRECISE_METHODS
3855 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003856 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3857 LOGI("PGC: added %s.%s %p\n",
3858 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003859#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003860#if WITH_EXTRA_GC_CHECKS > 1
3861 /*
3862 * May also want to enable the memset() in the "invokeMethod"
3863 * goto target in the portable interpreter. That sets the stack
3864 * to a pattern that makes referring to uninitialized data
3865 * very obvious.
3866 */
3867
3868 if (first) {
3869 /*
3870 * First frame, isn't native, check the "alternate" saved PC
3871 * as a sanity check.
3872 *
3873 * It seems like we could check the second frame if the first
3874 * is native, since the PCs should be the same. It turns out
3875 * this doesn't always work. The problem is that we could
3876 * have calls in the sequence:
3877 * interp method #2
3878 * native method
3879 * interp method #1
3880 *
3881 * and then GC while in the native method after returning
3882 * from interp method #2. The currentPc on the stack is
3883 * for interp method #1, but thread->currentPc2 is still
3884 * set for the last thing interp method #2 did.
3885 *
3886 * This can also happen in normal execution:
3887 * - sget-object on not-yet-loaded class
3888 * - class init updates currentPc2
3889 * - static field init is handled by parsing annotations;
3890 * static String init requires creation of a String object,
3891 * which can cause a GC
3892 *
3893 * Essentially, any pattern that involves executing
3894 * interpreted code and then causes an allocation without
3895 * executing instructions in the original method will hit
3896 * this. These are rare enough that the test still has
3897 * some value.
3898 */
3899 if (saveArea->xtra.currentPc != thread->currentPc2) {
3900 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3901 saveArea->xtra.currentPc, thread->currentPc2,
3902 method->clazz->descriptor, method->name, method->insns);
3903 if (saveArea->xtra.currentPc != NULL)
3904 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3905 if (thread->currentPc2 != NULL)
3906 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3907 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003908 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003909 } else {
3910 /*
3911 * It's unusual, but not impossible, for a non-first frame
3912 * to be at something other than a method invocation. For
3913 * example, if we do a new-instance on a nonexistent class,
3914 * we'll have a lot of class loader activity on the stack
3915 * above the frame with the "new" operation. Could also
3916 * happen while we initialize a Throwable when an instruction
3917 * fails.
3918 *
3919 * So there's not much we can do here to verify the PC,
3920 * except to verify that it's a GC point.
3921 */
3922 }
3923 assert(saveArea->xtra.currentPc != NULL);
3924#endif
3925
3926 const RegisterMap* pMap;
3927 const u1* regVector;
3928 int i;
3929
Andy McFaddencf8b55c2009-04-13 15:26:03 -07003930 Method* nonConstMethod = (Method*) method; // quiet gcc
3931 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07003932 if (pMap != NULL) {
3933 /* found map, get registers for this address */
3934 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07003935 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07003936 if (regVector == NULL) {
3937 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
3938 method->clazz->descriptor, method->name, addr);
3939 } else {
3940 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
3941 method->clazz->descriptor, method->name, addr,
3942 thread->threadId);
3943 }
3944 } else {
3945 /*
3946 * No map found. If precise GC is disabled this is
3947 * expected -- we don't create pointers to the map data even
3948 * if it's present -- but if it's enabled it means we're
3949 * unexpectedly falling back on a conservative scan, so it's
3950 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07003951 */
3952 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07003953 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07003954 method->clazz->descriptor, method->name);
3955 }
3956 regVector = NULL;
3957 }
3958
3959 if (regVector == NULL) {
3960 /* conservative scan */
3961 for (i = method->registersSize - 1; i >= 0; i--) {
3962 u4 rval = *framePtr++;
3963 if (rval != 0 && (rval & 0x3) == 0) {
3964 dvmMarkIfObject((Object *)rval);
3965 }
3966 }
3967 } else {
3968 /*
3969 * Precise scan. v0 is at the lowest address on the
3970 * interpreted stack, and is the first bit in the register
3971 * vector, so we can walk through the register map and
3972 * memory in the same direction.
3973 *
3974 * A '1' bit indicates a live reference.
3975 */
3976 u2 bits = 1 << 1;
3977 for (i = method->registersSize - 1; i >= 0; i--) {
3978 u4 rval = *framePtr++;
3979
3980 bits >>= 1;
3981 if (bits == 1) {
3982 /* set bit 9 so we can tell when we're empty */
3983 bits = *regVector++ | 0x0100;
3984 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
3985 }
3986
3987 if (rval != 0 && (bits & 0x01) != 0) {
3988 /*
3989 * Non-null, register marked as live reference. This
3990 * should always be a valid object.
3991 */
3992#if WITH_EXTRA_GC_CHECKS > 0
3993 if ((rval & 0x3) != 0 ||
3994 !dvmIsValidObject((Object*) rval))
3995 {
3996 /* this is very bad */
3997 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
3998 method->registersSize-1 - i, rval);
3999 } else
4000#endif
4001 {
4002 dvmMarkObjectNonNull((Object *)rval);
4003 }
4004 } else {
4005 /*
4006 * Null or non-reference, do nothing at all.
4007 */
4008#if WITH_EXTRA_GC_CHECKS > 1
4009 if (dvmIsValidObject((Object*) rval)) {
4010 /* this is normal, but we feel chatty */
4011 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
4012 method->registersSize-1 - i, rval);
4013 }
4014#endif
4015 }
4016 }
4017 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004018 }
4019 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004020
The Android Open Source Project99409882009-03-18 22:20:24 -07004021#if WITH_EXTRA_GC_CHECKS > 1
4022 first = false;
4023#endif
4024
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004025 /* Don't fall into an infinite loop if things get corrupted.
4026 */
4027 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
4028 saveArea->prevFrame == NULL);
4029 framePtr = saveArea->prevFrame;
4030 }
4031}
4032
4033static void gcScanReferenceTable(ReferenceTable *refTable)
4034{
4035 Object **op;
4036
4037 //TODO: these asserts are overkill; turn them off when things stablize.
4038 assert(refTable != NULL);
4039 assert(refTable->table != NULL);
4040 assert(refTable->nextEntry != NULL);
4041 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
4042 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
4043
4044 op = refTable->table;
4045 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
4046 dvmMarkObjectNonNull(*(op++));
4047 }
4048}
4049
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004050#ifdef USE_INDIRECT_REF
Andy McFaddend5ab7262009-08-25 07:19:34 -07004051static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
4052{
4053 Object** op = pRefTable->table;
4054 int numEntries = dvmIndirectRefTableEntries(pRefTable);
4055 int i;
4056
4057 for (i = 0; i < numEntries; i++) {
4058 Object* obj = *op;
4059 if (obj != NULL)
4060 dvmMarkObjectNonNull(obj);
4061 op++;
4062 }
4063}
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004064#endif
Andy McFaddend5ab7262009-08-25 07:19:34 -07004065
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004066/*
4067 * Scan a Thread and mark any objects it references.
4068 */
4069static void gcScanThread(Thread *thread)
4070{
4071 assert(thread != NULL);
4072
4073 /*
4074 * The target thread must be suspended or in a state where it can't do
4075 * any harm (e.g. in Object.wait()). The only exception is the current
4076 * thread, which will still be active and in the "running" state.
4077 *
4078 * (Newly-created threads shouldn't be able to shift themselves to
4079 * RUNNING without a suspend-pending check, so this shouldn't cause
4080 * a false-positive.)
4081 */
Andy McFaddend40223e2009-12-07 15:35:51 -08004082 if (thread->status == THREAD_RUNNING && !thread->isSuspended &&
4083 thread != dvmThreadSelf())
4084 {
4085 Thread* self = dvmThreadSelf();
4086 LOGW("threadid=%d: BUG: GC scanning a running thread (%d)\n",
4087 self->threadId, thread->threadId);
4088 dvmDumpThread(thread, true);
4089 LOGW("Found by:\n");
4090 dvmDumpThread(self, false);
4091
4092 /* continue anyway? */
4093 dvmAbort();
4094 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004095
4096 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
4097
4098 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
4099
4100 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
4101
4102 dvmMarkObject(thread->exception); // usually NULL
4103 gcScanReferenceTable(&thread->internalLocalRefTable);
4104
4105 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
4106
Andy McFaddend5ab7262009-08-25 07:19:34 -07004107#ifdef USE_INDIRECT_REF
4108 gcScanIndirectRefTable(&thread->jniLocalRefTable);
4109#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004110 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07004111#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004112
4113 if (thread->jniMonitorRefTable.table != NULL) {
4114 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
4115
4116 gcScanReferenceTable(&thread->jniMonitorRefTable);
4117 }
4118
4119 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
4120
4121 gcScanInterpStackReferences(thread);
4122
4123 HPROF_CLEAR_GC_SCAN_STATE();
4124}
4125
4126static void gcScanAllThreads()
4127{
4128 Thread *thread;
4129
4130 /* Lock the thread list so we can safely use the
4131 * next/prev pointers.
4132 */
4133 dvmLockThreadList(dvmThreadSelf());
4134
4135 for (thread = gDvm.threadList; thread != NULL;
4136 thread = thread->next)
4137 {
4138 /* We need to scan our own stack, so don't special-case
4139 * the current thread.
4140 */
4141 gcScanThread(thread);
4142 }
4143
4144 dvmUnlockThreadList();
4145}
4146
4147void dvmGcScanRootThreadGroups()
4148{
4149 /* We scan the VM's list of threads instead of going
4150 * through the actual ThreadGroups, but it should be
4151 * equivalent.
4152 *
Jeff Hao97319a82009-08-12 16:57:15 -07004153 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004154 * the root set, which should always be true; it's
4155 * loaded by the built-in class loader, which is part
4156 * of the root set.
4157 */
4158 gcScanAllThreads();
4159}