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