blob: 7dde87c7416671af046010331a3ab7a508e1ff66 [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 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001354#if defined(HAVE_PTHREAD_SETNAME_NP)
1355 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
Carl Shapiro5617ad32010-07-02 10:50:57 -07001468 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1469 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001470 newThread);
1471 oldStatus = dvmChangeStatus(self, oldStatus);
1472
1473 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001474 /*
1475 * Failure generally indicates that we have exceeded system
1476 * resource limits. VirtualMachineError is probably too severe,
1477 * so use OutOfMemoryError.
1478 */
1479 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1480
1481 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1482
1483 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1484 "thread creation failed");
1485 goto fail;
1486 }
1487
1488 /*
1489 * We need to wait for the thread to start. Otherwise, depending on
1490 * the whims of the OS scheduler, we could return and the code in our
1491 * thread could try to do operations on the new thread before it had
1492 * finished starting.
1493 *
1494 * The new thread will lock the thread list, change its state to
1495 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1496 * on gDvm.threadStartCond (which uses the thread list lock). This
1497 * thread (the parent) will either see that the thread is already ready
1498 * after we grab the thread list lock, or will be awakened from the
1499 * condition variable on the broadcast.
1500 *
1501 * We don't want to stall the rest of the VM while the new thread
1502 * starts, which can happen if the GC wakes up at the wrong moment.
1503 * So, we change our own status to VMWAIT, and self-suspend if
1504 * necessary after we finish adding the new thread.
1505 *
1506 *
1507 * We have to deal with an odd race with the GC/debugger suspension
1508 * mechanism when creating a new thread. The information about whether
1509 * or not a thread should be suspended is contained entirely within
1510 * the Thread struct; this is usually cleaner to deal with than having
1511 * one or more globally-visible suspension flags. The trouble is that
1512 * we could create the thread while the VM is trying to suspend all
1513 * threads. The suspend-count won't be nonzero for the new thread,
1514 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1515 *
1516 * The easiest way to deal with this is to prevent the new thread from
1517 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001518 * following (correct) sequence of events for a "badly timed" GC
1519 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001520 *
1521 * - call pthread_create()
1522 * - lock thread list
1523 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1524 * - sleep on condition var (mutex = thread list lock) until child starts
1525 * + GC triggered by another thread
1526 * + thread list locked; suspend counts updated; thread list unlocked
1527 * + loop waiting for all runnable threads to suspend
1528 * + success, start GC
1529 * o child thread wakes, signals condition var to wake parent
1530 * o child waits for parent ack on condition variable
1531 * - we wake up, locking thread list
1532 * - add child to thread list
1533 * - unlock thread list
1534 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1535 * + GC finishes; all threads in thread list are resumed
1536 * - lock thread list
1537 * - set child to THREAD_VMWAIT, and signal it to start
1538 * - unlock thread list
1539 * o child resumes
1540 * o child changes state to THREAD_RUNNING
1541 *
1542 * The above shows the GC starting up during thread creation, but if
1543 * it starts anywhere after VMThread.create() is called it will
1544 * produce the same series of events.
1545 *
1546 * Once the child is in the thread list, it will be suspended and
1547 * resumed like any other thread. In the above scenario the resume-all
1548 * code will try to resume the new thread, which was never actually
1549 * suspended, and try to decrement the child's thread suspend count to -1.
1550 * We can catch this in the resume-all code.
1551 *
1552 * Bouncing back and forth between threads like this adds a small amount
1553 * of scheduler overhead to thread startup.
1554 *
1555 * One alternative to having the child wait for the parent would be
1556 * to have the child inherit the parents' suspension count. This
1557 * would work for a GC, since we can safely assume that the parent
1558 * thread didn't cause it, but we must only do so if the parent suspension
1559 * was caused by a suspend-all. If the parent was being asked to
1560 * suspend singly by the debugger, the child should not inherit the value.
1561 *
1562 * We could also have a global "new thread suspend count" that gets
1563 * picked up by new threads before changing state to THREAD_RUNNING.
1564 * This would be protected by the thread list lock and set by a
1565 * suspend-all.
1566 */
1567 dvmLockThreadList(self);
1568 assert(self->status == THREAD_RUNNING);
1569 self->status = THREAD_VMWAIT;
1570 while (newThread->status != THREAD_STARTING)
1571 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1572
1573 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1574 newThread->next = gDvm.threadList->next;
1575 if (newThread->next != NULL)
1576 newThread->next->prev = newThread;
1577 newThread->prev = gDvm.threadList;
1578 gDvm.threadList->next = newThread;
1579
1580 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1581 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1582
1583 dvmUnlockThreadList();
1584
1585 /* change status back to RUNNING, self-suspending if necessary */
1586 dvmChangeStatus(self, THREAD_RUNNING);
1587
1588 /*
1589 * Tell the new thread to start.
1590 *
1591 * We must hold the thread list lock before messing with another thread.
1592 * In the general case we would also need to verify that newThread was
1593 * still in the thread list, but in our case the thread has not started
1594 * executing user code and therefore has not had a chance to exit.
1595 *
1596 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1597 * comes with a suspend-pending check.
1598 */
1599 dvmLockThreadList(self);
1600
1601 assert(newThread->status == THREAD_STARTING);
1602 newThread->status = THREAD_VMWAIT;
1603 pthread_cond_broadcast(&gDvm.threadStartCond);
1604
1605 dvmUnlockThreadList();
1606
1607 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1608 return true;
1609
1610fail:
1611 freeThread(newThread);
1612 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1613 return false;
1614}
1615
1616/*
1617 * pthread entry function for threads started from interpreted code.
1618 */
1619static void* interpThreadStart(void* arg)
1620{
1621 Thread* self = (Thread*) arg;
1622
1623 char *threadName = dvmGetThreadName(self);
1624 setThreadName(threadName);
1625 free(threadName);
1626
1627 /*
1628 * Finish initializing the Thread struct.
1629 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001630 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001631 prepareThread(self);
1632
1633 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1634
1635 /*
1636 * Change our status and wake our parent, who will add us to the
1637 * thread list and advance our state to VMWAIT.
1638 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001639 self->status = THREAD_STARTING;
1640 pthread_cond_broadcast(&gDvm.threadStartCond);
1641
1642 /*
1643 * Wait until the parent says we can go. Assuming there wasn't a
1644 * suspend pending, this will happen immediately. When it completes,
1645 * we're full-fledged citizens of the VM.
1646 *
1647 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1648 * because the pthread_cond_wait below needs to reacquire a lock that
1649 * suspend-all is also interested in. If we get unlucky, the parent could
1650 * change us to THREAD_RUNNING, then a GC could start before we get
1651 * signaled, and suspend-all will grab the thread list lock and then
1652 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1653 * trying to get the lock.
1654 */
1655 while (self->status != THREAD_VMWAIT)
1656 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1657
1658 dvmUnlockThreadList();
1659
1660 /*
1661 * Add a JNI context.
1662 */
1663 self->jniEnv = dvmCreateJNIEnv(self);
1664
1665 /*
1666 * Change our state so the GC will wait for us from now on. If a GC is
1667 * in progress this call will suspend us.
1668 */
1669 dvmChangeStatus(self, THREAD_RUNNING);
1670
1671 /*
1672 * Notify the debugger & DDM. The debugger notification may cause
1673 * us to suspend ourselves (and others).
1674 */
1675 if (gDvm.debuggerConnected)
1676 dvmDbgPostThreadStart(self);
1677
1678 /*
1679 * Set the system thread priority according to the Thread object's
1680 * priority level. We don't usually need to do this, because both the
1681 * Thread object and system thread priorities inherit from parents. The
1682 * tricky case is when somebody creates a Thread object, calls
1683 * setPriority(), and then starts the thread. We could manage this with
1684 * a "needs priority update" flag to avoid the redundant call.
1685 */
Andy McFadden4879df92009-08-07 14:49:40 -07001686 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001687 gDvm.offJavaLangThread_priority);
1688 dvmChangeThreadPriority(self, priority);
1689
1690 /*
1691 * Execute the "run" method.
1692 *
1693 * At this point our stack is empty, so somebody who comes looking for
1694 * stack traces right now won't have much to look at. This is normal.
1695 */
1696 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1697 JValue unused;
1698
1699 LOGV("threadid=%d: calling run()\n", self->threadId);
1700 assert(strcmp(run->name, "run") == 0);
1701 dvmCallMethod(self, run, self->threadObj, &unused);
1702 LOGV("threadid=%d: exiting\n", self->threadId);
1703
1704 /*
1705 * Remove the thread from various lists, report its death, and free
1706 * its resources.
1707 */
1708 dvmDetachCurrentThread();
1709
1710 return NULL;
1711}
1712
1713/*
1714 * The current thread is exiting with an uncaught exception. The
1715 * Java programming language allows the application to provide a
1716 * thread-exit-uncaught-exception handler for the VM, for a specific
1717 * Thread, and for all threads in a ThreadGroup.
1718 *
1719 * Version 1.5 added the per-thread handler. We need to call
1720 * "uncaughtException" in the handler object, which is either the
1721 * ThreadGroup object or the Thread-specific handler.
1722 */
1723static void threadExitUncaughtException(Thread* self, Object* group)
1724{
1725 Object* exception;
1726 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001727 Method* uncaughtHandler = NULL;
1728 InstField* threadHandler;
1729
1730 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1731 self->threadId, group);
1732 assert(group != NULL);
1733
1734 /*
1735 * Get a pointer to the exception, then clear out the one in the
1736 * thread. We don't want to have it set when executing interpreted code.
1737 */
1738 exception = dvmGetException(self);
1739 dvmAddTrackedAlloc(exception, self);
1740 dvmClearException(self);
1741
1742 /*
1743 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1744 * else use "group" (which is an instance of UncaughtExceptionHandler).
1745 */
1746 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1747 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1748 if (threadHandler == NULL) {
1749 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1750 goto bail;
1751 }
1752 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1753 if (handlerObj == NULL)
1754 handlerObj = group;
1755
1756 /*
1757 * Find the "uncaughtHandler" field in this object.
1758 */
1759 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1760 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1761
1762 if (uncaughtHandler != NULL) {
1763 //LOGI("+++ calling %s.uncaughtException\n",
1764 // handlerObj->clazz->descriptor);
1765 JValue unused;
1766 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1767 self->threadObj, exception);
1768 } else {
1769 /* restore it and dump a stack trace */
1770 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1771 handlerObj->clazz->descriptor);
1772 dvmSetException(self, exception);
1773 dvmLogExceptionStackTrace();
1774 }
1775
1776bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001777#if defined(WITH_JIT)
1778 /* Remove this thread's suspendCount from global suspendCount sum */
1779 lockThreadSuspendCount();
1780 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1781 unlockThreadSuspendCount();
1782#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001783 dvmReleaseTrackedAlloc(exception, self);
1784}
1785
1786
1787/*
1788 * Create an internal VM thread, for things like JDWP and finalizers.
1789 *
1790 * The easiest way to do this is create a new thread and then use the
1791 * JNI AttachCurrentThread implementation.
1792 *
1793 * This does not return until after the new thread has begun executing.
1794 */
1795bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1796 InternalThreadStart func, void* funcArg)
1797{
1798 InternalStartArgs* pArgs;
1799 Object* systemGroup;
1800 pthread_attr_t threadAttr;
1801 volatile Thread* newThread = NULL;
1802 volatile int createStatus = 0;
1803
1804 systemGroup = dvmGetSystemThreadGroup();
1805 if (systemGroup == NULL)
1806 return false;
1807
1808 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1809 pArgs->func = func;
1810 pArgs->funcArg = funcArg;
1811 pArgs->name = strdup(name); // storage will be owned by new thread
1812 pArgs->group = systemGroup;
1813 pArgs->isDaemon = true;
1814 pArgs->pThread = &newThread;
1815 pArgs->pCreateStatus = &createStatus;
1816
1817 pthread_attr_init(&threadAttr);
1818 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1819
1820 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1821 pArgs) != 0)
1822 {
1823 LOGE("internal thread creation failed\n");
1824 free(pArgs->name);
1825 free(pArgs);
1826 return false;
1827 }
1828
1829 /*
1830 * Wait for the child to start. This gives us an opportunity to make
1831 * sure that the thread started correctly, and allows our caller to
1832 * assume that the thread has started running.
1833 *
1834 * Because we aren't holding a lock across the thread creation, it's
1835 * possible that the child will already have completed its
1836 * initialization. Because the child only adjusts "createStatus" while
1837 * holding the thread list lock, the initial condition on the "while"
1838 * loop will correctly avoid the wait if this occurs.
1839 *
1840 * It's also possible that we'll have to wait for the thread to finish
1841 * being created, and as part of allocating a Thread object it might
1842 * need to initiate a GC. We switch to VMWAIT while we pause.
1843 */
1844 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001845 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001846 dvmLockThreadList(self);
1847 while (createStatus == 0)
1848 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1849
1850 if (newThread == NULL) {
1851 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1852 assert(createStatus < 0);
1853 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1854 dvmUnlockThreadList();
1855 dvmChangeStatus(self, oldStatus);
1856 return false;
1857 }
1858
1859 /* thread could be in any state now (except early init states) */
1860 //assert(newThread->status == THREAD_RUNNING);
1861
1862 dvmUnlockThreadList();
1863 dvmChangeStatus(self, oldStatus);
1864
1865 return true;
1866}
1867
1868/*
1869 * pthread entry function for internally-created threads.
1870 *
1871 * We are expected to free "arg" and its contents. If we're a daemon
1872 * thread, and we get cancelled abruptly when the VM shuts down, the
1873 * storage won't be freed. If this becomes a concern we can make a copy
1874 * on the stack.
1875 */
1876static void* internalThreadStart(void* arg)
1877{
1878 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1879 JavaVMAttachArgs jniArgs;
1880
1881 jniArgs.version = JNI_VERSION_1_2;
1882 jniArgs.name = pArgs->name;
1883 jniArgs.group = pArgs->group;
1884
1885 setThreadName(pArgs->name);
1886
1887 /* use local jniArgs as stack top */
1888 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1889 /*
1890 * Tell the parent of our success.
1891 *
1892 * threadListLock is the mutex for threadStartCond.
1893 */
1894 dvmLockThreadList(dvmThreadSelf());
1895 *pArgs->pCreateStatus = 1;
1896 *pArgs->pThread = dvmThreadSelf();
1897 pthread_cond_broadcast(&gDvm.threadStartCond);
1898 dvmUnlockThreadList();
1899
1900 LOG_THREAD("threadid=%d: internal '%s'\n",
1901 dvmThreadSelf()->threadId, pArgs->name);
1902
1903 /* execute */
1904 (*pArgs->func)(pArgs->funcArg);
1905
1906 /* detach ourselves */
1907 dvmDetachCurrentThread();
1908 } else {
1909 /*
1910 * Tell the parent of our failure. We don't have a Thread struct,
1911 * so we can't be suspended, so we don't need to enter a critical
1912 * section.
1913 */
1914 dvmLockThreadList(dvmThreadSelf());
1915 *pArgs->pCreateStatus = -1;
1916 assert(*pArgs->pThread == NULL);
1917 pthread_cond_broadcast(&gDvm.threadStartCond);
1918 dvmUnlockThreadList();
1919
1920 assert(*pArgs->pThread == NULL);
1921 }
1922
1923 free(pArgs->name);
1924 free(pArgs);
1925 return NULL;
1926}
1927
1928/*
1929 * Attach the current thread to the VM.
1930 *
1931 * Used for internally-created threads and JNI's AttachCurrentThread.
1932 */
1933bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1934{
1935 Thread* self = NULL;
1936 Object* threadObj = NULL;
1937 Object* vmThreadObj = NULL;
1938 StringObject* threadNameStr = NULL;
1939 Method* init;
1940 bool ok, ret;
1941
Andy McFaddene3346d82010-06-02 15:37:21 -07001942 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001943 self = allocThread(gDvm.stackSize);
1944 if (self == NULL)
1945 goto fail;
1946 setThreadSelf(self);
1947
1948 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001949 * Finish our thread prep. We need to do this before adding ourselves
1950 * to the thread list or invoking any interpreted code. prepareThread()
1951 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001952 */
1953 dvmLockThreadList(self);
1954 ok = prepareThread(self);
1955 dvmUnlockThreadList();
1956 if (!ok)
1957 goto fail;
1958
1959 self->jniEnv = dvmCreateJNIEnv(self);
1960 if (self->jniEnv == NULL)
1961 goto fail;
1962
1963 /*
1964 * Create a "fake" JNI frame at the top of the main thread interp stack.
1965 * It isn't really necessary for the internal threads, but it gives
1966 * the debugger something to show. It is essential for the JNI-attached
1967 * threads.
1968 */
1969 if (!createFakeRunFrame(self))
1970 goto fail;
1971
1972 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001973 * The native side of the thread is ready; add it to the list. Once
1974 * 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 -08001975 */
1976 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1977
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001978 dvmLockThreadList(self);
1979
1980 self->next = gDvm.threadList->next;
1981 if (self->next != NULL)
1982 self->next->prev = self;
1983 self->prev = gDvm.threadList;
1984 gDvm.threadList->next = self;
1985 if (!isDaemon)
1986 gDvm.nonDaemonThreadCount++;
1987
1988 dvmUnlockThreadList();
1989
1990 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001991 * Switch state from initializing to running.
1992 *
1993 * It's possible that a GC began right before we added ourselves
1994 * to the thread list, and is still going. That means our thread
1995 * suspend count won't reflect the fact that we should be suspended.
1996 * To deal with this, we transition to VMWAIT, pulse the heap lock,
1997 * and then advance to RUNNING. That will ensure that we stall until
1998 * the GC completes.
1999 *
2000 * Once we're in RUNNING, we're like any other thread in the VM (except
2001 * for the lack of an initialized threadObj). We're then free to
2002 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002003 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002004 assert(self->status == THREAD_INITIALIZING);
2005 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002006 dvmLockMutex(&gDvm.gcHeapLock);
2007 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002008 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002009
2010 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002011 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002012 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002013 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2014 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2015 if (threadObj == NULL || vmThreadObj == NULL)
2016 goto fail_unlink;
2017
2018 /*
2019 * This makes threadObj visible to the GC. We still have it in the
2020 * tracked allocation table, so it can't move around on us.
2021 */
2022 self->threadObj = threadObj;
2023 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2024
2025 /*
2026 * Create a string for the thread name.
2027 */
2028 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002029 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002030 if (threadNameStr == NULL) {
2031 assert(dvmCheckException(dvmThreadSelf()));
2032 goto fail_unlink;
2033 }
2034 }
2035
2036 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2037 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2038 if (init == NULL) {
2039 assert(dvmCheckException(self));
2040 goto fail_unlink;
2041 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002042
2043 /*
2044 * Now we're ready to run some interpreted code.
2045 *
2046 * We need to construct the Thread object and set the VMThread field.
2047 * Setting VMThread tells interpreted code that we're alive.
2048 *
2049 * Call the (group, name, priority, daemon) constructor on the Thread.
2050 * This sets the thread's name and adds it to the specified group, and
2051 * provides values for priority and daemon (which are normally inherited
2052 * from the current thread).
2053 */
2054 JValue unused;
2055 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2056 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2057 if (dvmCheckException(self)) {
2058 LOGE("exception thrown while constructing attached thread object\n");
2059 goto fail_unlink;
2060 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002061
2062 /*
2063 * Set the VMThread field, which tells interpreted code that we're alive.
2064 *
2065 * The risk of a thread start collision here is very low; somebody
2066 * would have to be deliberately polling the ThreadGroup list and
2067 * trying to start threads against anything it sees, which would
2068 * generally cause problems for all thread creation. However, for
2069 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002070 *
2071 * TODO: this still has a race, it's just smaller. Not sure this is
2072 * worth putting effort into fixing. Need to hold a lock while
2073 * fiddling with the field, or maybe initialize the Thread object in a
2074 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002075 */
2076 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002077 LOGW("WOW: thread start hijack\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002078 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2079 "thread has already been started");
2080 /* We don't want to free anything associated with the thread
2081 * because someone is obviously interested in it. Just let
2082 * it go and hope it will clean itself up when its finished.
2083 * This case should never happen anyway.
2084 *
2085 * Since we're letting it live, we need to finish setting it up.
2086 * We just have to let the caller know that the intended operation
2087 * has failed.
2088 *
2089 * [ This seems strange -- stepping on the vmThread object that's
2090 * already present seems like a bad idea. TODO: figure this out. ]
2091 */
2092 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002093 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002094 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002095 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002096 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2097
Andy McFaddene3346d82010-06-02 15:37:21 -07002098 /* we can now safely un-pin these */
2099 dvmReleaseTrackedAlloc(threadObj, self);
2100 dvmReleaseTrackedAlloc(vmThreadObj, self);
2101 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002102
2103 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2104 self->threadId, pArgs->name);
2105
2106 /* tell the debugger & DDM */
2107 if (gDvm.debuggerConnected)
2108 dvmDbgPostThreadStart(self);
2109
2110 return ret;
2111
2112fail_unlink:
2113 dvmLockThreadList(self);
2114 unlinkThread(self);
2115 if (!isDaemon)
2116 gDvm.nonDaemonThreadCount--;
2117 dvmUnlockThreadList();
2118 /* fall through to "fail" */
2119fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002120 dvmReleaseTrackedAlloc(threadObj, self);
2121 dvmReleaseTrackedAlloc(vmThreadObj, self);
2122 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002123 if (self != NULL) {
2124 if (self->jniEnv != NULL) {
2125 dvmDestroyJNIEnv(self->jniEnv);
2126 self->jniEnv = NULL;
2127 }
2128 freeThread(self);
2129 }
2130 setThreadSelf(NULL);
2131 return false;
2132}
2133
2134/*
2135 * Detach the thread from the various data structures, notify other threads
2136 * that are waiting to "join" it, and free up all heap-allocated storage.
2137 *
2138 * Used for all threads.
2139 *
2140 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2141 * requires us to enforce this for the DetachCurrentThread call, probably
2142 * because it also says that DetachCurrentThread causes all monitors
2143 * associated with the thread to be released. (Because the stack is empty,
2144 * we only have to worry about explicit JNI calls to MonitorEnter.)
2145 *
2146 * THOUGHT:
2147 * We might want to avoid freeing our internal Thread structure until the
2148 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2149 * get to once the thread shuts down, but there is a small possibility of
2150 * an operation starting in another thread before this thread halts, and
2151 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2152 * We don't want something like Thread.isInterrupted() crawling through
2153 * freed storage. Can do with a Thread finalizer, or by creating a
2154 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2155 * state into that.
2156 */
2157void dvmDetachCurrentThread(void)
2158{
2159 Thread* self = dvmThreadSelf();
2160 Object* vmThread;
2161 Object* group;
2162
2163 /*
2164 * Make sure we're not detaching a thread that's still running. (This
2165 * could happen with an explicit JNI detach call.)
2166 *
2167 * A thread created by interpreted code will finish with a depth of
2168 * zero, while a JNI-attached thread will have the synthetic "stack
2169 * starter" native method at the top.
2170 */
2171 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2172 if (curDepth != 0) {
2173 bool topIsNative = false;
2174
2175 if (curDepth == 1) {
2176 /* not expecting a lingering break frame; just look at curFrame */
2177 assert(!dvmIsBreakFrame(self->curFrame));
2178 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2179 if (dvmIsNativeMethod(ssa->method))
2180 topIsNative = true;
2181 }
2182
2183 if (!topIsNative) {
2184 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2185 curDepth);
2186 dvmDumpThread(self, false);
2187 dvmAbort();
2188 }
2189 }
2190
2191 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2192 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2193
2194 /*
2195 * Release any held monitors. Since there are no interpreted stack
2196 * frames, the only thing left are the monitors held by JNI MonitorEnter
2197 * calls.
2198 */
2199 dvmReleaseJniMonitors(self);
2200
2201 /*
2202 * Do some thread-exit uncaught exception processing if necessary.
2203 */
2204 if (dvmCheckException(self))
2205 threadExitUncaughtException(self, group);
2206
2207 /*
2208 * Remove the thread from the thread group.
2209 */
2210 if (group != NULL) {
2211 Method* removeThread =
2212 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2213 JValue unused;
2214 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2215 }
2216
2217 /*
2218 * Clear the vmThread reference in the Thread object. Interpreted code
2219 * will now see that this Thread is not running. As this may be the
2220 * only reference to the VMThread object that the VM knows about, we
2221 * have to create an internal reference to it first.
2222 */
2223 vmThread = dvmGetFieldObject(self->threadObj,
2224 gDvm.offJavaLangThread_vmThread);
2225 dvmAddTrackedAlloc(vmThread, self);
2226 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2227
2228 /* clear out our struct Thread pointer, since it's going away */
2229 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2230
2231 /*
2232 * Tell the debugger & DDM. This may cause the current thread or all
2233 * threads to suspend.
2234 *
2235 * The JDWP spec is somewhat vague about when this happens, other than
2236 * that it's issued by the dying thread, which may still appear in
2237 * an "all threads" listing.
2238 */
2239 if (gDvm.debuggerConnected)
2240 dvmDbgPostThreadDeath(self);
2241
2242 /*
2243 * Thread.join() is implemented as an Object.wait() on the VMThread
2244 * object. Signal anyone who is waiting.
2245 */
2246 dvmLockObject(self, vmThread);
2247 dvmObjectNotifyAll(self, vmThread);
2248 dvmUnlockObject(self, vmThread);
2249
2250 dvmReleaseTrackedAlloc(vmThread, self);
2251 vmThread = NULL;
2252
2253 /*
2254 * We're done manipulating objects, so it's okay if the GC runs in
2255 * parallel with us from here out. It's important to do this if
2256 * profiling is enabled, since we can wait indefinitely.
2257 */
2258 self->status = THREAD_VMWAIT;
2259
2260#ifdef WITH_PROFILER
2261 /*
2262 * If we're doing method trace profiling, we don't want threads to exit,
2263 * because if they do we'll end up reusing thread IDs. This complicates
2264 * analysis and makes it impossible to have reasonable output in the
2265 * "threads" section of the "key" file.
2266 *
2267 * We need to do this after Thread.join() completes, or other threads
2268 * could get wedged. Since self->threadObj is still valid, the Thread
2269 * object will not get GCed even though we're no longer in the ThreadGroup
2270 * list (which is important since the profiling thread needs to get
2271 * the thread's name).
2272 */
2273 MethodTraceState* traceState = &gDvm.methodTrace;
2274
2275 dvmLockMutex(&traceState->startStopLock);
2276 if (traceState->traceEnabled) {
2277 LOGI("threadid=%d: waiting for method trace to finish\n",
2278 self->threadId);
2279 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002280 dvmWaitCond(&traceState->threadExitCond,
2281 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002282 }
2283 }
2284 dvmUnlockMutex(&traceState->startStopLock);
2285#endif
2286
2287 dvmLockThreadList(self);
2288
2289 /*
2290 * Lose the JNI context.
2291 */
2292 dvmDestroyJNIEnv(self->jniEnv);
2293 self->jniEnv = NULL;
2294
2295 self->status = THREAD_ZOMBIE;
2296
2297 /*
2298 * Remove ourselves from the internal thread list.
2299 */
2300 unlinkThread(self);
2301
2302 /*
2303 * If we're the last one standing, signal anybody waiting in
2304 * DestroyJavaVM that it's okay to exit.
2305 */
2306 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2307 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2308
2309 if (gDvm.nonDaemonThreadCount == 0) {
2310 int cc;
2311
2312 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2313 //dvmDumpAllThreads(false);
2314 // cond var guarded by threadListLock, which we already hold
2315 cc = pthread_cond_signal(&gDvm.vmExitCond);
2316 assert(cc == 0);
2317 }
2318 }
2319
2320 LOGV("threadid=%d: bye!\n", self->threadId);
2321 releaseThreadId(self);
2322 dvmUnlockThreadList();
2323
2324 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002325
Bob Lee2fe146a2009-09-10 00:36:29 +02002326 dvmDetachSystemThread(self);
Bob Lee9dc72a32009-09-04 18:28:16 -07002327
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002328 freeThread(self);
2329}
2330
2331
2332/*
2333 * Suspend a single thread. Do not use to suspend yourself.
2334 *
2335 * This is used primarily for debugger/DDMS activity. Does not return
2336 * until the thread has suspended or is in a "safe" state (e.g. executing
2337 * native code outside the VM).
2338 *
2339 * The thread list lock should be held before calling here -- it's not
2340 * entirely safe to hang on to a Thread* from another thread otherwise.
2341 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2342 */
2343void dvmSuspendThread(Thread* thread)
2344{
2345 assert(thread != NULL);
2346 assert(thread != dvmThreadSelf());
2347 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2348
2349 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002350 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002351 thread->dbgSuspendCount++;
2352
2353 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2354 thread->threadId, thread->suspendCount);
2355 unlockThreadSuspendCount();
2356
2357 waitForThreadSuspend(dvmThreadSelf(), thread);
2358}
2359
2360/*
2361 * Reduce the suspend count of a thread. If it hits zero, tell it to
2362 * resume.
2363 *
2364 * Used primarily for debugger/DDMS activity. The thread in question
2365 * might have been suspended singly or as part of a suspend-all operation.
2366 *
2367 * The thread list lock should be held before calling here -- it's not
2368 * entirely safe to hang on to a Thread* from another thread otherwise.
2369 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2370 */
2371void dvmResumeThread(Thread* thread)
2372{
2373 assert(thread != NULL);
2374 assert(thread != dvmThreadSelf());
2375 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2376
2377 lockThreadSuspendCount();
2378 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002379 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002380 thread->dbgSuspendCount--;
2381 } else {
2382 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2383 thread->threadId);
2384 }
2385
2386 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2387 thread->threadId, thread->suspendCount);
2388
2389 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002390 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002391 }
2392
2393 unlockThreadSuspendCount();
2394}
2395
2396/*
2397 * Suspend yourself, as a result of debugger activity.
2398 */
2399void dvmSuspendSelf(bool jdwpActivity)
2400{
2401 Thread* self = dvmThreadSelf();
2402
2403 /* debugger thread may not suspend itself due to debugger activity! */
2404 assert(gDvm.jdwpState != NULL);
2405 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2406 assert(false);
2407 return;
2408 }
2409
2410 /*
2411 * Collisions with other suspends aren't really interesting. We want
2412 * to ensure that we're the only one fiddling with the suspend count
2413 * though.
2414 */
2415 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002416 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002417 self->dbgSuspendCount++;
2418
2419 /*
2420 * Suspend ourselves.
2421 */
2422 assert(self->suspendCount > 0);
2423 self->isSuspended = true;
2424 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2425
2426 /*
2427 * Tell JDWP that we've completed suspension. The JDWP thread can't
2428 * tell us to resume before we're fully asleep because we hold the
2429 * suspend count lock.
2430 *
2431 * If we got here via waitForDebugger(), don't do this part.
2432 */
2433 if (jdwpActivity) {
2434 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2435 // self->threadId, (int) self->handle);
2436 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2437 }
2438
2439 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002440 dvmWaitCond(&gDvm.threadSuspendCountCond,
2441 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002442 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002443 /*
2444 * The condition was signaled but we're still suspended. This
2445 * can happen if the debugger lets go while a SIGQUIT thread
2446 * dump event is pending (assuming SignalCatcher was resumed for
2447 * just long enough to try to grab the thread-suspend lock).
2448 */
2449 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
2450 self->threadId, self->suspendCount, self->dbgSuspendCount,
2451 self->isSuspended ? 'Y' : 'N');
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002452 }
2453 }
2454 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2455 self->isSuspended = false;
2456 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2457 self->threadId, self->status);
2458
2459 unlockThreadSuspendCount();
2460}
2461
2462
2463#ifdef HAVE_GLIBC
2464# define NUM_FRAMES 20
2465# include <execinfo.h>
2466/*
2467 * glibc-only stack dump function. Requires link with "--export-dynamic".
2468 *
2469 * TODO: move this into libs/cutils and make it work for all platforms.
2470 */
2471static void printBackTrace(void)
2472{
2473 void* array[NUM_FRAMES];
2474 size_t size;
2475 char** strings;
2476 size_t i;
2477
2478 size = backtrace(array, NUM_FRAMES);
2479 strings = backtrace_symbols(array, size);
2480
2481 LOGW("Obtained %zd stack frames.\n", size);
2482
2483 for (i = 0; i < size; i++)
2484 LOGW("%s\n", strings[i]);
2485
2486 free(strings);
2487}
2488#else
2489static void printBackTrace(void) {}
2490#endif
2491
2492/*
2493 * Dump the state of the current thread and that of another thread that
2494 * we think is wedged.
2495 */
2496static void dumpWedgedThread(Thread* thread)
2497{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002498 dvmDumpThread(dvmThreadSelf(), false);
2499 printBackTrace();
2500
2501 // dumping a running thread is risky, but could be useful
2502 dvmDumpThread(thread, true);
2503
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002504 // stop now and get a core dump
2505 //abort();
2506}
2507
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002508/*
2509 * If the thread is running at below-normal priority, temporarily elevate
2510 * it to "normal".
2511 *
2512 * Returns zero if no changes were made. Otherwise, returns bit flags
2513 * indicating what was changed, storing the previous values in the
2514 * provided locations.
2515 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002516int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002517 SchedPolicy* pSavedThreadPolicy)
2518{
2519 errno = 0;
2520 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2521 if (errno != 0) {
2522 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2523 thread->threadId, thread->systemTid);
2524 return 0;
2525 }
2526 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2527 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2528 thread->threadId, thread->systemTid);
2529 return 0;
2530 }
2531
2532 int changeFlags = 0;
2533
2534 /*
2535 * Change the priority if we're in the background group.
2536 */
2537 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2538 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2539 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2540 } else {
2541 changeFlags |= kChangedPolicy;
2542 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2543 thread->systemTid, *pSavedThreadPolicy);
2544 }
2545 }
2546
2547 /*
2548 * getpriority() returns the "nice" value, so larger numbers indicate
2549 * lower priority, with 0 being normal.
2550 */
2551 if (*pSavedThreadPrio > 0) {
2552 const int kHigher = 0;
2553 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2554 LOGW("Couldn't raise priority on tid %d to %d\n",
2555 thread->systemTid, kHigher);
2556 } else {
2557 changeFlags |= kChangedPriority;
2558 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2559 thread->systemTid, *pSavedThreadPrio, kHigher);
2560 }
2561 }
2562
2563 return changeFlags;
2564}
2565
2566/*
2567 * Reset the priority values for the thread in question.
2568 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002569void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002570 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2571{
2572 if ((changeFlags & kChangedPolicy) != 0) {
2573 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2574 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2575 thread->systemTid, savedThreadPolicy);
2576 } else {
2577 LOGD("Restored policy of %d to %d\n",
2578 thread->systemTid, savedThreadPolicy);
2579 }
2580 }
2581
2582 if ((changeFlags & kChangedPriority) != 0) {
2583 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2584 {
2585 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2586 thread->systemTid, savedThreadPrio);
2587 } else {
2588 LOGD("Restored priority on %d to %d\n",
2589 thread->systemTid, savedThreadPrio);
2590 }
2591 }
2592}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002593
2594/*
2595 * Wait for another thread to see the pending suspension and stop running.
2596 * It can either suspend itself or go into a non-running state such as
2597 * VMWAIT or NATIVE in which it cannot interact with the GC.
2598 *
2599 * If we're running at a higher priority, sched_yield() may not do anything,
2600 * so we need to sleep for "long enough" to guarantee that the other
2601 * thread has a chance to finish what it's doing. Sleeping for too short
2602 * a period (e.g. less than the resolution of the sleep clock) might cause
2603 * the scheduler to return immediately, so we want to start with a
2604 * "reasonable" value and expand.
2605 *
2606 * This does not return until the other thread has stopped running.
2607 * Eventually we time out and the VM aborts.
2608 *
2609 * This does not try to detect the situation where two threads are
2610 * waiting for each other to suspend. In normal use this is part of a
2611 * suspend-all, which implies that the suspend-all lock is held, or as
2612 * part of a debugger action in which the JDWP thread is always the one
2613 * doing the suspending. (We may need to re-evaluate this now that
2614 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2615 *
2616 * TODO: track basic stats about time required to suspend VM.
2617 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002618#define FIRST_SLEEP (250*1000) /* 0.25s */
2619#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002620static void waitForThreadSuspend(Thread* self, Thread* thread)
2621{
2622 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002623 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002624 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002625 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002626 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002627 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002628
2629 int sleepIter = 0;
2630 int retryCount = 0;
2631 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002632 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002633
2634 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002635 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002636 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002637 if (firstStartWhen == 0) // first iteration of first attempt
2638 firstStartWhen = startWhen;
2639
2640 /*
2641 * After waiting for a bit, check to see if the target thread is
2642 * running at a reduced priority. If so, bump it up temporarily
2643 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002644 */
2645 if (retryCount == 2) {
2646 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002647 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002648 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002649 }
2650 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002651
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002652#if defined (WITH_JIT)
2653 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002654 * If we're still waiting after the first timeout, unchain all
2655 * translations iff:
2656 * 1) There are new chains formed since the last unchain
2657 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002658 */
Ben Cheng6999d842010-01-26 16:46:15 -08002659 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2660 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002661 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002662 dvmJitUnchainAll();
2663 }
2664#endif
2665
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002666 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002667 * Sleep briefly. The iterative sleep call returns false if we've
2668 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002669 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002670 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002671 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002672 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002673 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002674 thread->threadId, priChangeFlags);
2675 if (retryCount > 1) {
2676 /* stack trace logging is slow; skip on first iter */
2677 dumpWedgedThread(thread);
2678 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002679 complained = true;
2680 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002681
2682 // keep going; could be slow due to valgrind
2683 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002684 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002685
2686 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002687 LOGE("Fatal spin-on-suspend, dumping threads\n");
2688 dvmDumpAllThreads(false);
2689
2690 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002691 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2692 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002693
2694 /* try to get a debuggerd dump from the spinning thread */
2695 dvmNukeThread(thread);
2696 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002697 dvmAbort();
2698 }
2699 }
2700 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002701
2702 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002703 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2704 self->threadId,
2705 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002706 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2707 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002708 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002709 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002710 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002711 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002712}
2713
2714/*
2715 * Suspend all threads except the current one. This is used by the GC,
2716 * the debugger, and by any thread that hits a "suspend all threads"
2717 * debugger event (e.g. breakpoint or exception).
2718 *
2719 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2720 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2721 * create objects and even execute arbitrary code. The "why" argument
2722 * allows the caller to say why the suspension is taking place.
2723 *
2724 * This can be called when a global suspend has already happened, due to
2725 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2726 * doesn't work.
2727 *
2728 * DO NOT grab any locks before calling here. We grab & release the thread
2729 * lock and suspend lock here (and we're not using recursive threads), and
2730 * we might have to self-suspend if somebody else beats us here.
2731 *
2732 * The current thread may not be attached to the VM. This can happen if
2733 * we happen to GC as the result of an allocation of a Thread object.
2734 */
2735void dvmSuspendAllThreads(SuspendCause why)
2736{
2737 Thread* self = dvmThreadSelf();
2738 Thread* thread;
2739
2740 assert(why != 0);
2741
2742 /*
2743 * Start by grabbing the thread suspend lock. If we can't get it, most
2744 * likely somebody else is in the process of performing a suspend or
2745 * resume, so lockThreadSuspend() will cause us to self-suspend.
2746 *
2747 * We keep the lock until all other threads are suspended.
2748 */
2749 lockThreadSuspend("susp-all", why);
2750
2751 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2752
2753 /*
2754 * This is possible if the current thread was in VMWAIT mode when a
2755 * suspend-all happened, and then decided to do its own suspend-all.
2756 * This can happen when a couple of threads have simultaneous events
2757 * of interest to the debugger.
2758 */
2759 //assert(self->suspendCount == 0);
2760
2761 /*
2762 * Increment everybody's suspend count (except our own).
2763 */
2764 dvmLockThreadList(self);
2765
2766 lockThreadSuspendCount();
2767 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2768 if (thread == self)
2769 continue;
2770
2771 /* debugger events don't suspend JDWP thread */
2772 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2773 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2774 continue;
2775
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002776 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002777 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2778 thread->dbgSuspendCount++;
2779 }
2780 unlockThreadSuspendCount();
2781
2782 /*
2783 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2784 * indicate the code is either running natively or sleeping quietly.
2785 * Any attempt to transition back to THREAD_RUNNING will cause a check
2786 * for suspension, so it should be impossible for anything to execute
2787 * interpreted code or modify objects (assuming native code plays nicely).
2788 *
2789 * It's also okay if the thread transitions to a non-RUNNING state.
2790 *
2791 * Note we released the threadSuspendCountLock before getting here,
2792 * so if another thread is fiddling with its suspend count (perhaps
2793 * self-suspending for the debugger) it won't block while we're waiting
2794 * in here.
2795 */
2796 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2797 if (thread == self)
2798 continue;
2799
2800 /* debugger events don't suspend JDWP thread */
2801 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2802 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2803 continue;
2804
2805 /* wait for the other thread to see the pending suspend */
2806 waitForThreadSuspend(self, thread);
2807
Jeff Hao97319a82009-08-12 16:57:15 -07002808 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 -08002809 self->threadId,
2810 thread->threadId, thread->status, thread->suspendCount,
2811 thread->dbgSuspendCount, thread->isSuspended);
2812 }
2813
2814 dvmUnlockThreadList();
2815 unlockThreadSuspend();
2816
2817 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2818}
2819
2820/*
2821 * Resume all threads that are currently suspended.
2822 *
2823 * The "why" must match with the previous suspend.
2824 */
2825void dvmResumeAllThreads(SuspendCause why)
2826{
2827 Thread* self = dvmThreadSelf();
2828 Thread* thread;
2829 int cc;
2830
2831 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2832 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2833
2834 /*
2835 * Decrement the suspend counts for all threads. No need for atomic
2836 * writes, since nobody should be moving until we decrement the count.
2837 * We do need to hold the thread list because of JNI attaches.
2838 */
2839 dvmLockThreadList(self);
2840 lockThreadSuspendCount();
2841 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2842 if (thread == self)
2843 continue;
2844
2845 /* debugger events don't suspend JDWP thread */
2846 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2847 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002848 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002849 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002850 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002851
2852 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002853 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002854 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2855 thread->dbgSuspendCount--;
2856 } else {
2857 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2858 thread->threadId);
2859 }
2860 }
2861 unlockThreadSuspendCount();
2862 dvmUnlockThreadList();
2863
2864 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002865 * In some ways it makes sense to continue to hold the thread-suspend
2866 * lock while we issue the wakeup broadcast. It allows us to complete
2867 * one operation before moving on to the next, which simplifies the
2868 * thread activity debug traces.
2869 *
2870 * This approach caused us some difficulty under Linux, because the
2871 * condition variable broadcast not only made the threads runnable,
2872 * but actually caused them to execute, and it was a while before
2873 * the thread performing the wakeup had an opportunity to release the
2874 * thread-suspend lock.
2875 *
2876 * This is a problem because, when a thread tries to acquire that
2877 * lock, it times out after 3 seconds. If at some point the thread
2878 * is told to suspend, the clock resets; but since the VM is still
2879 * theoretically mid-resume, there's no suspend pending. If, for
2880 * example, the GC was waking threads up while the SIGQUIT handler
2881 * was trying to acquire the lock, we would occasionally time out on
2882 * a busy system and SignalCatcher would abort.
2883 *
2884 * We now perform the unlock before the wakeup broadcast. The next
2885 * suspend can't actually start until the broadcast completes and
2886 * returns, because we're holding the thread-suspend-count lock, but the
2887 * suspending thread is now able to make progress and we avoid the abort.
2888 *
2889 * (Technically there is a narrow window between when we release
2890 * the thread-suspend lock and grab the thread-suspend-count lock.
2891 * This could cause us to send a broadcast to threads with nonzero
2892 * suspend counts, but this is expected and they'll all just fall
2893 * right back to sleep. It's probably safe to grab the suspend-count
2894 * lock before releasing thread-suspend, since we're still following
2895 * the correct order of acquisition, but it feels weird.)
2896 */
2897
2898 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2899 unlockThreadSuspend();
2900
2901 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002902 * Broadcast a notification to all suspended threads, some or all of
2903 * which may choose to wake up. No need to wait for them.
2904 */
2905 lockThreadSuspendCount();
2906 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2907 assert(cc == 0);
2908 unlockThreadSuspendCount();
2909
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002910 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2911}
2912
2913/*
2914 * Undo any debugger suspensions. This is called when the debugger
2915 * disconnects.
2916 */
2917void dvmUndoDebuggerSuspensions(void)
2918{
2919 Thread* self = dvmThreadSelf();
2920 Thread* thread;
2921 int cc;
2922
2923 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2924 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2925
2926 /*
2927 * Decrement the suspend counts for all threads. No need for atomic
2928 * writes, since nobody should be moving until we decrement the count.
2929 * We do need to hold the thread list because of JNI attaches.
2930 */
2931 dvmLockThreadList(self);
2932 lockThreadSuspendCount();
2933 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2934 if (thread == self)
2935 continue;
2936
2937 /* debugger events don't suspend JDWP thread */
2938 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2939 assert(thread->dbgSuspendCount == 0);
2940 continue;
2941 }
2942
2943 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002944 dvmAddToThreadSuspendCount(&thread->suspendCount,
2945 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002946 thread->dbgSuspendCount = 0;
2947 }
2948 unlockThreadSuspendCount();
2949 dvmUnlockThreadList();
2950
2951 /*
2952 * Broadcast a notification to all suspended threads, some or all of
2953 * which may choose to wake up. No need to wait for them.
2954 */
2955 lockThreadSuspendCount();
2956 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2957 assert(cc == 0);
2958 unlockThreadSuspendCount();
2959
2960 unlockThreadSuspend();
2961
2962 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2963}
2964
2965/*
2966 * Determine if a thread is suspended.
2967 *
2968 * As with all operations on foreign threads, the caller should hold
2969 * the thread list lock before calling.
2970 */
2971bool dvmIsSuspended(Thread* thread)
2972{
2973 /*
2974 * The thread could be:
2975 * (1) Running happily. status is RUNNING, isSuspended is false,
2976 * suspendCount is zero. Return "false".
2977 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2978 * suspendCount is nonzero. Return "false".
2979 * (3) Suspended. suspendCount is nonzero, and either (status is
2980 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2981 * Return "true".
2982 * (4) Waking up. suspendCount is zero, status is RUNNING and
2983 * isSuspended is true. Return "false" (since it could change
2984 * out from under us, unless we hold suspendCountLock).
2985 */
2986
2987 return (thread->suspendCount != 0 &&
2988 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2989 (thread->status != THREAD_RUNNING)));
2990}
2991
2992/*
2993 * Wait until another thread self-suspends. This is specifically for
2994 * synchronization between the JDWP thread and a thread that has decided
2995 * to suspend itself after sending an event to the debugger.
2996 *
2997 * Threads that encounter "suspend all" events work as well -- the thread
2998 * in question suspends everybody else and then itself.
2999 *
3000 * We can't hold a thread lock here or in the caller, because we could
3001 * get here just before the to-be-waited-for-thread issues a "suspend all".
3002 * There's an opportunity for badness if the thread we're waiting for exits
3003 * and gets cleaned up, but since the thread in question is processing a
3004 * debugger event, that's not really a possibility. (To avoid deadlock,
3005 * it's important that we not be in THREAD_RUNNING while we wait.)
3006 */
3007void dvmWaitForSuspend(Thread* thread)
3008{
3009 Thread* self = dvmThreadSelf();
3010
3011 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3012 self->threadId, thread->threadId);
3013
3014 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3015 assert(thread != self);
3016 assert(self->status != THREAD_RUNNING);
3017
3018 waitForThreadSuspend(self, thread);
3019
3020 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3021 self->threadId, thread->threadId);
3022}
3023
3024/*
3025 * Check to see if we need to suspend ourselves. If so, go to sleep on
3026 * a condition variable.
3027 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003028 * If "newStatus" is not THREAD_UNDEFINED, we change to that state before
3029 * we release the thread suspend count lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003030 *
3031 * Returns "true" if we suspended ourselves.
3032 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003033static bool checkSuspendAndChangeStatus(Thread* self, ThreadStatus newStatus)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003034{
3035 bool didSuspend;
3036
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003037 assert(self != NULL);
3038 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003039
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003040 /* fast path: if count is zero and no state change, bail immediately */
3041 if (self->suspendCount == 0 && newStatus == THREAD_UNDEFINED) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003042 return false;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003043 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003044
3045 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3046
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003047 didSuspend = (self->suspendCount != 0);
3048 self->isSuspended = true;
3049 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
3050 while (self->suspendCount != 0) {
3051 /* wait for wakeup signal; releases lock */
3052 int cc;
3053 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
3054 &gDvm.threadSuspendCountLock);
3055 assert(cc == 0);
3056 }
3057 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
3058 self->isSuspended = false;
3059 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3060 self->threadId, self->status);
3061
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003062 /*
3063 * The status change needs to happen while the suspend count lock is
3064 * held. Otherwise we could switch to RUNNING after another thread
3065 * increases our suspend count, which isn't a "bad" state for us
3066 * (we'll suspend on the next check) but could be a problem for the
3067 * other thread (which thinks we're safely in VMWAIT or NATIVE with
3068 * a nonzero suspend count, and proceeds to initate GC).
3069 */
3070 if (newStatus != THREAD_UNDEFINED)
3071 self->status = newStatus;
3072
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003073 unlockThreadSuspendCount();
3074
3075 return didSuspend;
3076}
3077
3078/*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003079 * One-argument wrapper for checkSuspendAndChangeStatus().
3080 */
3081bool dvmCheckSuspendPending(Thread* self)
3082{
3083 return checkSuspendAndChangeStatus(self, THREAD_UNDEFINED);
3084}
3085
3086/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003087 * Update our status.
3088 *
3089 * The "self" argument, which may be NULL, is accepted as an optimization.
3090 *
3091 * Returns the old status.
3092 */
3093ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3094{
3095 ThreadStatus oldStatus;
3096
3097 if (self == NULL)
3098 self = dvmThreadSelf();
3099
3100 LOGVV("threadid=%d: (status %d -> %d)\n",
3101 self->threadId, self->status, newStatus);
3102
3103 oldStatus = self->status;
3104
3105 if (newStatus == THREAD_RUNNING) {
3106 /*
3107 * Change our status to THREAD_RUNNING. The transition requires
3108 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003109 * us to be "asleep" in all other states, and another thread could
3110 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003111 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003112 * The check for suspension requires holding the thread suspend
3113 * count lock, which the suspend-all code also grabs. We want to
3114 * check our suspension status and change to RUNNING atomically
3115 * to avoid a situation where suspend-all thinks we're safe
3116 * (e.g. VMWAIT or NATIVE with suspendCount=1) but we've actually
3117 * switched to RUNNING and are executing code.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003118 */
3119 assert(self->status != THREAD_RUNNING);
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003120 checkSuspendAndChangeStatus(self, newStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003121 } else {
3122 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003123 * Not changing to THREAD_RUNNING. No additional work required.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003124 */
3125 self->status = newStatus;
3126 }
3127
3128 return oldStatus;
3129}
3130
3131/*
3132 * Get a statically defined thread group from a field in the ThreadGroup
3133 * Class object. Expected arguments are "mMain" and "mSystem".
3134 */
3135static Object* getStaticThreadGroup(const char* fieldName)
3136{
3137 StaticField* groupField;
3138 Object* groupObj;
3139
3140 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3141 fieldName, "Ljava/lang/ThreadGroup;");
3142 if (groupField == NULL) {
3143 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3144 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3145 return NULL;
3146 }
3147 groupObj = dvmGetStaticFieldObject(groupField);
3148 if (groupObj == NULL) {
3149 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3150 dvmThrowException("Ljava/lang/InternalError;", NULL);
3151 return NULL;
3152 }
3153
3154 return groupObj;
3155}
3156Object* dvmGetSystemThreadGroup(void)
3157{
3158 return getStaticThreadGroup("mSystem");
3159}
3160Object* dvmGetMainThreadGroup(void)
3161{
3162 return getStaticThreadGroup("mMain");
3163}
3164
3165/*
3166 * Given a VMThread object, return the associated Thread*.
3167 *
3168 * NOTE: if the thread detaches, the struct Thread will disappear, and
3169 * we will be touching invalid data. For safety, lock the thread list
3170 * before calling this.
3171 */
3172Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3173{
3174 int vmData;
3175
3176 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003177
3178 if (false) {
3179 Thread* thread = gDvm.threadList;
3180 while (thread != NULL) {
3181 if ((Thread*)vmData == thread)
3182 break;
3183
3184 thread = thread->next;
3185 }
3186
3187 if (thread == NULL) {
3188 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3189 vmThreadObj, (Thread*)vmData);
3190 vmData = 0;
3191 }
3192 }
3193
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003194 return (Thread*) vmData;
3195}
3196
Andy McFadden2b94b302010-03-09 16:38:36 -08003197/*
3198 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003199 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003200 *
3201 * Returns NULL if the thread was not found.
3202 */
3203Thread* dvmGetThreadByHandle(pthread_t handle)
3204{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003205 Thread* thread;
3206 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003207 if (thread->handle == handle)
3208 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003209 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003210 return thread;
3211}
Andy McFadden2b94b302010-03-09 16:38:36 -08003212
Andy McFadden0a24ef92010-03-12 13:39:59 -08003213/*
3214 * Given a threadId, return the associated Thread*.
3215 * Caller must hold the thread list lock.
3216 *
3217 * Returns NULL if the thread was not found.
3218 */
3219Thread* dvmGetThreadByThreadId(u4 threadId)
3220{
3221 Thread* thread;
3222 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3223 if (thread->threadId == threadId)
3224 break;
3225 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003226 return thread;
3227}
3228
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003229
3230/*
3231 * Conversion map for "nice" values.
3232 *
3233 * We use Android thread priority constants to be consistent with the rest
3234 * of the system. In some cases adjacent entries may overlap.
3235 */
3236static const int kNiceValues[10] = {
3237 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3238 ANDROID_PRIORITY_BACKGROUND + 6,
3239 ANDROID_PRIORITY_BACKGROUND + 3,
3240 ANDROID_PRIORITY_BACKGROUND,
3241 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3242 ANDROID_PRIORITY_NORMAL - 2,
3243 ANDROID_PRIORITY_NORMAL - 4,
3244 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3245 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3246 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3247};
3248
3249/*
3250 * Change the priority of a system thread to match that of the Thread object.
3251 *
3252 * We map a priority value from 1-10 to Linux "nice" values, where lower
3253 * numbers indicate higher priority.
3254 */
3255void dvmChangeThreadPriority(Thread* thread, int newPriority)
3256{
3257 pid_t pid = thread->systemTid;
3258 int newNice;
3259
3260 if (newPriority < 1 || newPriority > 10) {
3261 LOGW("bad priority %d\n", newPriority);
3262 newPriority = 5;
3263 }
3264 newNice = kNiceValues[newPriority-1];
3265
Andy McFaddend62c0b52009-08-04 15:02:12 -07003266 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003267 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003268 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003269 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003270 }
3271
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003272 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3273 char* str = dvmGetThreadName(thread);
3274 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3275 pid, str, newPriority, newNice, strerror(errno));
3276 free(str);
3277 } else {
3278 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3279 pid, newPriority, newNice);
3280 }
3281}
3282
3283/*
3284 * Get the thread priority for the current thread by querying the system.
3285 * This is useful when attaching a thread through JNI.
3286 *
3287 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3288 */
3289static int getThreadPriorityFromSystem(void)
3290{
3291 int i, sysprio, jprio;
3292
3293 errno = 0;
3294 sysprio = getpriority(PRIO_PROCESS, 0);
3295 if (sysprio == -1 && errno != 0) {
3296 LOGW("getpriority() failed: %s\n", strerror(errno));
3297 return THREAD_NORM_PRIORITY;
3298 }
3299
3300 jprio = THREAD_MIN_PRIORITY;
3301 for (i = 0; i < NELEM(kNiceValues); i++) {
3302 if (sysprio >= kNiceValues[i])
3303 break;
3304 jprio++;
3305 }
3306 if (jprio > THREAD_MAX_PRIORITY)
3307 jprio = THREAD_MAX_PRIORITY;
3308
3309 return jprio;
3310}
3311
3312
3313/*
3314 * Return true if the thread is on gDvm.threadList.
3315 * Caller should not hold gDvm.threadListLock.
3316 */
3317bool dvmIsOnThreadList(const Thread* thread)
3318{
3319 bool ret = false;
3320
3321 dvmLockThreadList(NULL);
3322 if (thread == gDvm.threadList) {
3323 ret = true;
3324 } else {
3325 ret = thread->prev != NULL || thread->next != NULL;
3326 }
3327 dvmUnlockThreadList();
3328
3329 return ret;
3330}
3331
3332/*
3333 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3334 * output target.
3335 */
3336void dvmDumpThread(Thread* thread, bool isRunning)
3337{
3338 DebugOutputTarget target;
3339
3340 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3341 dvmDumpThreadEx(&target, thread, isRunning);
3342}
3343
3344/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003345 * Try to get the scheduler group.
3346 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003347 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003348 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003349 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003350 *
3351 * We return the part after the "/", which will be an empty string for
3352 * the default cgroup. If the string is longer than "bufLen", the string
3353 * will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003354 *
3355 * TODO: this is cloned from a static function in libcutils; expose that?
Andy McFaddend62c0b52009-08-04 15:02:12 -07003356 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003357static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003358{
3359#ifdef HAVE_ANDROID_OS
3360 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003361 char lineBuf[256];
3362 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003363
Andy McFadden7f64ede2010-03-03 15:37:10 -08003364 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
3365 if (!(fp = fopen(pathBuf, "r"))) {
3366 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003367 }
3368
Andy McFadden7f64ede2010-03-03 15:37:10 -08003369 while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
3370 char *next = lineBuf;
3371 char *subsys;
3372 char *grp;
3373 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003374
Andy McFadden7f64ede2010-03-03 15:37:10 -08003375 /* Junk the first field */
3376 if (!strsep(&next, ":")) {
3377 goto out_bad_data;
3378 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003379
Andy McFadden7f64ede2010-03-03 15:37:10 -08003380 if (!(subsys = strsep(&next, ":"))) {
3381 goto out_bad_data;
3382 }
3383
3384 if (strcmp(subsys, "cpu")) {
3385 /* Not the subsys we're looking for */
3386 continue;
3387 }
3388
3389 if (!(grp = strsep(&next, ":"))) {
3390 goto out_bad_data;
3391 }
3392 grp++; /* Drop the leading '/' */
3393 len = strlen(grp);
3394 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3395
3396 if (bufLen <= len) {
3397 len = bufLen - 1;
3398 }
3399 strncpy(buf, grp, len);
3400 buf[len] = '\0';
3401 fclose(fp);
3402 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003403 }
3404
Andy McFadden7f64ede2010-03-03 15:37:10 -08003405 LOGE("Failed to find cpu subsys");
3406 fclose(fp);
3407 return -1;
3408 out_bad_data:
3409 LOGE("Bad cgroup data {%s}", lineBuf);
3410 fclose(fp);
3411 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003412#else
Andy McFadden7f64ede2010-03-03 15:37:10 -08003413 errno = ENOSYS;
3414 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003415#endif
3416}
3417
3418/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003419 * Convert ThreadStatus to a string.
3420 */
3421const char* dvmGetThreadStatusStr(ThreadStatus status)
3422{
3423 switch (status) {
3424 case THREAD_ZOMBIE: return "ZOMBIE";
3425 case THREAD_RUNNING: return "RUNNABLE";
3426 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3427 case THREAD_MONITOR: return "MONITOR";
3428 case THREAD_WAIT: return "WAIT";
3429 case THREAD_INITIALIZING: return "INITIALIZING";
3430 case THREAD_STARTING: return "STARTING";
3431 case THREAD_NATIVE: return "NATIVE";
3432 case THREAD_VMWAIT: return "VMWAIT";
3433 default: return "UNKNOWN";
3434 }
3435}
3436
3437/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003438 * Print information about the specified thread.
3439 *
3440 * Works best when the thread in question is "self" or has been suspended.
3441 * When dumping a separate thread that's still running, set "isRunning" to
3442 * use a more cautious thread dump function.
3443 */
3444void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3445 bool isRunning)
3446{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003447 Object* threadObj;
3448 Object* groupObj;
3449 StringObject* nameStr;
3450 char* threadName = NULL;
3451 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003452 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003453 bool isDaemon;
3454 int priority; // java.lang.Thread priority
3455 int policy; // pthread policy
3456 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003457 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
3458 int schedstatFd;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003459
Andy McFaddene3346d82010-06-02 15:37:21 -07003460 /*
3461 * Get the java.lang.Thread object. This function gets called from
3462 * some weird debug contexts, so it's possible that there's a GC in
3463 * progress on some other thread. To decrease the chances of the
3464 * thread object being moved out from under us, we add the reference
3465 * to the tracked allocation list, which pins it in place.
3466 *
3467 * If threadObj is NULL, the thread is still in the process of being
3468 * attached to the VM, and there's really nothing interesting to
3469 * say about it yet.
3470 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003471 threadObj = thread->threadObj;
3472 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003473 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003474 return;
3475 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003476 dvmAddTrackedAlloc(threadObj, NULL);
3477
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003478 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3479 gDvm.offJavaLangThread_name);
3480 threadName = dvmCreateCstrFromString(nameStr);
3481
3482 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3483 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3484
3485 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3486 LOGW("Warning: pthread_getschedparam failed\n");
3487 policy = -1;
3488 sp.sched_priority = -1;
3489 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003490 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
3491 sizeof(schedulerGroupBuf)) != 0)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003492 {
3493 strcpy(schedulerGroupBuf, "unknown");
3494 } else if (schedulerGroupBuf[0] == '\0') {
3495 strcpy(schedulerGroupBuf, "default");
3496 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003497
3498 /* a null value for group is not expected, but deal with it anyway */
3499 groupObj = (Object*) dvmGetFieldObject(threadObj,
3500 gDvm.offJavaLangThread_group);
3501 if (groupObj != NULL) {
3502 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3503 "name", "Ljava/lang/String;");
3504 if (offset < 0) {
3505 LOGW("Unable to find 'name' field in ThreadGroup\n");
3506 } else {
3507 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3508 groupName = dvmCreateCstrFromString(nameStr);
3509 }
3510 }
3511 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003512 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003513
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003514 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003515 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003516 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003517 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3518#if defined(WITH_JIT)
3519 thread->inJitCodeCache ? " JIT" : ""
3520#else
3521 ""
3522#endif
3523 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003524 dvmPrintDebugMessage(target,
Andy McFadden2aa43612009-06-17 16:29:30 -07003525 " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003526 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden2aa43612009-06-17 16:29:30 -07003527 thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003528 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003529 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003530 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003531 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003532
Christopher Tate962f8962010-06-02 16:17:46 -07003533 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/%d/task/%d/schedstat",
3534 getpid(), thread->systemTid);
3535 schedstatFd = open(schedstatBuf, O_RDONLY);
3536 if (schedstatFd >= 0) {
3537 int bytes;
3538 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3539 close(schedstatFd);
3540 if (bytes > 1) {
3541 schedstatBuf[bytes-1] = 0; // trailing newline
3542 dvmPrintDebugMessage(target, " | schedstat=( %s )\n", schedstatBuf);
3543 }
3544 }
3545
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003546#ifdef WITH_MONITOR_TRACKING
3547 if (!isRunning) {
3548 LockedObjectData* lod = thread->pLockedObjects;
3549 if (lod != NULL)
3550 dvmPrintDebugMessage(target, " | monitors held:\n");
3551 else
3552 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3553 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003554 Object* obj = lod->obj;
3555 if (obj->clazz == gDvm.classJavaLangClass) {
3556 ClassObject* clazz = (ClassObject*) obj;
3557 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3558 obj, lod->recursionCount, obj->clazz->descriptor,
3559 clazz->descriptor);
3560 } else {
3561 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3562 obj, lod->recursionCount, obj->clazz->descriptor);
3563 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003564 lod = lod->next;
3565 }
3566 }
3567#endif
3568
3569 if (isRunning)
3570 dvmDumpRunningThreadStack(target, thread);
3571 else
3572 dvmDumpThreadStack(target, thread);
3573
Andy McFaddene3346d82010-06-02 15:37:21 -07003574 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003575 free(threadName);
3576 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003577}
3578
3579/*
3580 * Get the name of a thread.
3581 *
3582 * For correctness, the caller should hold the thread list lock to ensure
3583 * that the thread doesn't go away mid-call.
3584 *
3585 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3586 */
3587char* dvmGetThreadName(Thread* thread)
3588{
3589 StringObject* nameObj;
3590
3591 if (thread->threadObj == NULL) {
3592 LOGW("threadObj is NULL, name not available\n");
3593 return strdup("-unknown-");
3594 }
3595
3596 nameObj = (StringObject*)
3597 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3598 return dvmCreateCstrFromString(nameObj);
3599}
3600
3601/*
3602 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3603 * an output target.
3604 */
3605void dvmDumpAllThreads(bool grabLock)
3606{
3607 DebugOutputTarget target;
3608
3609 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3610 dvmDumpAllThreadsEx(&target, grabLock);
3611}
3612
3613/*
3614 * Print information about all known threads. Assumes they have been
3615 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3616 *
3617 * If "grabLock" is true, we grab the thread lock list. This is important
3618 * to do unless the caller already holds the lock.
3619 */
3620void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3621{
3622 Thread* thread;
3623
3624 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3625
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003626#ifdef HAVE_ANDROID_OS
3627 dvmPrintDebugMessage(target,
3628 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3629 gDvm.threadListLock.value,
3630 gDvm._threadSuspendLock.value,
3631 gDvm.threadSuspendCountLock.value,
3632 gDvm.gcHeapLock.value,
3633 gDvm.heapWorkerLock.value,
3634 gDvm.heapWorkerListLock.value);
3635#endif
3636
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003637 if (grabLock)
3638 dvmLockThreadList(dvmThreadSelf());
3639
3640 thread = gDvm.threadList;
3641 while (thread != NULL) {
3642 dvmDumpThreadEx(target, thread, false);
3643
3644 /* verify link */
3645 assert(thread->next == NULL || thread->next->prev == thread);
3646
3647 thread = thread->next;
3648 }
3649
3650 if (grabLock)
3651 dvmUnlockThreadList();
3652}
3653
Andy McFadden384ef6b2010-03-15 17:24:55 -07003654/*
3655 * Nuke the target thread from orbit.
3656 *
3657 * The idea is to send a "crash" signal to the target thread so that
3658 * debuggerd will take notice and dump an appropriate stack trace.
3659 * Because of the way debuggerd works, we have to throw the same signal
3660 * at it twice.
3661 *
3662 * This does not necessarily cause the entire process to stop, but once a
3663 * thread has been nuked the rest of the system is likely to be unstable.
3664 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003665 * performed, but it's advisable (and expected) to call dvmAbort soon.
3666 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003667 */
3668void dvmNukeThread(Thread* thread)
3669{
Andy McFaddena388a162010-03-18 16:27:14 -07003670 /* suppress the heapworker watchdog to assist anyone using a debugger */
3671 gDvm.nativeDebuggerActive = true;
3672
Andy McFadden384ef6b2010-03-15 17:24:55 -07003673 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003674 * Send the signals, separated by a brief interval to allow debuggerd
3675 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3676 * can be used instead of SIGSEGV to avoid making it look like the
3677 * code actually crashed at the current point of execution.
3678 *
3679 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3680 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3681 * you don't get the second stack trace; possibly something in the
3682 * kernel decides that a signal has already been sent and it's time
3683 * to just kill the process. The position in the current thread is
3684 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003685 *
Andy McFaddena388a162010-03-18 16:27:14 -07003686 * The target thread can continue to execute between the two signals.
3687 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003688 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003689 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3690 " cause debuggerd dump\n",
3691 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
3692 pthread_kill(thread->handle, SIGSTKFLT);
Andy McFaddena388a162010-03-18 16:27:14 -07003693 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddend4e09522010-03-23 12:34:43 -07003694 pthread_kill(thread->handle, SIGSTKFLT);
Andy McFadden7122d862010-03-19 15:18:57 -07003695 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003696 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003697
3698 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3699 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003700 LOGD("Continuing\n");
3701}
3702
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003703#ifdef WITH_MONITOR_TRACKING
3704/*
3705 * Count up the #of locked objects in the current thread.
3706 */
3707static int getThreadObjectCount(const Thread* self)
3708{
3709 LockedObjectData* lod;
3710 int count = 0;
3711
3712 lod = self->pLockedObjects;
3713 while (lod != NULL) {
3714 count++;
3715 lod = lod->next;
3716 }
3717 return count;
3718}
3719
3720/*
3721 * Add the object to the thread's locked object list if it doesn't already
3722 * exist. The most recently added object is the most likely to be released
3723 * next, so we insert at the head of the list.
3724 *
3725 * If it already exists, we increase the recursive lock count.
3726 *
3727 * The object's lock may be thin or fat.
3728 */
3729void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3730{
3731 LockedObjectData* newLod;
3732 LockedObjectData* lod;
3733 int* trace;
3734 int depth;
3735
3736 lod = self->pLockedObjects;
3737 while (lod != NULL) {
3738 if (lod->obj == obj) {
3739 lod->recursionCount++;
3740 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3741 return;
3742 }
3743 lod = lod->next;
3744 }
3745
3746 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3747 if (newLod == NULL) {
3748 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3749 return;
3750 }
3751 newLod->obj = obj;
3752 newLod->recursionCount = 0;
3753
3754 if (withTrace) {
3755 trace = dvmFillInStackTraceRaw(self, &depth);
3756 newLod->rawStackTrace = trace;
3757 newLod->stackDepth = depth;
3758 }
3759
3760 newLod->next = self->pLockedObjects;
3761 self->pLockedObjects = newLod;
3762
3763 LOGV("+++ threadid=%d: added %p, now %d\n",
3764 self->threadId, newLod, getThreadObjectCount(self));
3765}
3766
3767/*
3768 * Remove the object from the thread's locked object list. If the entry
3769 * has a nonzero recursion count, we just decrement the count instead.
3770 */
3771void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3772{
3773 LockedObjectData* lod;
3774 LockedObjectData* prevLod;
3775
3776 lod = self->pLockedObjects;
3777 prevLod = NULL;
3778 while (lod != NULL) {
3779 if (lod->obj == obj) {
3780 if (lod->recursionCount > 0) {
3781 lod->recursionCount--;
3782 LOGV("+++ -recursive lock %p -> %d\n",
3783 obj, lod->recursionCount);
3784 return;
3785 } else {
3786 break;
3787 }
3788 }
3789 prevLod = lod;
3790 lod = lod->next;
3791 }
3792
3793 if (lod == NULL) {
3794 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3795 return;
3796 }
3797 if (prevLod == NULL) {
3798 /* first item in list */
3799 assert(self->pLockedObjects == lod);
3800 self->pLockedObjects = lod->next;
3801 } else {
3802 /* middle/end of list */
3803 prevLod->next = lod->next;
3804 }
3805
3806 LOGV("+++ threadid=%d: removed %p, now %d\n",
3807 self->threadId, lod, getThreadObjectCount(self));
3808 free(lod->rawStackTrace);
3809 free(lod);
3810}
3811
3812/*
3813 * If the specified object is already in the thread's locked object list,
3814 * return the LockedObjectData struct. Otherwise return NULL.
3815 */
3816LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3817{
3818 LockedObjectData* lod;
3819
3820 lod = self->pLockedObjects;
3821 while (lod != NULL) {
3822 if (lod->obj == obj)
3823 return lod;
3824 lod = lod->next;
3825 }
3826 return NULL;
3827}
3828#endif /*WITH_MONITOR_TRACKING*/
3829
3830
3831/*
3832 * GC helper functions
3833 */
3834
The Android Open Source Project99409882009-03-18 22:20:24 -07003835/*
3836 * Add the contents of the registers from the interpreted call stack.
3837 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003838static void gcScanInterpStackReferences(Thread *thread)
3839{
3840 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003841#if WITH_EXTRA_GC_CHECKS > 1
3842 bool first = true;
3843#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003844
3845 framePtr = (const u4 *)thread->curFrame;
3846 while (framePtr != NULL) {
3847 const StackSaveArea *saveArea;
3848 const Method *method;
3849
3850 saveArea = SAVEAREA_FROM_FP(framePtr);
3851 method = saveArea->method;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003852 if (method != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003853#ifdef COUNT_PRECISE_METHODS
3854 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003855 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3856 LOGI("PGC: added %s.%s %p\n",
3857 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003858#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003859#if WITH_EXTRA_GC_CHECKS > 1
3860 /*
3861 * May also want to enable the memset() in the "invokeMethod"
3862 * goto target in the portable interpreter. That sets the stack
3863 * to a pattern that makes referring to uninitialized data
3864 * very obvious.
3865 */
3866
3867 if (first) {
3868 /*
3869 * First frame, isn't native, check the "alternate" saved PC
3870 * as a sanity check.
3871 *
3872 * It seems like we could check the second frame if the first
3873 * is native, since the PCs should be the same. It turns out
3874 * this doesn't always work. The problem is that we could
3875 * have calls in the sequence:
3876 * interp method #2
3877 * native method
3878 * interp method #1
3879 *
3880 * and then GC while in the native method after returning
3881 * from interp method #2. The currentPc on the stack is
3882 * for interp method #1, but thread->currentPc2 is still
3883 * set for the last thing interp method #2 did.
3884 *
3885 * This can also happen in normal execution:
3886 * - sget-object on not-yet-loaded class
3887 * - class init updates currentPc2
3888 * - static field init is handled by parsing annotations;
3889 * static String init requires creation of a String object,
3890 * which can cause a GC
3891 *
3892 * Essentially, any pattern that involves executing
3893 * interpreted code and then causes an allocation without
3894 * executing instructions in the original method will hit
3895 * this. These are rare enough that the test still has
3896 * some value.
3897 */
3898 if (saveArea->xtra.currentPc != thread->currentPc2) {
3899 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3900 saveArea->xtra.currentPc, thread->currentPc2,
3901 method->clazz->descriptor, method->name, method->insns);
3902 if (saveArea->xtra.currentPc != NULL)
3903 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3904 if (thread->currentPc2 != NULL)
3905 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3906 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003907 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003908 } else {
3909 /*
3910 * It's unusual, but not impossible, for a non-first frame
3911 * to be at something other than a method invocation. For
3912 * example, if we do a new-instance on a nonexistent class,
3913 * we'll have a lot of class loader activity on the stack
3914 * above the frame with the "new" operation. Could also
3915 * happen while we initialize a Throwable when an instruction
3916 * fails.
3917 *
3918 * So there's not much we can do here to verify the PC,
3919 * except to verify that it's a GC point.
3920 */
3921 }
3922 assert(saveArea->xtra.currentPc != NULL);
3923#endif
3924
3925 const RegisterMap* pMap;
3926 const u1* regVector;
3927 int i;
3928
Andy McFaddencf8b55c2009-04-13 15:26:03 -07003929 Method* nonConstMethod = (Method*) method; // quiet gcc
3930 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07003931 if (pMap != NULL) {
3932 /* found map, get registers for this address */
3933 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07003934 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07003935 if (regVector == NULL) {
3936 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
3937 method->clazz->descriptor, method->name, addr);
3938 } else {
3939 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
3940 method->clazz->descriptor, method->name, addr,
3941 thread->threadId);
3942 }
3943 } else {
3944 /*
3945 * No map found. If precise GC is disabled this is
3946 * expected -- we don't create pointers to the map data even
3947 * if it's present -- but if it's enabled it means we're
3948 * unexpectedly falling back on a conservative scan, so it's
3949 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07003950 */
3951 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07003952 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07003953 method->clazz->descriptor, method->name);
3954 }
3955 regVector = NULL;
3956 }
3957
3958 if (regVector == NULL) {
3959 /* conservative scan */
3960 for (i = method->registersSize - 1; i >= 0; i--) {
3961 u4 rval = *framePtr++;
3962 if (rval != 0 && (rval & 0x3) == 0) {
3963 dvmMarkIfObject((Object *)rval);
3964 }
3965 }
3966 } else {
3967 /*
3968 * Precise scan. v0 is at the lowest address on the
3969 * interpreted stack, and is the first bit in the register
3970 * vector, so we can walk through the register map and
3971 * memory in the same direction.
3972 *
3973 * A '1' bit indicates a live reference.
3974 */
3975 u2 bits = 1 << 1;
3976 for (i = method->registersSize - 1; i >= 0; i--) {
3977 u4 rval = *framePtr++;
3978
3979 bits >>= 1;
3980 if (bits == 1) {
3981 /* set bit 9 so we can tell when we're empty */
3982 bits = *regVector++ | 0x0100;
3983 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
3984 }
3985
3986 if (rval != 0 && (bits & 0x01) != 0) {
3987 /*
3988 * Non-null, register marked as live reference. This
3989 * should always be a valid object.
3990 */
3991#if WITH_EXTRA_GC_CHECKS > 0
3992 if ((rval & 0x3) != 0 ||
3993 !dvmIsValidObject((Object*) rval))
3994 {
3995 /* this is very bad */
3996 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
3997 method->registersSize-1 - i, rval);
3998 } else
3999#endif
4000 {
4001 dvmMarkObjectNonNull((Object *)rval);
4002 }
4003 } else {
4004 /*
4005 * Null or non-reference, do nothing at all.
4006 */
4007#if WITH_EXTRA_GC_CHECKS > 1
4008 if (dvmIsValidObject((Object*) rval)) {
4009 /* this is normal, but we feel chatty */
4010 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
4011 method->registersSize-1 - i, rval);
4012 }
4013#endif
4014 }
4015 }
4016 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004017 }
4018 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004019
The Android Open Source Project99409882009-03-18 22:20:24 -07004020#if WITH_EXTRA_GC_CHECKS > 1
4021 first = false;
4022#endif
4023
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004024 /* Don't fall into an infinite loop if things get corrupted.
4025 */
4026 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
4027 saveArea->prevFrame == NULL);
4028 framePtr = saveArea->prevFrame;
4029 }
4030}
4031
4032static void gcScanReferenceTable(ReferenceTable *refTable)
4033{
4034 Object **op;
4035
4036 //TODO: these asserts are overkill; turn them off when things stablize.
4037 assert(refTable != NULL);
4038 assert(refTable->table != NULL);
4039 assert(refTable->nextEntry != NULL);
4040 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
4041 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
4042
4043 op = refTable->table;
4044 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
4045 dvmMarkObjectNonNull(*(op++));
4046 }
4047}
4048
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004049#ifdef USE_INDIRECT_REF
Andy McFaddend5ab7262009-08-25 07:19:34 -07004050static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
4051{
4052 Object** op = pRefTable->table;
4053 int numEntries = dvmIndirectRefTableEntries(pRefTable);
4054 int i;
4055
4056 for (i = 0; i < numEntries; i++) {
4057 Object* obj = *op;
4058 if (obj != NULL)
4059 dvmMarkObjectNonNull(obj);
4060 op++;
4061 }
4062}
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004063#endif
Andy McFaddend5ab7262009-08-25 07:19:34 -07004064
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004065/*
4066 * Scan a Thread and mark any objects it references.
4067 */
4068static void gcScanThread(Thread *thread)
4069{
4070 assert(thread != NULL);
4071
4072 /*
4073 * The target thread must be suspended or in a state where it can't do
4074 * any harm (e.g. in Object.wait()). The only exception is the current
4075 * thread, which will still be active and in the "running" state.
4076 *
4077 * (Newly-created threads shouldn't be able to shift themselves to
4078 * RUNNING without a suspend-pending check, so this shouldn't cause
4079 * a false-positive.)
4080 */
Andy McFaddend40223e2009-12-07 15:35:51 -08004081 if (thread->status == THREAD_RUNNING && !thread->isSuspended &&
4082 thread != dvmThreadSelf())
4083 {
4084 Thread* self = dvmThreadSelf();
4085 LOGW("threadid=%d: BUG: GC scanning a running thread (%d)\n",
4086 self->threadId, thread->threadId);
4087 dvmDumpThread(thread, true);
4088 LOGW("Found by:\n");
4089 dvmDumpThread(self, false);
4090
4091 /* continue anyway? */
4092 dvmAbort();
4093 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004094
4095 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
4096
4097 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
4098
4099 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
4100
4101 dvmMarkObject(thread->exception); // usually NULL
4102 gcScanReferenceTable(&thread->internalLocalRefTable);
4103
4104 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
4105
Andy McFaddend5ab7262009-08-25 07:19:34 -07004106#ifdef USE_INDIRECT_REF
4107 gcScanIndirectRefTable(&thread->jniLocalRefTable);
4108#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004109 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07004110#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004111
4112 if (thread->jniMonitorRefTable.table != NULL) {
4113 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
4114
4115 gcScanReferenceTable(&thread->jniMonitorRefTable);
4116 }
4117
4118 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
4119
4120 gcScanInterpStackReferences(thread);
4121
4122 HPROF_CLEAR_GC_SCAN_STATE();
4123}
4124
4125static void gcScanAllThreads()
4126{
4127 Thread *thread;
4128
4129 /* Lock the thread list so we can safely use the
4130 * next/prev pointers.
4131 */
4132 dvmLockThreadList(dvmThreadSelf());
4133
4134 for (thread = gDvm.threadList; thread != NULL;
4135 thread = thread->next)
4136 {
4137 /* We need to scan our own stack, so don't special-case
4138 * the current thread.
4139 */
4140 gcScanThread(thread);
4141 }
4142
4143 dvmUnlockThreadList();
4144}
4145
4146void dvmGcScanRootThreadGroups()
4147{
4148 /* We scan the VM's list of threads instead of going
4149 * through the actual ThreadGroups, but it should be
4150 * equivalent.
4151 *
Jeff Hao97319a82009-08-12 16:57:15 -07004152 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004153 * the root set, which should always be true; it's
4154 * loaded by the built-in class loader, which is part
4155 * of the root set.
4156 */
4157 gcScanAllThreads();
4158}