blob: 727c56bcd62b7e66a69b86c8386d8679bc4cbf6e [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
632 //dvmEnterCritical(self);
633 dvmLockThreadList(self);
634
Andy McFadden44860362009-08-06 17:56:14 -0700635 if (self != NULL)
636 threadId = self->threadId;
637
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800638 target = gDvm.threadList;
639 while (target != NULL) {
640 if (target == self) {
641 target = target->next;
642 continue;
643 }
644
645 if (!dvmGetFieldBoolean(target->threadObj,
646 gDvm.offJavaLangThread_daemon))
647 {
Andy McFadden44860362009-08-06 17:56:14 -0700648 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800649 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700650 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800651 }
652
Andy McFadden44860362009-08-06 17:56:14 -0700653 char* threadName = dvmGetThreadName(target);
654 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
655 threadId, target->threadId, threadName);
656 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800657
Andy McFadden44860362009-08-06 17:56:14 -0700658 /* mark as suspended */
659 lockThreadSuspendCount();
660 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
661 unlockThreadSuspendCount();
662 doWait = true;
663
664 target = target->next;
665 }
666
667 //dvmDumpAllThreads(false);
668
669 /*
670 * Unlock the thread list, relocking it later if necessary. It's
671 * possible a thread is in VMWAIT after calling dvmLockThreadList,
672 * and that function *doesn't* check for pending suspend after
673 * acquiring the lock. We want to let them finish their business
674 * and see the pending suspend before we continue here.
675 *
676 * There's no guarantee of mutex fairness, so this might not work.
677 * (The alternative is to have dvmLockThreadList check for suspend
678 * after acquiring the lock and back off, something we should consider.)
679 */
680 dvmUnlockThreadList();
681
682 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800683 bool complained = false;
684
Andy McFadden44860362009-08-06 17:56:14 -0700685 usleep(200 * 1000);
686
687 dvmLockThreadList(self);
688
689 /*
690 * Sleep for a bit until the threads have suspended. We're trying
691 * to exit, so don't wait for too long.
692 */
693 int i;
694 for (i = 0; i < 10; i++) {
695 bool allSuspended = true;
696
697 target = gDvm.threadList;
698 while (target != NULL) {
699 if (target == self) {
700 target = target->next;
701 continue;
702 }
703
704 if (target->status == THREAD_RUNNING && !target->isSuspended) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800705 if (!complained)
706 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700707 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800708 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700709 }
710
711 target = target->next;
712 }
713
714 if (allSuspended) {
715 LOGD("threadid=%d: all daemons have suspended\n", threadId);
716 break;
717 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800718 if (!complained) {
719 complained = true;
720 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
721 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800722 }
Andy McFadden44860362009-08-06 17:56:14 -0700723 }
724
725 usleep(200 * 1000);
726 }
727 dvmUnlockThreadList();
728 }
729
730#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
731 /*
732 * Abandon the threads and recover their resources.
733 */
734 target = gDvm.threadList;
735 while (target != NULL) {
736 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800737 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800738 freeThread(target);
739 target = nextTarget;
740 }
Andy McFadden44860362009-08-06 17:56:14 -0700741#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800742
Andy McFadden44860362009-08-06 17:56:14 -0700743 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800744}
745
746
747/*
748 * Finish preparing the parts of the Thread struct required to support
749 * JNI registration.
750 */
751bool dvmPrepMainForJni(JNIEnv* pEnv)
752{
753 Thread* self;
754
755 /* main thread is always first in list at this point */
756 self = gDvm.threadList;
757 assert(self->threadId == kMainThreadId);
758
759 /* create a "fake" JNI frame at the top of the main thread interp stack */
760 if (!createFakeEntryFrame(self))
761 return false;
762
763 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
764 dvmSetJniEnvThreadId(pEnv, self);
765 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
766
767 return true;
768}
769
770
771/*
772 * Finish preparing the main thread, allocating some objects to represent
773 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700774 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800775 */
776bool dvmPrepMainThread(void)
777{
778 Thread* thread;
779 Object* groupObj;
780 Object* threadObj;
781 Object* vmThreadObj;
782 StringObject* threadNameStr;
783 Method* init;
784 JValue unused;
785
786 LOGV("+++ finishing prep on main VM thread\n");
787
788 /* main thread is always first in list at this point */
789 thread = gDvm.threadList;
790 assert(thread->threadId == kMainThreadId);
791
792 /*
793 * Make sure the classes are initialized. We have to do this before
794 * we create an instance of them.
795 */
796 if (!dvmInitClass(gDvm.classJavaLangClass)) {
797 LOGE("'Class' class failed to initialize\n");
798 return false;
799 }
800 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
801 !dvmInitClass(gDvm.classJavaLangThread) ||
802 !dvmInitClass(gDvm.classJavaLangVMThread))
803 {
804 LOGE("thread classes failed to initialize\n");
805 return false;
806 }
807
808 groupObj = dvmGetMainThreadGroup();
809 if (groupObj == NULL)
810 return false;
811
812 /*
813 * Allocate and construct a Thread with the internal-creation
814 * constructor.
815 */
816 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
817 if (threadObj == NULL) {
818 LOGE("unable to allocate main thread object\n");
819 return false;
820 }
821 dvmReleaseTrackedAlloc(threadObj, NULL);
822
823 threadNameStr = dvmCreateStringFromCstr("main", ALLOC_DEFAULT);
824 if (threadNameStr == NULL)
825 return false;
826 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
827
828 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
829 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
830 assert(init != NULL);
831 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
832 THREAD_NORM_PRIORITY, false);
833 if (dvmCheckException(thread)) {
834 LOGE("exception thrown while constructing main thread object\n");
835 return false;
836 }
837
838 /*
839 * Allocate and construct a VMThread.
840 */
841 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
842 if (vmThreadObj == NULL) {
843 LOGE("unable to allocate main vmthread object\n");
844 return false;
845 }
846 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
847
848 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
849 "(Ljava/lang/Thread;)V");
850 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
851 if (dvmCheckException(thread)) {
852 LOGE("exception thrown while constructing main vmthread object\n");
853 return false;
854 }
855
856 /* set the VMThread.vmData field to our Thread struct */
857 assert(gDvm.offJavaLangVMThread_vmData != 0);
858 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
859
860 /*
861 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700862 * Threads will see that this Thread is running (at least, they would,
863 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800864 */
865 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
866 vmThreadObj);
867
868 thread->threadObj = threadObj;
869
870 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700871 * Set the context class loader. This invokes a ClassLoader method,
872 * which could conceivably call Thread.currentThread(), so we want the
873 * Thread to be fully configured before we do this.
874 */
875 Object* systemLoader = dvmGetSystemClassLoader();
876 if (systemLoader == NULL) {
877 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
878 /* keep going */
879 }
880 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
881 "contextClassLoader", "Ljava/lang/ClassLoader;");
882 if (ctxtClassLoaderOffset < 0) {
883 LOGE("Unable to find contextClassLoader field in Thread\n");
884 return false;
885 }
886 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
887
888 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800889 * Finish our thread prep.
890 */
891
892 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
893 gDvm.nonDaemonThreadCount++;
894
895 return true;
896}
897
898
899/*
900 * Alloc and initialize a Thread struct.
901 *
902 * "threadObj" is the java.lang.Thread object. It will be NULL for the
903 * main VM thread, but non-NULL for everything else.
904 *
905 * Does not create any objects, just stuff on the system (malloc) heap. (If
906 * this changes, we need to use ALLOC_NO_GC. And also verify that we're
907 * ready to load classes at the time this is called.)
908 */
909static Thread* allocThread(int interpStackSize)
910{
911 Thread* thread;
912 u1* stackBottom;
913
914 thread = (Thread*) calloc(1, sizeof(Thread));
915 if (thread == NULL)
916 return NULL;
917
Jeff Hao97319a82009-08-12 16:57:15 -0700918#if defined(WITH_SELF_VERIFICATION)
919 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
920 return NULL;
921#endif
922
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800923 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
924
925 thread->status = THREAD_INITIALIZING;
926 thread->suspendCount = 0;
927
928#ifdef WITH_ALLOC_LIMITS
929 thread->allocLimit = -1;
930#endif
931
932 /*
933 * Allocate and initialize the interpreted code stack. We essentially
934 * "lose" the alloc pointer, which points at the bottom of the stack,
935 * but we can get it back later because we know how big the stack is.
936 *
937 * The stack must be aligned on a 4-byte boundary.
938 */
939#ifdef MALLOC_INTERP_STACK
940 stackBottom = (u1*) malloc(interpStackSize);
941 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700942#if defined(WITH_SELF_VERIFICATION)
943 dvmSelfVerificationShadowSpaceFree(thread);
944#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800945 free(thread);
946 return NULL;
947 }
948 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
949#else
950 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
951 MAP_PRIVATE | MAP_ANON, -1, 0);
952 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700953#if defined(WITH_SELF_VERIFICATION)
954 dvmSelfVerificationShadowSpaceFree(thread);
955#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800956 free(thread);
957 return NULL;
958 }
959#endif
960
961 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
962 thread->interpStackSize = interpStackSize;
963 thread->interpStackStart = stackBottom + interpStackSize;
964 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
965
966 /* give the thread code a chance to set things up */
967 dvmInitInterpStack(thread, interpStackSize);
968
969 return thread;
970}
971
972/*
973 * Get a meaningful thread ID. At present this only has meaning under Linux,
974 * where getpid() and gettid() sometimes agree and sometimes don't depending
975 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
976 */
977pid_t dvmGetSysThreadId(void)
978{
979#ifdef HAVE_GETTID
980 return gettid();
981#else
982 return getpid();
983#endif
984}
985
986/*
987 * Finish initialization of a Thread struct.
988 *
989 * This must be called while executing in the new thread, but before the
990 * thread is added to the thread list.
991 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700992 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800993 * assignThreadId()).
994 */
995static bool prepareThread(Thread* thread)
996{
997 assignThreadId(thread);
998 thread->handle = pthread_self();
999 thread->systemTid = dvmGetSysThreadId();
1000
1001 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1002 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001003 /*
1004 * If we were called by dvmAttachCurrentThread, the self value is
1005 * already correctly established as "thread".
1006 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001007 setThreadSelf(thread);
1008
1009 LOGV("threadid=%d: interp stack at %p\n",
1010 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1011
1012 /*
1013 * Initialize invokeReq.
1014 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001015 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001016 pthread_cond_init(&thread->invokeReq.cv, NULL);
1017
1018 /*
1019 * Initialize our reference tracking tables.
1020 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001021 * Most threads won't use jniMonitorRefTable, so we clear out the
1022 * structure but don't call the init function (which allocs storage).
1023 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001024#ifdef USE_INDIRECT_REF
1025 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1026 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1027 return false;
1028#else
1029 /*
1030 * The JNI local ref table *must* be fixed-size because we keep pointers
1031 * into the table in our stack frames.
1032 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001033 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1034 kJniLocalRefMax, kJniLocalRefMax))
1035 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001036#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001037 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1038 kInternalRefDefault, kInternalRefMax))
1039 return false;
1040
1041 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1042
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001043 pthread_cond_init(&thread->waitCond, NULL);
1044 dvmInitMutex(&thread->waitMutex);
1045
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001046 return true;
1047}
1048
1049/*
1050 * Remove a thread from the internal list.
1051 * Clear out the links to make it obvious that the thread is
1052 * no longer on the list. Caller must hold gDvm.threadListLock.
1053 */
1054static void unlinkThread(Thread* thread)
1055{
1056 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1057 if (thread == gDvm.threadList) {
1058 assert(thread->prev == NULL);
1059 gDvm.threadList = thread->next;
1060 } else {
1061 assert(thread->prev != NULL);
1062 thread->prev->next = thread->next;
1063 }
1064 if (thread->next != NULL)
1065 thread->next->prev = thread->prev;
1066 thread->prev = thread->next = NULL;
1067}
1068
1069/*
1070 * Free a Thread struct, and all the stuff allocated within.
1071 */
1072static void freeThread(Thread* thread)
1073{
1074 if (thread == NULL)
1075 return;
1076
1077 /* thread->threadId is zero at this point */
1078 LOGVV("threadid=%d: freeing\n", thread->threadId);
1079
1080 if (thread->interpStackStart != NULL) {
1081 u1* interpStackBottom;
1082
1083 interpStackBottom = thread->interpStackStart;
1084 interpStackBottom -= thread->interpStackSize;
1085#ifdef MALLOC_INTERP_STACK
1086 free(interpStackBottom);
1087#else
1088 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1089 LOGW("munmap(thread stack) failed\n");
1090#endif
1091 }
1092
Andy McFaddend5ab7262009-08-25 07:19:34 -07001093#ifdef USE_INDIRECT_REF
1094 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1095#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001096 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001097#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001098 dvmClearReferenceTable(&thread->internalLocalRefTable);
1099 if (&thread->jniMonitorRefTable.table != NULL)
1100 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1101
Jeff Hao97319a82009-08-12 16:57:15 -07001102#if defined(WITH_SELF_VERIFICATION)
1103 dvmSelfVerificationShadowSpaceFree(thread);
1104#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001105 free(thread);
1106}
1107
1108/*
1109 * Like pthread_self(), but on a Thread*.
1110 */
1111Thread* dvmThreadSelf(void)
1112{
1113 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1114}
1115
1116/*
1117 * Explore our sense of self. Stuffs the thread pointer into TLS.
1118 */
1119static void setThreadSelf(Thread* thread)
1120{
1121 int cc;
1122
1123 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1124 if (cc != 0) {
1125 /*
1126 * Sometimes this fails under Bionic with EINVAL during shutdown.
1127 * This can happen if the timing is just right, e.g. a thread
1128 * fails to attach during shutdown, but the "fail" path calls
1129 * here to ensure we clean up after ourselves.
1130 */
1131 if (thread != NULL) {
1132 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1133 dvmAbort(); /* the world is fundamentally hosed */
1134 }
1135 }
1136}
1137
1138/*
1139 * This is associated with the pthreadKeySelf key. It's called by the
1140 * pthread library when a thread is exiting and the "self" pointer in TLS
1141 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001142 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001143 *
1144 * This is mainly of use to ensure that we don't leak resources if, for
1145 * example, a thread attaches itself to us with AttachCurrentThread and
1146 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001147 *
1148 * We could do the detach here instead of aborting, but this will lead to
1149 * portability problems. Other implementations do not do this check and
1150 * will simply be unaware that the thread has exited, leading to resource
1151 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1152 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001153 *
1154 * Because some implementations may want to use the pthread destructor
1155 * to initiate the detach, and the ordering of destructors is not defined,
1156 * 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 -08001157 */
1158static void threadExitCheck(void* arg)
1159{
Andy McFadden909ce242009-12-10 16:38:30 -08001160 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001161
Andy McFadden909ce242009-12-10 16:38:30 -08001162 Thread* self = (Thread*) arg;
1163 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001164
Andy McFadden909ce242009-12-10 16:38:30 -08001165 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1166 self->threadId, arg, self->threadExitCheckCount);
1167
1168 if (self->status == THREAD_ZOMBIE) {
1169 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1170 self->threadId);
1171 return;
1172 }
1173
1174 if (self->threadExitCheckCount < kMaxCount) {
1175 /*
1176 * Spin a couple of times to let other destructors fire.
1177 */
1178 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1179 self->threadId, self->threadExitCheckCount);
1180 self->threadExitCheckCount++;
1181 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1182 if (cc != 0) {
1183 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1184 self->threadId);
1185 dvmAbort();
1186 }
1187 } else {
1188 LOGE("threadid=%d: native thread exited without detaching\n",
1189 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001190 dvmAbort();
1191 }
1192}
1193
1194
1195/*
1196 * Assign the threadId. This needs to be a small integer so that our
1197 * "thin" locks fit in a small number of bits.
1198 *
1199 * We reserve zero for use as an invalid ID.
1200 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001201 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001202 */
1203static void assignThreadId(Thread* thread)
1204{
Carl Shapiro59a93122010-01-26 17:12:51 -08001205 /*
1206 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001207 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1208 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001209 */
1210 int num = dvmAllocBit(gDvm.threadIdMap);
1211 if (num < 0) {
1212 LOGE("Ran out of thread IDs\n");
1213 dvmAbort(); // TODO: make this a non-fatal error result
1214 }
1215
Carl Shapiro59a93122010-01-26 17:12:51 -08001216 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001217
1218 assert(thread->threadId != 0);
1219 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1220}
1221
1222/*
1223 * Give back the thread ID.
1224 */
1225static void releaseThreadId(Thread* thread)
1226{
1227 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001228 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001229 thread->threadId = 0;
1230}
1231
1232
1233/*
1234 * Add a stack frame that makes it look like the native code in the main
1235 * thread was originally invoked from interpreted code. This gives us a
1236 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1237 * VM begins by executing "main" in a class, so in a way this brings us
1238 * closer to the spec.
1239 */
1240static bool createFakeEntryFrame(Thread* thread)
1241{
1242 assert(thread->threadId == kMainThreadId); // main thread only
1243
1244 /* find the method on first use */
1245 if (gDvm.methFakeNativeEntry == NULL) {
1246 ClassObject* nativeStart;
1247 Method* mainMeth;
1248
1249 nativeStart = dvmFindSystemClassNoInit(
1250 "Ldalvik/system/NativeStart;");
1251 if (nativeStart == NULL) {
1252 LOGE("Unable to find dalvik.system.NativeStart class\n");
1253 return false;
1254 }
1255
1256 /*
1257 * Because we are creating a frame that represents application code, we
1258 * want to stuff the application class loader into the method's class
1259 * loader field, even though we're using the system class loader to
1260 * load it. This makes life easier over in JNI FindClass (though it
1261 * could bite us in other ways).
1262 *
1263 * Unfortunately this is occurring too early in the initialization,
1264 * of necessity coming before JNI is initialized, and we're not quite
1265 * ready to set up the application class loader.
1266 *
1267 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1268 * and check it in FindClass. The method is private so nobody else
1269 * can call it.
1270 */
1271 //nativeStart->classLoader = dvmGetSystemClassLoader();
1272
1273 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1274 "main", "([Ljava/lang/String;)V");
1275 if (mainMeth == NULL) {
1276 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1277 return false;
1278 }
1279
1280 gDvm.methFakeNativeEntry = mainMeth;
1281 }
1282
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001283 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1284 return false;
1285
1286 /*
1287 * Null out the "String[] args" argument.
1288 */
1289 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1290 u4* framePtr = (u4*) thread->curFrame;
1291 framePtr[0] = 0;
1292
1293 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001294}
1295
1296
1297/*
1298 * Add a stack frame that makes it look like the native thread has been
1299 * executing interpreted code. This gives us a place to hang JNI local
1300 * references.
1301 */
1302static bool createFakeRunFrame(Thread* thread)
1303{
1304 ClassObject* nativeStart;
1305 Method* runMeth;
1306
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001307 /*
1308 * TODO: cache this result so we don't have to dig for it every time
1309 * somebody attaches a thread to the VM. Also consider changing this
1310 * to a static method so we don't have a null "this" pointer in the
1311 * "ins" on the stack. (Does it really need to look like a Runnable?)
1312 */
1313 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001314 if (nativeStart == NULL) {
1315 LOGE("Unable to find dalvik.system.NativeStart class\n");
1316 return false;
1317 }
1318
1319 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1320 if (runMeth == NULL) {
1321 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1322 return false;
1323 }
1324
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001325 if (!dvmPushJNIFrame(thread, runMeth))
1326 return false;
1327
1328 /*
1329 * Provide a NULL 'this' argument. The method we've put at the top of
1330 * the stack looks like a virtual call to run() in a Runnable class.
1331 * (If we declared the method static, it wouldn't take any arguments
1332 * and we wouldn't have to do this.)
1333 */
1334 assert(runMeth->registersSize == 1);
1335 u4* framePtr = (u4*) thread->curFrame;
1336 framePtr[0] = 0;
1337
1338 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001339}
1340
1341/*
1342 * Helper function to set the name of the current thread
1343 */
1344static void setThreadName(const char *threadName)
1345{
1346#if defined(HAVE_PRCTL)
1347 int hasAt = 0;
1348 int hasDot = 0;
1349 const char *s = threadName;
1350 while (*s) {
1351 if (*s == '.') hasDot = 1;
1352 else if (*s == '@') hasAt = 1;
1353 s++;
1354 }
1355 int len = s - threadName;
1356 if (len < 15 || hasAt || !hasDot) {
1357 s = threadName;
1358 } else {
1359 s = threadName + len - 15;
1360 }
1361 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
1362#endif
1363}
1364
1365/*
1366 * Create a thread as a result of java.lang.Thread.start().
1367 *
1368 * We do have to worry about some concurrency problems, e.g. programs
1369 * that try to call Thread.start() on the same object from multiple threads.
1370 * (This will fail for all but one, but we have to make sure that it succeeds
1371 * for exactly one.)
1372 *
1373 * Some of the complexity here arises from our desire to mimic the
1374 * Thread vs. VMThread class decomposition we inherited. We've been given
1375 * a Thread, and now we need to create a VMThread and then populate both
1376 * objects. We also need to create one of our internal Thread objects.
1377 *
1378 * Pass in a stack size of 0 to get the default.
1379 */
1380bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1381{
1382 pthread_attr_t threadAttr;
1383 pthread_t threadHandle;
1384 Thread* self;
1385 Thread* newThread = NULL;
1386 Object* vmThreadObj = NULL;
1387 int stackSize;
1388
1389 assert(threadObj != NULL);
1390
1391 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001392 // Allow the sampling profiler thread. We shut it down before forking.
1393 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1394 gDvm.offJavaLangThread_name);
1395 char* threadName = dvmCreateCstrFromString(nameStr);
1396 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1397 free(threadName);
1398 if (!profilerThread) {
1399 dvmThrowException("Ljava/lang/IllegalStateException;",
1400 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001401
Bob Lee9dc72a32009-09-04 18:28:16 -07001402 goto fail;
1403 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001404 }
1405
1406 self = dvmThreadSelf();
1407 if (reqStackSize == 0)
1408 stackSize = gDvm.stackSize;
1409 else if (reqStackSize < kMinStackSize)
1410 stackSize = kMinStackSize;
1411 else if (reqStackSize > kMaxStackSize)
1412 stackSize = kMaxStackSize;
1413 else
1414 stackSize = reqStackSize;
1415
1416 pthread_attr_init(&threadAttr);
1417 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1418
1419 /*
1420 * To minimize the time spent in the critical section, we allocate the
1421 * vmThread object here.
1422 */
1423 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1424 if (vmThreadObj == NULL)
1425 goto fail;
1426
1427 newThread = allocThread(stackSize);
1428 if (newThread == NULL)
1429 goto fail;
1430 newThread->threadObj = threadObj;
1431
1432 assert(newThread->status == THREAD_INITIALIZING);
1433
1434 /*
1435 * We need to lock out other threads while we test and set the
1436 * "vmThread" field in java.lang.Thread, because we use that to determine
1437 * if this thread has been started before. We use the thread list lock
1438 * because it's handy and we're going to need to grab it again soon
1439 * anyway.
1440 */
1441 dvmLockThreadList(self);
1442
1443 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1444 dvmUnlockThreadList();
1445 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1446 "thread has already been started");
1447 goto fail;
1448 }
1449
1450 /*
1451 * There are actually three data structures: Thread (object), VMThread
1452 * (object), and Thread (C struct). All of them point to at least one
1453 * other.
1454 *
1455 * As soon as "VMThread.vmData" is assigned, other threads can start
1456 * making calls into us (e.g. setPriority).
1457 */
1458 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1459 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1460
1461 /*
1462 * Thread creation might take a while, so release the lock.
1463 */
1464 dvmUnlockThreadList();
1465
Andy McFadden2aa43612009-06-17 16:29:30 -07001466 int cc, oldStatus;
1467 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1468 cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1469 newThread);
1470 oldStatus = dvmChangeStatus(self, oldStatus);
1471
1472 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001473 /*
1474 * Failure generally indicates that we have exceeded system
1475 * resource limits. VirtualMachineError is probably too severe,
1476 * so use OutOfMemoryError.
1477 */
1478 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1479
1480 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1481
1482 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1483 "thread creation failed");
1484 goto fail;
1485 }
1486
1487 /*
1488 * We need to wait for the thread to start. Otherwise, depending on
1489 * the whims of the OS scheduler, we could return and the code in our
1490 * thread could try to do operations on the new thread before it had
1491 * finished starting.
1492 *
1493 * The new thread will lock the thread list, change its state to
1494 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1495 * on gDvm.threadStartCond (which uses the thread list lock). This
1496 * thread (the parent) will either see that the thread is already ready
1497 * after we grab the thread list lock, or will be awakened from the
1498 * condition variable on the broadcast.
1499 *
1500 * We don't want to stall the rest of the VM while the new thread
1501 * starts, which can happen if the GC wakes up at the wrong moment.
1502 * So, we change our own status to VMWAIT, and self-suspend if
1503 * necessary after we finish adding the new thread.
1504 *
1505 *
1506 * We have to deal with an odd race with the GC/debugger suspension
1507 * mechanism when creating a new thread. The information about whether
1508 * or not a thread should be suspended is contained entirely within
1509 * the Thread struct; this is usually cleaner to deal with than having
1510 * one or more globally-visible suspension flags. The trouble is that
1511 * we could create the thread while the VM is trying to suspend all
1512 * threads. The suspend-count won't be nonzero for the new thread,
1513 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1514 *
1515 * The easiest way to deal with this is to prevent the new thread from
1516 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001517 * following (correct) sequence of events for a "badly timed" GC
1518 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001519 *
1520 * - call pthread_create()
1521 * - lock thread list
1522 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1523 * - sleep on condition var (mutex = thread list lock) until child starts
1524 * + GC triggered by another thread
1525 * + thread list locked; suspend counts updated; thread list unlocked
1526 * + loop waiting for all runnable threads to suspend
1527 * + success, start GC
1528 * o child thread wakes, signals condition var to wake parent
1529 * o child waits for parent ack on condition variable
1530 * - we wake up, locking thread list
1531 * - add child to thread list
1532 * - unlock thread list
1533 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1534 * + GC finishes; all threads in thread list are resumed
1535 * - lock thread list
1536 * - set child to THREAD_VMWAIT, and signal it to start
1537 * - unlock thread list
1538 * o child resumes
1539 * o child changes state to THREAD_RUNNING
1540 *
1541 * The above shows the GC starting up during thread creation, but if
1542 * it starts anywhere after VMThread.create() is called it will
1543 * produce the same series of events.
1544 *
1545 * Once the child is in the thread list, it will be suspended and
1546 * resumed like any other thread. In the above scenario the resume-all
1547 * code will try to resume the new thread, which was never actually
1548 * suspended, and try to decrement the child's thread suspend count to -1.
1549 * We can catch this in the resume-all code.
1550 *
1551 * Bouncing back and forth between threads like this adds a small amount
1552 * of scheduler overhead to thread startup.
1553 *
1554 * One alternative to having the child wait for the parent would be
1555 * to have the child inherit the parents' suspension count. This
1556 * would work for a GC, since we can safely assume that the parent
1557 * thread didn't cause it, but we must only do so if the parent suspension
1558 * was caused by a suspend-all. If the parent was being asked to
1559 * suspend singly by the debugger, the child should not inherit the value.
1560 *
1561 * We could also have a global "new thread suspend count" that gets
1562 * picked up by new threads before changing state to THREAD_RUNNING.
1563 * This would be protected by the thread list lock and set by a
1564 * suspend-all.
1565 */
1566 dvmLockThreadList(self);
1567 assert(self->status == THREAD_RUNNING);
1568 self->status = THREAD_VMWAIT;
1569 while (newThread->status != THREAD_STARTING)
1570 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1571
1572 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1573 newThread->next = gDvm.threadList->next;
1574 if (newThread->next != NULL)
1575 newThread->next->prev = newThread;
1576 newThread->prev = gDvm.threadList;
1577 gDvm.threadList->next = newThread;
1578
1579 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1580 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1581
1582 dvmUnlockThreadList();
1583
1584 /* change status back to RUNNING, self-suspending if necessary */
1585 dvmChangeStatus(self, THREAD_RUNNING);
1586
1587 /*
1588 * Tell the new thread to start.
1589 *
1590 * We must hold the thread list lock before messing with another thread.
1591 * In the general case we would also need to verify that newThread was
1592 * still in the thread list, but in our case the thread has not started
1593 * executing user code and therefore has not had a chance to exit.
1594 *
1595 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1596 * comes with a suspend-pending check.
1597 */
1598 dvmLockThreadList(self);
1599
1600 assert(newThread->status == THREAD_STARTING);
1601 newThread->status = THREAD_VMWAIT;
1602 pthread_cond_broadcast(&gDvm.threadStartCond);
1603
1604 dvmUnlockThreadList();
1605
1606 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1607 return true;
1608
1609fail:
1610 freeThread(newThread);
1611 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1612 return false;
1613}
1614
1615/*
1616 * pthread entry function for threads started from interpreted code.
1617 */
1618static void* interpThreadStart(void* arg)
1619{
1620 Thread* self = (Thread*) arg;
1621
1622 char *threadName = dvmGetThreadName(self);
1623 setThreadName(threadName);
1624 free(threadName);
1625
1626 /*
1627 * Finish initializing the Thread struct.
1628 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001629 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001630 prepareThread(self);
1631
1632 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1633
1634 /*
1635 * Change our status and wake our parent, who will add us to the
1636 * thread list and advance our state to VMWAIT.
1637 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001638 self->status = THREAD_STARTING;
1639 pthread_cond_broadcast(&gDvm.threadStartCond);
1640
1641 /*
1642 * Wait until the parent says we can go. Assuming there wasn't a
1643 * suspend pending, this will happen immediately. When it completes,
1644 * we're full-fledged citizens of the VM.
1645 *
1646 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1647 * because the pthread_cond_wait below needs to reacquire a lock that
1648 * suspend-all is also interested in. If we get unlucky, the parent could
1649 * change us to THREAD_RUNNING, then a GC could start before we get
1650 * signaled, and suspend-all will grab the thread list lock and then
1651 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1652 * trying to get the lock.
1653 */
1654 while (self->status != THREAD_VMWAIT)
1655 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1656
1657 dvmUnlockThreadList();
1658
1659 /*
1660 * Add a JNI context.
1661 */
1662 self->jniEnv = dvmCreateJNIEnv(self);
1663
1664 /*
1665 * Change our state so the GC will wait for us from now on. If a GC is
1666 * in progress this call will suspend us.
1667 */
1668 dvmChangeStatus(self, THREAD_RUNNING);
1669
1670 /*
1671 * Notify the debugger & DDM. The debugger notification may cause
1672 * us to suspend ourselves (and others).
1673 */
1674 if (gDvm.debuggerConnected)
1675 dvmDbgPostThreadStart(self);
1676
1677 /*
1678 * Set the system thread priority according to the Thread object's
1679 * priority level. We don't usually need to do this, because both the
1680 * Thread object and system thread priorities inherit from parents. The
1681 * tricky case is when somebody creates a Thread object, calls
1682 * setPriority(), and then starts the thread. We could manage this with
1683 * a "needs priority update" flag to avoid the redundant call.
1684 */
Andy McFadden4879df92009-08-07 14:49:40 -07001685 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001686 gDvm.offJavaLangThread_priority);
1687 dvmChangeThreadPriority(self, priority);
1688
1689 /*
1690 * Execute the "run" method.
1691 *
1692 * At this point our stack is empty, so somebody who comes looking for
1693 * stack traces right now won't have much to look at. This is normal.
1694 */
1695 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1696 JValue unused;
1697
1698 LOGV("threadid=%d: calling run()\n", self->threadId);
1699 assert(strcmp(run->name, "run") == 0);
1700 dvmCallMethod(self, run, self->threadObj, &unused);
1701 LOGV("threadid=%d: exiting\n", self->threadId);
1702
1703 /*
1704 * Remove the thread from various lists, report its death, and free
1705 * its resources.
1706 */
1707 dvmDetachCurrentThread();
1708
1709 return NULL;
1710}
1711
1712/*
1713 * The current thread is exiting with an uncaught exception. The
1714 * Java programming language allows the application to provide a
1715 * thread-exit-uncaught-exception handler for the VM, for a specific
1716 * Thread, and for all threads in a ThreadGroup.
1717 *
1718 * Version 1.5 added the per-thread handler. We need to call
1719 * "uncaughtException" in the handler object, which is either the
1720 * ThreadGroup object or the Thread-specific handler.
1721 */
1722static void threadExitUncaughtException(Thread* self, Object* group)
1723{
1724 Object* exception;
1725 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001726 Method* uncaughtHandler = NULL;
1727 InstField* threadHandler;
1728
1729 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1730 self->threadId, group);
1731 assert(group != NULL);
1732
1733 /*
1734 * Get a pointer to the exception, then clear out the one in the
1735 * thread. We don't want to have it set when executing interpreted code.
1736 */
1737 exception = dvmGetException(self);
1738 dvmAddTrackedAlloc(exception, self);
1739 dvmClearException(self);
1740
1741 /*
1742 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1743 * else use "group" (which is an instance of UncaughtExceptionHandler).
1744 */
1745 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1746 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1747 if (threadHandler == NULL) {
1748 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1749 goto bail;
1750 }
1751 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1752 if (handlerObj == NULL)
1753 handlerObj = group;
1754
1755 /*
1756 * Find the "uncaughtHandler" field in this object.
1757 */
1758 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1759 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1760
1761 if (uncaughtHandler != NULL) {
1762 //LOGI("+++ calling %s.uncaughtException\n",
1763 // handlerObj->clazz->descriptor);
1764 JValue unused;
1765 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1766 self->threadObj, exception);
1767 } else {
1768 /* restore it and dump a stack trace */
1769 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1770 handlerObj->clazz->descriptor);
1771 dvmSetException(self, exception);
1772 dvmLogExceptionStackTrace();
1773 }
1774
1775bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001776#if defined(WITH_JIT)
1777 /* Remove this thread's suspendCount from global suspendCount sum */
1778 lockThreadSuspendCount();
1779 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1780 unlockThreadSuspendCount();
1781#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001782 dvmReleaseTrackedAlloc(exception, self);
1783}
1784
1785
1786/*
1787 * Create an internal VM thread, for things like JDWP and finalizers.
1788 *
1789 * The easiest way to do this is create a new thread and then use the
1790 * JNI AttachCurrentThread implementation.
1791 *
1792 * This does not return until after the new thread has begun executing.
1793 */
1794bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1795 InternalThreadStart func, void* funcArg)
1796{
1797 InternalStartArgs* pArgs;
1798 Object* systemGroup;
1799 pthread_attr_t threadAttr;
1800 volatile Thread* newThread = NULL;
1801 volatile int createStatus = 0;
1802
1803 systemGroup = dvmGetSystemThreadGroup();
1804 if (systemGroup == NULL)
1805 return false;
1806
1807 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1808 pArgs->func = func;
1809 pArgs->funcArg = funcArg;
1810 pArgs->name = strdup(name); // storage will be owned by new thread
1811 pArgs->group = systemGroup;
1812 pArgs->isDaemon = true;
1813 pArgs->pThread = &newThread;
1814 pArgs->pCreateStatus = &createStatus;
1815
1816 pthread_attr_init(&threadAttr);
1817 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1818
1819 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1820 pArgs) != 0)
1821 {
1822 LOGE("internal thread creation failed\n");
1823 free(pArgs->name);
1824 free(pArgs);
1825 return false;
1826 }
1827
1828 /*
1829 * Wait for the child to start. This gives us an opportunity to make
1830 * sure that the thread started correctly, and allows our caller to
1831 * assume that the thread has started running.
1832 *
1833 * Because we aren't holding a lock across the thread creation, it's
1834 * possible that the child will already have completed its
1835 * initialization. Because the child only adjusts "createStatus" while
1836 * holding the thread list lock, the initial condition on the "while"
1837 * loop will correctly avoid the wait if this occurs.
1838 *
1839 * It's also possible that we'll have to wait for the thread to finish
1840 * being created, and as part of allocating a Thread object it might
1841 * need to initiate a GC. We switch to VMWAIT while we pause.
1842 */
1843 Thread* self = dvmThreadSelf();
1844 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1845 dvmLockThreadList(self);
1846 while (createStatus == 0)
1847 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1848
1849 if (newThread == NULL) {
1850 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1851 assert(createStatus < 0);
1852 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1853 dvmUnlockThreadList();
1854 dvmChangeStatus(self, oldStatus);
1855 return false;
1856 }
1857
1858 /* thread could be in any state now (except early init states) */
1859 //assert(newThread->status == THREAD_RUNNING);
1860
1861 dvmUnlockThreadList();
1862 dvmChangeStatus(self, oldStatus);
1863
1864 return true;
1865}
1866
1867/*
1868 * pthread entry function for internally-created threads.
1869 *
1870 * We are expected to free "arg" and its contents. If we're a daemon
1871 * thread, and we get cancelled abruptly when the VM shuts down, the
1872 * storage won't be freed. If this becomes a concern we can make a copy
1873 * on the stack.
1874 */
1875static void* internalThreadStart(void* arg)
1876{
1877 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1878 JavaVMAttachArgs jniArgs;
1879
1880 jniArgs.version = JNI_VERSION_1_2;
1881 jniArgs.name = pArgs->name;
1882 jniArgs.group = pArgs->group;
1883
1884 setThreadName(pArgs->name);
1885
1886 /* use local jniArgs as stack top */
1887 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1888 /*
1889 * Tell the parent of our success.
1890 *
1891 * threadListLock is the mutex for threadStartCond.
1892 */
1893 dvmLockThreadList(dvmThreadSelf());
1894 *pArgs->pCreateStatus = 1;
1895 *pArgs->pThread = dvmThreadSelf();
1896 pthread_cond_broadcast(&gDvm.threadStartCond);
1897 dvmUnlockThreadList();
1898
1899 LOG_THREAD("threadid=%d: internal '%s'\n",
1900 dvmThreadSelf()->threadId, pArgs->name);
1901
1902 /* execute */
1903 (*pArgs->func)(pArgs->funcArg);
1904
1905 /* detach ourselves */
1906 dvmDetachCurrentThread();
1907 } else {
1908 /*
1909 * Tell the parent of our failure. We don't have a Thread struct,
1910 * so we can't be suspended, so we don't need to enter a critical
1911 * section.
1912 */
1913 dvmLockThreadList(dvmThreadSelf());
1914 *pArgs->pCreateStatus = -1;
1915 assert(*pArgs->pThread == NULL);
1916 pthread_cond_broadcast(&gDvm.threadStartCond);
1917 dvmUnlockThreadList();
1918
1919 assert(*pArgs->pThread == NULL);
1920 }
1921
1922 free(pArgs->name);
1923 free(pArgs);
1924 return NULL;
1925}
1926
1927/*
1928 * Attach the current thread to the VM.
1929 *
1930 * Used for internally-created threads and JNI's AttachCurrentThread.
1931 */
1932bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1933{
1934 Thread* self = NULL;
1935 Object* threadObj = NULL;
1936 Object* vmThreadObj = NULL;
1937 StringObject* threadNameStr = NULL;
1938 Method* init;
1939 bool ok, ret;
1940
1941 /* establish a basic sense of self */
1942 self = allocThread(gDvm.stackSize);
1943 if (self == NULL)
1944 goto fail;
1945 setThreadSelf(self);
1946
1947 /*
1948 * Create Thread and VMThread objects. We have to use ALLOC_NO_GC
1949 * because this thread is not yet visible to the VM. We could also
1950 * just grab the GC lock earlier, but that leaves us executing
1951 * interpreted code with the lock held, which is not prudent.
1952 *
1953 * The alloc calls will block if a GC is in progress, so we don't need
1954 * to check for global suspension here.
1955 *
1956 * It's also possible for the allocation calls to *cause* a GC.
1957 */
1958 //BUG: deadlock if a GC happens here during HeapWorker creation
1959 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_NO_GC);
1960 if (threadObj == NULL)
1961 goto fail;
1962 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_NO_GC);
1963 if (vmThreadObj == NULL)
1964 goto fail;
1965
1966 self->threadObj = threadObj;
1967 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1968
1969 /*
1970 * Do some java.lang.Thread constructor prep before we lock stuff down.
1971 */
1972 if (pArgs->name != NULL) {
1973 threadNameStr = dvmCreateStringFromCstr(pArgs->name, ALLOC_NO_GC);
1974 if (threadNameStr == NULL) {
1975 assert(dvmCheckException(dvmThreadSelf()));
1976 goto fail;
1977 }
1978 }
1979
1980 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1981 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1982 if (init == NULL) {
1983 assert(dvmCheckException(dvmThreadSelf()));
1984 goto fail;
1985 }
1986
1987 /*
1988 * Finish our thread prep. We need to do this before invoking any
1989 * interpreted code. prepareThread() requires that we hold the thread
1990 * list lock.
1991 */
1992 dvmLockThreadList(self);
1993 ok = prepareThread(self);
1994 dvmUnlockThreadList();
1995 if (!ok)
1996 goto fail;
1997
1998 self->jniEnv = dvmCreateJNIEnv(self);
1999 if (self->jniEnv == NULL)
2000 goto fail;
2001
2002 /*
2003 * Create a "fake" JNI frame at the top of the main thread interp stack.
2004 * It isn't really necessary for the internal threads, but it gives
2005 * the debugger something to show. It is essential for the JNI-attached
2006 * threads.
2007 */
2008 if (!createFakeRunFrame(self))
2009 goto fail;
2010
2011 /*
2012 * The native side of the thread is ready; add it to the list.
2013 */
2014 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
2015
2016 /* Start off in VMWAIT, because we may be about to block
2017 * on the heap lock, and we don't want any suspensions
2018 * to wait for us.
2019 */
2020 self->status = THREAD_VMWAIT;
2021
2022 /*
2023 * Add ourselves to the thread list. Once we finish here we are
2024 * visible to the debugger and the GC.
2025 */
2026 dvmLockThreadList(self);
2027
2028 self->next = gDvm.threadList->next;
2029 if (self->next != NULL)
2030 self->next->prev = self;
2031 self->prev = gDvm.threadList;
2032 gDvm.threadList->next = self;
2033 if (!isDaemon)
2034 gDvm.nonDaemonThreadCount++;
2035
2036 dvmUnlockThreadList();
2037
2038 /*
2039 * It's possible that a GC is currently running. Our thread
2040 * wasn't in the list when the GC started, so it's not properly
2041 * suspended in that case. Synchronize on the heap lock (held
2042 * when a GC is happening) to guarantee that any GCs from here
2043 * on will see this thread in the list.
2044 */
2045 dvmLockMutex(&gDvm.gcHeapLock);
2046 dvmUnlockMutex(&gDvm.gcHeapLock);
2047
2048 /*
2049 * Switch to the running state now that we're ready for
2050 * suspensions. This call may suspend.
2051 */
2052 dvmChangeStatus(self, THREAD_RUNNING);
2053
2054 /*
2055 * Now we're ready to run some interpreted code.
2056 *
2057 * We need to construct the Thread object and set the VMThread field.
2058 * Setting VMThread tells interpreted code that we're alive.
2059 *
2060 * Call the (group, name, priority, daemon) constructor on the Thread.
2061 * This sets the thread's name and adds it to the specified group, and
2062 * provides values for priority and daemon (which are normally inherited
2063 * from the current thread).
2064 */
2065 JValue unused;
2066 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2067 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2068 if (dvmCheckException(self)) {
2069 LOGE("exception thrown while constructing attached thread object\n");
2070 goto fail_unlink;
2071 }
2072 //if (isDaemon)
2073 // dvmSetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon, true);
2074
2075 /*
2076 * Set the VMThread field, which tells interpreted code that we're alive.
2077 *
2078 * The risk of a thread start collision here is very low; somebody
2079 * would have to be deliberately polling the ThreadGroup list and
2080 * trying to start threads against anything it sees, which would
2081 * generally cause problems for all thread creation. However, for
2082 * correctness we test "vmThread" before setting it.
2083 */
2084 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
2085 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2086 "thread has already been started");
2087 /* We don't want to free anything associated with the thread
2088 * because someone is obviously interested in it. Just let
2089 * it go and hope it will clean itself up when its finished.
2090 * This case should never happen anyway.
2091 *
2092 * Since we're letting it live, we need to finish setting it up.
2093 * We just have to let the caller know that the intended operation
2094 * has failed.
2095 *
2096 * [ This seems strange -- stepping on the vmThread object that's
2097 * already present seems like a bad idea. TODO: figure this out. ]
2098 */
2099 ret = false;
2100 } else
2101 ret = true;
2102 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2103
2104 /* These are now reachable from the thread groups. */
2105 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
2106 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
2107
2108 /*
2109 * The thread is ready to go; let the debugger see it.
2110 */
2111 self->threadObj = threadObj;
2112
2113 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2114 self->threadId, pArgs->name);
2115
2116 /* tell the debugger & DDM */
2117 if (gDvm.debuggerConnected)
2118 dvmDbgPostThreadStart(self);
2119
2120 return ret;
2121
2122fail_unlink:
2123 dvmLockThreadList(self);
2124 unlinkThread(self);
2125 if (!isDaemon)
2126 gDvm.nonDaemonThreadCount--;
2127 dvmUnlockThreadList();
2128 /* fall through to "fail" */
2129fail:
2130 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
2131 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
2132 if (self != NULL) {
2133 if (self->jniEnv != NULL) {
2134 dvmDestroyJNIEnv(self->jniEnv);
2135 self->jniEnv = NULL;
2136 }
2137 freeThread(self);
2138 }
2139 setThreadSelf(NULL);
2140 return false;
2141}
2142
2143/*
2144 * Detach the thread from the various data structures, notify other threads
2145 * that are waiting to "join" it, and free up all heap-allocated storage.
2146 *
2147 * Used for all threads.
2148 *
2149 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2150 * requires us to enforce this for the DetachCurrentThread call, probably
2151 * because it also says that DetachCurrentThread causes all monitors
2152 * associated with the thread to be released. (Because the stack is empty,
2153 * we only have to worry about explicit JNI calls to MonitorEnter.)
2154 *
2155 * THOUGHT:
2156 * We might want to avoid freeing our internal Thread structure until the
2157 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2158 * get to once the thread shuts down, but there is a small possibility of
2159 * an operation starting in another thread before this thread halts, and
2160 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2161 * We don't want something like Thread.isInterrupted() crawling through
2162 * freed storage. Can do with a Thread finalizer, or by creating a
2163 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2164 * state into that.
2165 */
2166void dvmDetachCurrentThread(void)
2167{
2168 Thread* self = dvmThreadSelf();
2169 Object* vmThread;
2170 Object* group;
2171
2172 /*
2173 * Make sure we're not detaching a thread that's still running. (This
2174 * could happen with an explicit JNI detach call.)
2175 *
2176 * A thread created by interpreted code will finish with a depth of
2177 * zero, while a JNI-attached thread will have the synthetic "stack
2178 * starter" native method at the top.
2179 */
2180 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2181 if (curDepth != 0) {
2182 bool topIsNative = false;
2183
2184 if (curDepth == 1) {
2185 /* not expecting a lingering break frame; just look at curFrame */
2186 assert(!dvmIsBreakFrame(self->curFrame));
2187 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2188 if (dvmIsNativeMethod(ssa->method))
2189 topIsNative = true;
2190 }
2191
2192 if (!topIsNative) {
2193 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2194 curDepth);
2195 dvmDumpThread(self, false);
2196 dvmAbort();
2197 }
2198 }
2199
2200 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2201 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2202
2203 /*
2204 * Release any held monitors. Since there are no interpreted stack
2205 * frames, the only thing left are the monitors held by JNI MonitorEnter
2206 * calls.
2207 */
2208 dvmReleaseJniMonitors(self);
2209
2210 /*
2211 * Do some thread-exit uncaught exception processing if necessary.
2212 */
2213 if (dvmCheckException(self))
2214 threadExitUncaughtException(self, group);
2215
2216 /*
2217 * Remove the thread from the thread group.
2218 */
2219 if (group != NULL) {
2220 Method* removeThread =
2221 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2222 JValue unused;
2223 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2224 }
2225
2226 /*
2227 * Clear the vmThread reference in the Thread object. Interpreted code
2228 * will now see that this Thread is not running. As this may be the
2229 * only reference to the VMThread object that the VM knows about, we
2230 * have to create an internal reference to it first.
2231 */
2232 vmThread = dvmGetFieldObject(self->threadObj,
2233 gDvm.offJavaLangThread_vmThread);
2234 dvmAddTrackedAlloc(vmThread, self);
2235 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2236
2237 /* clear out our struct Thread pointer, since it's going away */
2238 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2239
2240 /*
2241 * Tell the debugger & DDM. This may cause the current thread or all
2242 * threads to suspend.
2243 *
2244 * The JDWP spec is somewhat vague about when this happens, other than
2245 * that it's issued by the dying thread, which may still appear in
2246 * an "all threads" listing.
2247 */
2248 if (gDvm.debuggerConnected)
2249 dvmDbgPostThreadDeath(self);
2250
2251 /*
2252 * Thread.join() is implemented as an Object.wait() on the VMThread
2253 * object. Signal anyone who is waiting.
2254 */
2255 dvmLockObject(self, vmThread);
2256 dvmObjectNotifyAll(self, vmThread);
2257 dvmUnlockObject(self, vmThread);
2258
2259 dvmReleaseTrackedAlloc(vmThread, self);
2260 vmThread = NULL;
2261
2262 /*
2263 * We're done manipulating objects, so it's okay if the GC runs in
2264 * parallel with us from here out. It's important to do this if
2265 * profiling is enabled, since we can wait indefinitely.
2266 */
2267 self->status = THREAD_VMWAIT;
2268
2269#ifdef WITH_PROFILER
2270 /*
2271 * If we're doing method trace profiling, we don't want threads to exit,
2272 * because if they do we'll end up reusing thread IDs. This complicates
2273 * analysis and makes it impossible to have reasonable output in the
2274 * "threads" section of the "key" file.
2275 *
2276 * We need to do this after Thread.join() completes, or other threads
2277 * could get wedged. Since self->threadObj is still valid, the Thread
2278 * object will not get GCed even though we're no longer in the ThreadGroup
2279 * list (which is important since the profiling thread needs to get
2280 * the thread's name).
2281 */
2282 MethodTraceState* traceState = &gDvm.methodTrace;
2283
2284 dvmLockMutex(&traceState->startStopLock);
2285 if (traceState->traceEnabled) {
2286 LOGI("threadid=%d: waiting for method trace to finish\n",
2287 self->threadId);
2288 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002289 dvmWaitCond(&traceState->threadExitCond,
2290 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002291 }
2292 }
2293 dvmUnlockMutex(&traceState->startStopLock);
2294#endif
2295
2296 dvmLockThreadList(self);
2297
2298 /*
2299 * Lose the JNI context.
2300 */
2301 dvmDestroyJNIEnv(self->jniEnv);
2302 self->jniEnv = NULL;
2303
2304 self->status = THREAD_ZOMBIE;
2305
2306 /*
2307 * Remove ourselves from the internal thread list.
2308 */
2309 unlinkThread(self);
2310
2311 /*
2312 * If we're the last one standing, signal anybody waiting in
2313 * DestroyJavaVM that it's okay to exit.
2314 */
2315 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2316 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2317
2318 if (gDvm.nonDaemonThreadCount == 0) {
2319 int cc;
2320
2321 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2322 //dvmDumpAllThreads(false);
2323 // cond var guarded by threadListLock, which we already hold
2324 cc = pthread_cond_signal(&gDvm.vmExitCond);
2325 assert(cc == 0);
2326 }
2327 }
2328
2329 LOGV("threadid=%d: bye!\n", self->threadId);
2330 releaseThreadId(self);
2331 dvmUnlockThreadList();
2332
2333 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002334
Bob Lee2fe146a2009-09-10 00:36:29 +02002335 dvmDetachSystemThread(self);
Bob Lee9dc72a32009-09-04 18:28:16 -07002336
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002337 freeThread(self);
2338}
2339
2340
2341/*
2342 * Suspend a single thread. Do not use to suspend yourself.
2343 *
2344 * This is used primarily for debugger/DDMS activity. Does not return
2345 * until the thread has suspended or is in a "safe" state (e.g. executing
2346 * native code outside the VM).
2347 *
2348 * The thread list lock should be held before calling here -- it's not
2349 * entirely safe to hang on to a Thread* from another thread otherwise.
2350 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2351 */
2352void dvmSuspendThread(Thread* thread)
2353{
2354 assert(thread != NULL);
2355 assert(thread != dvmThreadSelf());
2356 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2357
2358 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002359 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002360 thread->dbgSuspendCount++;
2361
2362 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2363 thread->threadId, thread->suspendCount);
2364 unlockThreadSuspendCount();
2365
2366 waitForThreadSuspend(dvmThreadSelf(), thread);
2367}
2368
2369/*
2370 * Reduce the suspend count of a thread. If it hits zero, tell it to
2371 * resume.
2372 *
2373 * Used primarily for debugger/DDMS activity. The thread in question
2374 * might have been suspended singly or as part of a suspend-all operation.
2375 *
2376 * The thread list lock should be held before calling here -- it's not
2377 * entirely safe to hang on to a Thread* from another thread otherwise.
2378 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2379 */
2380void dvmResumeThread(Thread* thread)
2381{
2382 assert(thread != NULL);
2383 assert(thread != dvmThreadSelf());
2384 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2385
2386 lockThreadSuspendCount();
2387 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002388 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002389 thread->dbgSuspendCount--;
2390 } else {
2391 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2392 thread->threadId);
2393 }
2394
2395 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2396 thread->threadId, thread->suspendCount);
2397
2398 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002399 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002400 }
2401
2402 unlockThreadSuspendCount();
2403}
2404
2405/*
2406 * Suspend yourself, as a result of debugger activity.
2407 */
2408void dvmSuspendSelf(bool jdwpActivity)
2409{
2410 Thread* self = dvmThreadSelf();
2411
2412 /* debugger thread may not suspend itself due to debugger activity! */
2413 assert(gDvm.jdwpState != NULL);
2414 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2415 assert(false);
2416 return;
2417 }
2418
2419 /*
2420 * Collisions with other suspends aren't really interesting. We want
2421 * to ensure that we're the only one fiddling with the suspend count
2422 * though.
2423 */
2424 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002425 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002426 self->dbgSuspendCount++;
2427
2428 /*
2429 * Suspend ourselves.
2430 */
2431 assert(self->suspendCount > 0);
2432 self->isSuspended = true;
2433 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2434
2435 /*
2436 * Tell JDWP that we've completed suspension. The JDWP thread can't
2437 * tell us to resume before we're fully asleep because we hold the
2438 * suspend count lock.
2439 *
2440 * If we got here via waitForDebugger(), don't do this part.
2441 */
2442 if (jdwpActivity) {
2443 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2444 // self->threadId, (int) self->handle);
2445 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2446 }
2447
2448 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002449 dvmWaitCond(&gDvm.threadSuspendCountCond,
2450 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002451 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002452 /*
2453 * The condition was signaled but we're still suspended. This
2454 * can happen if the debugger lets go while a SIGQUIT thread
2455 * dump event is pending (assuming SignalCatcher was resumed for
2456 * just long enough to try to grab the thread-suspend lock).
2457 */
2458 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
2459 self->threadId, self->suspendCount, self->dbgSuspendCount,
2460 self->isSuspended ? 'Y' : 'N');
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002461 }
2462 }
2463 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2464 self->isSuspended = false;
2465 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2466 self->threadId, self->status);
2467
2468 unlockThreadSuspendCount();
2469}
2470
2471
2472#ifdef HAVE_GLIBC
2473# define NUM_FRAMES 20
2474# include <execinfo.h>
2475/*
2476 * glibc-only stack dump function. Requires link with "--export-dynamic".
2477 *
2478 * TODO: move this into libs/cutils and make it work for all platforms.
2479 */
2480static void printBackTrace(void)
2481{
2482 void* array[NUM_FRAMES];
2483 size_t size;
2484 char** strings;
2485 size_t i;
2486
2487 size = backtrace(array, NUM_FRAMES);
2488 strings = backtrace_symbols(array, size);
2489
2490 LOGW("Obtained %zd stack frames.\n", size);
2491
2492 for (i = 0; i < size; i++)
2493 LOGW("%s\n", strings[i]);
2494
2495 free(strings);
2496}
2497#else
2498static void printBackTrace(void) {}
2499#endif
2500
2501/*
2502 * Dump the state of the current thread and that of another thread that
2503 * we think is wedged.
2504 */
2505static void dumpWedgedThread(Thread* thread)
2506{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002507 dvmDumpThread(dvmThreadSelf(), false);
2508 printBackTrace();
2509
2510 // dumping a running thread is risky, but could be useful
2511 dvmDumpThread(thread, true);
2512
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002513 // stop now and get a core dump
2514 //abort();
2515}
2516
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002517/*
2518 * If the thread is running at below-normal priority, temporarily elevate
2519 * it to "normal".
2520 *
2521 * Returns zero if no changes were made. Otherwise, returns bit flags
2522 * indicating what was changed, storing the previous values in the
2523 * provided locations.
2524 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002525int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002526 SchedPolicy* pSavedThreadPolicy)
2527{
2528 errno = 0;
2529 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2530 if (errno != 0) {
2531 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2532 thread->threadId, thread->systemTid);
2533 return 0;
2534 }
2535 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2536 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2537 thread->threadId, thread->systemTid);
2538 return 0;
2539 }
2540
2541 int changeFlags = 0;
2542
2543 /*
2544 * Change the priority if we're in the background group.
2545 */
2546 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2547 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2548 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2549 } else {
2550 changeFlags |= kChangedPolicy;
2551 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2552 thread->systemTid, *pSavedThreadPolicy);
2553 }
2554 }
2555
2556 /*
2557 * getpriority() returns the "nice" value, so larger numbers indicate
2558 * lower priority, with 0 being normal.
2559 */
2560 if (*pSavedThreadPrio > 0) {
2561 const int kHigher = 0;
2562 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2563 LOGW("Couldn't raise priority on tid %d to %d\n",
2564 thread->systemTid, kHigher);
2565 } else {
2566 changeFlags |= kChangedPriority;
2567 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2568 thread->systemTid, *pSavedThreadPrio, kHigher);
2569 }
2570 }
2571
2572 return changeFlags;
2573}
2574
2575/*
2576 * Reset the priority values for the thread in question.
2577 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002578void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002579 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2580{
2581 if ((changeFlags & kChangedPolicy) != 0) {
2582 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2583 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2584 thread->systemTid, savedThreadPolicy);
2585 } else {
2586 LOGD("Restored policy of %d to %d\n",
2587 thread->systemTid, savedThreadPolicy);
2588 }
2589 }
2590
2591 if ((changeFlags & kChangedPriority) != 0) {
2592 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2593 {
2594 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2595 thread->systemTid, savedThreadPrio);
2596 } else {
2597 LOGD("Restored priority on %d to %d\n",
2598 thread->systemTid, savedThreadPrio);
2599 }
2600 }
2601}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002602
2603/*
2604 * Wait for another thread to see the pending suspension and stop running.
2605 * It can either suspend itself or go into a non-running state such as
2606 * VMWAIT or NATIVE in which it cannot interact with the GC.
2607 *
2608 * If we're running at a higher priority, sched_yield() may not do anything,
2609 * so we need to sleep for "long enough" to guarantee that the other
2610 * thread has a chance to finish what it's doing. Sleeping for too short
2611 * a period (e.g. less than the resolution of the sleep clock) might cause
2612 * the scheduler to return immediately, so we want to start with a
2613 * "reasonable" value and expand.
2614 *
2615 * This does not return until the other thread has stopped running.
2616 * Eventually we time out and the VM aborts.
2617 *
2618 * This does not try to detect the situation where two threads are
2619 * waiting for each other to suspend. In normal use this is part of a
2620 * suspend-all, which implies that the suspend-all lock is held, or as
2621 * part of a debugger action in which the JDWP thread is always the one
2622 * doing the suspending. (We may need to re-evaluate this now that
2623 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2624 *
2625 * TODO: track basic stats about time required to suspend VM.
2626 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002627#define FIRST_SLEEP (250*1000) /* 0.25s */
2628#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002629static void waitForThreadSuspend(Thread* self, Thread* thread)
2630{
2631 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002632 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002633 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002634 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002635 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002636 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002637
2638 int sleepIter = 0;
2639 int retryCount = 0;
2640 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002641 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002642
2643 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002644 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002645 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002646 if (firstStartWhen == 0) // first iteration of first attempt
2647 firstStartWhen = startWhen;
2648
2649 /*
2650 * After waiting for a bit, check to see if the target thread is
2651 * running at a reduced priority. If so, bump it up temporarily
2652 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002653 */
2654 if (retryCount == 2) {
2655 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002656 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002657 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002658 }
2659 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002660
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002661#if defined (WITH_JIT)
2662 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002663 * If we're still waiting after the first timeout, unchain all
2664 * translations iff:
2665 * 1) There are new chains formed since the last unchain
2666 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002667 */
Ben Cheng6999d842010-01-26 16:46:15 -08002668 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2669 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002670 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002671 dvmJitUnchainAll();
2672 }
2673#endif
2674
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002675 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002676 * Sleep briefly. The iterative sleep call returns false if we've
2677 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002678 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002679 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002680 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002681 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002682 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002683 thread->threadId, priChangeFlags);
2684 if (retryCount > 1) {
2685 /* stack trace logging is slow; skip on first iter */
2686 dumpWedgedThread(thread);
2687 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002688 complained = true;
2689 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002690
2691 // keep going; could be slow due to valgrind
2692 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002693 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002694
2695 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002696 LOGE("Fatal spin-on-suspend, dumping threads\n");
2697 dvmDumpAllThreads(false);
2698
2699 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002700 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2701 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002702
2703 /* try to get a debuggerd dump from the spinning thread */
2704 dvmNukeThread(thread);
2705 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002706 dvmAbort();
2707 }
2708 }
2709 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002710
2711 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002712 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2713 self->threadId,
2714 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002715 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2716 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002717 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002718 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002719 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002720 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002721}
2722
2723/*
2724 * Suspend all threads except the current one. This is used by the GC,
2725 * the debugger, and by any thread that hits a "suspend all threads"
2726 * debugger event (e.g. breakpoint or exception).
2727 *
2728 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2729 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2730 * create objects and even execute arbitrary code. The "why" argument
2731 * allows the caller to say why the suspension is taking place.
2732 *
2733 * This can be called when a global suspend has already happened, due to
2734 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2735 * doesn't work.
2736 *
2737 * DO NOT grab any locks before calling here. We grab & release the thread
2738 * lock and suspend lock here (and we're not using recursive threads), and
2739 * we might have to self-suspend if somebody else beats us here.
2740 *
2741 * The current thread may not be attached to the VM. This can happen if
2742 * we happen to GC as the result of an allocation of a Thread object.
2743 */
2744void dvmSuspendAllThreads(SuspendCause why)
2745{
2746 Thread* self = dvmThreadSelf();
2747 Thread* thread;
2748
2749 assert(why != 0);
2750
2751 /*
2752 * Start by grabbing the thread suspend lock. If we can't get it, most
2753 * likely somebody else is in the process of performing a suspend or
2754 * resume, so lockThreadSuspend() will cause us to self-suspend.
2755 *
2756 * We keep the lock until all other threads are suspended.
2757 */
2758 lockThreadSuspend("susp-all", why);
2759
2760 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2761
2762 /*
2763 * This is possible if the current thread was in VMWAIT mode when a
2764 * suspend-all happened, and then decided to do its own suspend-all.
2765 * This can happen when a couple of threads have simultaneous events
2766 * of interest to the debugger.
2767 */
2768 //assert(self->suspendCount == 0);
2769
2770 /*
2771 * Increment everybody's suspend count (except our own).
2772 */
2773 dvmLockThreadList(self);
2774
2775 lockThreadSuspendCount();
2776 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2777 if (thread == self)
2778 continue;
2779
2780 /* debugger events don't suspend JDWP thread */
2781 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2782 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2783 continue;
2784
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002785 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002786 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2787 thread->dbgSuspendCount++;
2788 }
2789 unlockThreadSuspendCount();
2790
2791 /*
2792 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2793 * indicate the code is either running natively or sleeping quietly.
2794 * Any attempt to transition back to THREAD_RUNNING will cause a check
2795 * for suspension, so it should be impossible for anything to execute
2796 * interpreted code or modify objects (assuming native code plays nicely).
2797 *
2798 * It's also okay if the thread transitions to a non-RUNNING state.
2799 *
2800 * Note we released the threadSuspendCountLock before getting here,
2801 * so if another thread is fiddling with its suspend count (perhaps
2802 * self-suspending for the debugger) it won't block while we're waiting
2803 * in here.
2804 */
2805 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2806 if (thread == self)
2807 continue;
2808
2809 /* debugger events don't suspend JDWP thread */
2810 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2811 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2812 continue;
2813
2814 /* wait for the other thread to see the pending suspend */
2815 waitForThreadSuspend(self, thread);
2816
Jeff Hao97319a82009-08-12 16:57:15 -07002817 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 -08002818 self->threadId,
2819 thread->threadId, thread->status, thread->suspendCount,
2820 thread->dbgSuspendCount, thread->isSuspended);
2821 }
2822
2823 dvmUnlockThreadList();
2824 unlockThreadSuspend();
2825
2826 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2827}
2828
2829/*
2830 * Resume all threads that are currently suspended.
2831 *
2832 * The "why" must match with the previous suspend.
2833 */
2834void dvmResumeAllThreads(SuspendCause why)
2835{
2836 Thread* self = dvmThreadSelf();
2837 Thread* thread;
2838 int cc;
2839
2840 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2841 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2842
2843 /*
2844 * Decrement the suspend counts for all threads. No need for atomic
2845 * writes, since nobody should be moving until we decrement the count.
2846 * We do need to hold the thread list because of JNI attaches.
2847 */
2848 dvmLockThreadList(self);
2849 lockThreadSuspendCount();
2850 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2851 if (thread == self)
2852 continue;
2853
2854 /* debugger events don't suspend JDWP thread */
2855 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2856 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002857 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002858 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002859 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002860
2861 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002862 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002863 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2864 thread->dbgSuspendCount--;
2865 } else {
2866 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2867 thread->threadId);
2868 }
2869 }
2870 unlockThreadSuspendCount();
2871 dvmUnlockThreadList();
2872
2873 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002874 * In some ways it makes sense to continue to hold the thread-suspend
2875 * lock while we issue the wakeup broadcast. It allows us to complete
2876 * one operation before moving on to the next, which simplifies the
2877 * thread activity debug traces.
2878 *
2879 * This approach caused us some difficulty under Linux, because the
2880 * condition variable broadcast not only made the threads runnable,
2881 * but actually caused them to execute, and it was a while before
2882 * the thread performing the wakeup had an opportunity to release the
2883 * thread-suspend lock.
2884 *
2885 * This is a problem because, when a thread tries to acquire that
2886 * lock, it times out after 3 seconds. If at some point the thread
2887 * is told to suspend, the clock resets; but since the VM is still
2888 * theoretically mid-resume, there's no suspend pending. If, for
2889 * example, the GC was waking threads up while the SIGQUIT handler
2890 * was trying to acquire the lock, we would occasionally time out on
2891 * a busy system and SignalCatcher would abort.
2892 *
2893 * We now perform the unlock before the wakeup broadcast. The next
2894 * suspend can't actually start until the broadcast completes and
2895 * returns, because we're holding the thread-suspend-count lock, but the
2896 * suspending thread is now able to make progress and we avoid the abort.
2897 *
2898 * (Technically there is a narrow window between when we release
2899 * the thread-suspend lock and grab the thread-suspend-count lock.
2900 * This could cause us to send a broadcast to threads with nonzero
2901 * suspend counts, but this is expected and they'll all just fall
2902 * right back to sleep. It's probably safe to grab the suspend-count
2903 * lock before releasing thread-suspend, since we're still following
2904 * the correct order of acquisition, but it feels weird.)
2905 */
2906
2907 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2908 unlockThreadSuspend();
2909
2910 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002911 * Broadcast a notification to all suspended threads, some or all of
2912 * which may choose to wake up. No need to wait for them.
2913 */
2914 lockThreadSuspendCount();
2915 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2916 assert(cc == 0);
2917 unlockThreadSuspendCount();
2918
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002919 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2920}
2921
2922/*
2923 * Undo any debugger suspensions. This is called when the debugger
2924 * disconnects.
2925 */
2926void dvmUndoDebuggerSuspensions(void)
2927{
2928 Thread* self = dvmThreadSelf();
2929 Thread* thread;
2930 int cc;
2931
2932 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2933 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2934
2935 /*
2936 * Decrement the suspend counts for all threads. No need for atomic
2937 * writes, since nobody should be moving until we decrement the count.
2938 * We do need to hold the thread list because of JNI attaches.
2939 */
2940 dvmLockThreadList(self);
2941 lockThreadSuspendCount();
2942 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2943 if (thread == self)
2944 continue;
2945
2946 /* debugger events don't suspend JDWP thread */
2947 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2948 assert(thread->dbgSuspendCount == 0);
2949 continue;
2950 }
2951
2952 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002953 dvmAddToThreadSuspendCount(&thread->suspendCount,
2954 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002955 thread->dbgSuspendCount = 0;
2956 }
2957 unlockThreadSuspendCount();
2958 dvmUnlockThreadList();
2959
2960 /*
2961 * Broadcast a notification to all suspended threads, some or all of
2962 * which may choose to wake up. No need to wait for them.
2963 */
2964 lockThreadSuspendCount();
2965 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2966 assert(cc == 0);
2967 unlockThreadSuspendCount();
2968
2969 unlockThreadSuspend();
2970
2971 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2972}
2973
2974/*
2975 * Determine if a thread is suspended.
2976 *
2977 * As with all operations on foreign threads, the caller should hold
2978 * the thread list lock before calling.
2979 */
2980bool dvmIsSuspended(Thread* thread)
2981{
2982 /*
2983 * The thread could be:
2984 * (1) Running happily. status is RUNNING, isSuspended is false,
2985 * suspendCount is zero. Return "false".
2986 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2987 * suspendCount is nonzero. Return "false".
2988 * (3) Suspended. suspendCount is nonzero, and either (status is
2989 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2990 * Return "true".
2991 * (4) Waking up. suspendCount is zero, status is RUNNING and
2992 * isSuspended is true. Return "false" (since it could change
2993 * out from under us, unless we hold suspendCountLock).
2994 */
2995
2996 return (thread->suspendCount != 0 &&
2997 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2998 (thread->status != THREAD_RUNNING)));
2999}
3000
3001/*
3002 * Wait until another thread self-suspends. This is specifically for
3003 * synchronization between the JDWP thread and a thread that has decided
3004 * to suspend itself after sending an event to the debugger.
3005 *
3006 * Threads that encounter "suspend all" events work as well -- the thread
3007 * in question suspends everybody else and then itself.
3008 *
3009 * We can't hold a thread lock here or in the caller, because we could
3010 * get here just before the to-be-waited-for-thread issues a "suspend all".
3011 * There's an opportunity for badness if the thread we're waiting for exits
3012 * and gets cleaned up, but since the thread in question is processing a
3013 * debugger event, that's not really a possibility. (To avoid deadlock,
3014 * it's important that we not be in THREAD_RUNNING while we wait.)
3015 */
3016void dvmWaitForSuspend(Thread* thread)
3017{
3018 Thread* self = dvmThreadSelf();
3019
3020 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3021 self->threadId, thread->threadId);
3022
3023 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3024 assert(thread != self);
3025 assert(self->status != THREAD_RUNNING);
3026
3027 waitForThreadSuspend(self, thread);
3028
3029 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3030 self->threadId, thread->threadId);
3031}
3032
3033/*
3034 * Check to see if we need to suspend ourselves. If so, go to sleep on
3035 * a condition variable.
3036 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003037 * If "newStatus" is not THREAD_UNDEFINED, we change to that state before
3038 * we release the thread suspend count lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003039 *
3040 * Returns "true" if we suspended ourselves.
3041 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003042static bool checkSuspendAndChangeStatus(Thread* self, ThreadStatus newStatus)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003043{
3044 bool didSuspend;
3045
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003046 assert(self != NULL);
3047 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003048
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003049 /* fast path: if count is zero and no state change, bail immediately */
3050 if (self->suspendCount == 0 && newStatus == THREAD_UNDEFINED) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003051 return false;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003052 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003053
3054 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3055
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003056 didSuspend = (self->suspendCount != 0);
3057 self->isSuspended = true;
3058 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
3059 while (self->suspendCount != 0) {
3060 /* wait for wakeup signal; releases lock */
3061 int cc;
3062 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
3063 &gDvm.threadSuspendCountLock);
3064 assert(cc == 0);
3065 }
3066 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
3067 self->isSuspended = false;
3068 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3069 self->threadId, self->status);
3070
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003071 /*
3072 * The status change needs to happen while the suspend count lock is
3073 * held. Otherwise we could switch to RUNNING after another thread
3074 * increases our suspend count, which isn't a "bad" state for us
3075 * (we'll suspend on the next check) but could be a problem for the
3076 * other thread (which thinks we're safely in VMWAIT or NATIVE with
3077 * a nonzero suspend count, and proceeds to initate GC).
3078 */
3079 if (newStatus != THREAD_UNDEFINED)
3080 self->status = newStatus;
3081
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003082 unlockThreadSuspendCount();
3083
3084 return didSuspend;
3085}
3086
3087/*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003088 * One-argument wrapper for checkSuspendAndChangeStatus().
3089 */
3090bool dvmCheckSuspendPending(Thread* self)
3091{
3092 return checkSuspendAndChangeStatus(self, THREAD_UNDEFINED);
3093}
3094
3095/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003096 * Update our status.
3097 *
3098 * The "self" argument, which may be NULL, is accepted as an optimization.
3099 *
3100 * Returns the old status.
3101 */
3102ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3103{
3104 ThreadStatus oldStatus;
3105
3106 if (self == NULL)
3107 self = dvmThreadSelf();
3108
3109 LOGVV("threadid=%d: (status %d -> %d)\n",
3110 self->threadId, self->status, newStatus);
3111
3112 oldStatus = self->status;
3113
3114 if (newStatus == THREAD_RUNNING) {
3115 /*
3116 * Change our status to THREAD_RUNNING. The transition requires
3117 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003118 * us to be "asleep" in all other states, and another thread could
3119 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003120 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003121 * The check for suspension requires holding the thread suspend
3122 * count lock, which the suspend-all code also grabs. We want to
3123 * check our suspension status and change to RUNNING atomically
3124 * to avoid a situation where suspend-all thinks we're safe
3125 * (e.g. VMWAIT or NATIVE with suspendCount=1) but we've actually
3126 * switched to RUNNING and are executing code.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003127 */
3128 assert(self->status != THREAD_RUNNING);
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003129 checkSuspendAndChangeStatus(self, newStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003130 } else {
3131 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003132 * Not changing to THREAD_RUNNING. No additional work required.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003133 */
3134 self->status = newStatus;
3135 }
3136
3137 return oldStatus;
3138}
3139
3140/*
3141 * Get a statically defined thread group from a field in the ThreadGroup
3142 * Class object. Expected arguments are "mMain" and "mSystem".
3143 */
3144static Object* getStaticThreadGroup(const char* fieldName)
3145{
3146 StaticField* groupField;
3147 Object* groupObj;
3148
3149 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3150 fieldName, "Ljava/lang/ThreadGroup;");
3151 if (groupField == NULL) {
3152 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3153 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3154 return NULL;
3155 }
3156 groupObj = dvmGetStaticFieldObject(groupField);
3157 if (groupObj == NULL) {
3158 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3159 dvmThrowException("Ljava/lang/InternalError;", NULL);
3160 return NULL;
3161 }
3162
3163 return groupObj;
3164}
3165Object* dvmGetSystemThreadGroup(void)
3166{
3167 return getStaticThreadGroup("mSystem");
3168}
3169Object* dvmGetMainThreadGroup(void)
3170{
3171 return getStaticThreadGroup("mMain");
3172}
3173
3174/*
3175 * Given a VMThread object, return the associated Thread*.
3176 *
3177 * NOTE: if the thread detaches, the struct Thread will disappear, and
3178 * we will be touching invalid data. For safety, lock the thread list
3179 * before calling this.
3180 */
3181Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3182{
3183 int vmData;
3184
3185 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003186
3187 if (false) {
3188 Thread* thread = gDvm.threadList;
3189 while (thread != NULL) {
3190 if ((Thread*)vmData == thread)
3191 break;
3192
3193 thread = thread->next;
3194 }
3195
3196 if (thread == NULL) {
3197 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3198 vmThreadObj, (Thread*)vmData);
3199 vmData = 0;
3200 }
3201 }
3202
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003203 return (Thread*) vmData;
3204}
3205
Andy McFadden2b94b302010-03-09 16:38:36 -08003206/*
3207 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003208 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003209 *
3210 * Returns NULL if the thread was not found.
3211 */
3212Thread* dvmGetThreadByHandle(pthread_t handle)
3213{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003214 Thread* thread;
3215 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003216 if (thread->handle == handle)
3217 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003218 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003219 return thread;
3220}
Andy McFadden2b94b302010-03-09 16:38:36 -08003221
Andy McFadden0a24ef92010-03-12 13:39:59 -08003222/*
3223 * Given a threadId, return the associated Thread*.
3224 * Caller must hold the thread list lock.
3225 *
3226 * Returns NULL if the thread was not found.
3227 */
3228Thread* dvmGetThreadByThreadId(u4 threadId)
3229{
3230 Thread* thread;
3231 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3232 if (thread->threadId == threadId)
3233 break;
3234 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003235 return thread;
3236}
3237
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003238
3239/*
3240 * Conversion map for "nice" values.
3241 *
3242 * We use Android thread priority constants to be consistent with the rest
3243 * of the system. In some cases adjacent entries may overlap.
3244 */
3245static const int kNiceValues[10] = {
3246 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3247 ANDROID_PRIORITY_BACKGROUND + 6,
3248 ANDROID_PRIORITY_BACKGROUND + 3,
3249 ANDROID_PRIORITY_BACKGROUND,
3250 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3251 ANDROID_PRIORITY_NORMAL - 2,
3252 ANDROID_PRIORITY_NORMAL - 4,
3253 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3254 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3255 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3256};
3257
3258/*
3259 * Change the priority of a system thread to match that of the Thread object.
3260 *
3261 * We map a priority value from 1-10 to Linux "nice" values, where lower
3262 * numbers indicate higher priority.
3263 */
3264void dvmChangeThreadPriority(Thread* thread, int newPriority)
3265{
3266 pid_t pid = thread->systemTid;
3267 int newNice;
3268
3269 if (newPriority < 1 || newPriority > 10) {
3270 LOGW("bad priority %d\n", newPriority);
3271 newPriority = 5;
3272 }
3273 newNice = kNiceValues[newPriority-1];
3274
Andy McFaddend62c0b52009-08-04 15:02:12 -07003275 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003276 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003277 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003278 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003279 }
3280
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003281 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3282 char* str = dvmGetThreadName(thread);
3283 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3284 pid, str, newPriority, newNice, strerror(errno));
3285 free(str);
3286 } else {
3287 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3288 pid, newPriority, newNice);
3289 }
3290}
3291
3292/*
3293 * Get the thread priority for the current thread by querying the system.
3294 * This is useful when attaching a thread through JNI.
3295 *
3296 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3297 */
3298static int getThreadPriorityFromSystem(void)
3299{
3300 int i, sysprio, jprio;
3301
3302 errno = 0;
3303 sysprio = getpriority(PRIO_PROCESS, 0);
3304 if (sysprio == -1 && errno != 0) {
3305 LOGW("getpriority() failed: %s\n", strerror(errno));
3306 return THREAD_NORM_PRIORITY;
3307 }
3308
3309 jprio = THREAD_MIN_PRIORITY;
3310 for (i = 0; i < NELEM(kNiceValues); i++) {
3311 if (sysprio >= kNiceValues[i])
3312 break;
3313 jprio++;
3314 }
3315 if (jprio > THREAD_MAX_PRIORITY)
3316 jprio = THREAD_MAX_PRIORITY;
3317
3318 return jprio;
3319}
3320
3321
3322/*
3323 * Return true if the thread is on gDvm.threadList.
3324 * Caller should not hold gDvm.threadListLock.
3325 */
3326bool dvmIsOnThreadList(const Thread* thread)
3327{
3328 bool ret = false;
3329
3330 dvmLockThreadList(NULL);
3331 if (thread == gDvm.threadList) {
3332 ret = true;
3333 } else {
3334 ret = thread->prev != NULL || thread->next != NULL;
3335 }
3336 dvmUnlockThreadList();
3337
3338 return ret;
3339}
3340
3341/*
3342 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3343 * output target.
3344 */
3345void dvmDumpThread(Thread* thread, bool isRunning)
3346{
3347 DebugOutputTarget target;
3348
3349 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3350 dvmDumpThreadEx(&target, thread, isRunning);
3351}
3352
3353/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003354 * Try to get the scheduler group.
3355 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003356 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003357 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003358 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003359 *
3360 * We return the part after the "/", which will be an empty string for
3361 * the default cgroup. If the string is longer than "bufLen", the string
3362 * will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003363 *
3364 * TODO: this is cloned from a static function in libcutils; expose that?
Andy McFaddend62c0b52009-08-04 15:02:12 -07003365 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003366static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003367{
3368#ifdef HAVE_ANDROID_OS
3369 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003370 char lineBuf[256];
3371 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003372
Andy McFadden7f64ede2010-03-03 15:37:10 -08003373 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
3374 if (!(fp = fopen(pathBuf, "r"))) {
3375 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003376 }
3377
Andy McFadden7f64ede2010-03-03 15:37:10 -08003378 while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
3379 char *next = lineBuf;
3380 char *subsys;
3381 char *grp;
3382 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003383
Andy McFadden7f64ede2010-03-03 15:37:10 -08003384 /* Junk the first field */
3385 if (!strsep(&next, ":")) {
3386 goto out_bad_data;
3387 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003388
Andy McFadden7f64ede2010-03-03 15:37:10 -08003389 if (!(subsys = strsep(&next, ":"))) {
3390 goto out_bad_data;
3391 }
3392
3393 if (strcmp(subsys, "cpu")) {
3394 /* Not the subsys we're looking for */
3395 continue;
3396 }
3397
3398 if (!(grp = strsep(&next, ":"))) {
3399 goto out_bad_data;
3400 }
3401 grp++; /* Drop the leading '/' */
3402 len = strlen(grp);
3403 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3404
3405 if (bufLen <= len) {
3406 len = bufLen - 1;
3407 }
3408 strncpy(buf, grp, len);
3409 buf[len] = '\0';
3410 fclose(fp);
3411 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003412 }
3413
Andy McFadden7f64ede2010-03-03 15:37:10 -08003414 LOGE("Failed to find cpu subsys");
3415 fclose(fp);
3416 return -1;
3417 out_bad_data:
3418 LOGE("Bad cgroup data {%s}", lineBuf);
3419 fclose(fp);
3420 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003421#else
Andy McFadden7f64ede2010-03-03 15:37:10 -08003422 errno = ENOSYS;
3423 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003424#endif
3425}
3426
3427/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003428 * Convert ThreadStatus to a string.
3429 */
3430const char* dvmGetThreadStatusStr(ThreadStatus status)
3431{
3432 switch (status) {
3433 case THREAD_ZOMBIE: return "ZOMBIE";
3434 case THREAD_RUNNING: return "RUNNABLE";
3435 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3436 case THREAD_MONITOR: return "MONITOR";
3437 case THREAD_WAIT: return "WAIT";
3438 case THREAD_INITIALIZING: return "INITIALIZING";
3439 case THREAD_STARTING: return "STARTING";
3440 case THREAD_NATIVE: return "NATIVE";
3441 case THREAD_VMWAIT: return "VMWAIT";
3442 default: return "UNKNOWN";
3443 }
3444}
3445
3446/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003447 * Print information about the specified thread.
3448 *
3449 * Works best when the thread in question is "self" or has been suspended.
3450 * When dumping a separate thread that's still running, set "isRunning" to
3451 * use a more cautious thread dump function.
3452 */
3453void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3454 bool isRunning)
3455{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003456 Object* threadObj;
3457 Object* groupObj;
3458 StringObject* nameStr;
3459 char* threadName = NULL;
3460 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003461 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003462 bool isDaemon;
3463 int priority; // java.lang.Thread priority
3464 int policy; // pthread policy
3465 struct sched_param sp; // pthread scheduling parameters
3466
3467 threadObj = thread->threadObj;
3468 if (threadObj == NULL) {
3469 LOGW("Can't dump thread %d: threadObj not set\n", thread->threadId);
3470 return;
3471 }
3472 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3473 gDvm.offJavaLangThread_name);
3474 threadName = dvmCreateCstrFromString(nameStr);
3475
3476 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3477 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3478
3479 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3480 LOGW("Warning: pthread_getschedparam failed\n");
3481 policy = -1;
3482 sp.sched_priority = -1;
3483 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003484 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
3485 sizeof(schedulerGroupBuf)) != 0)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003486 {
3487 strcpy(schedulerGroupBuf, "unknown");
3488 } else if (schedulerGroupBuf[0] == '\0') {
3489 strcpy(schedulerGroupBuf, "default");
3490 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003491
3492 /* a null value for group is not expected, but deal with it anyway */
3493 groupObj = (Object*) dvmGetFieldObject(threadObj,
3494 gDvm.offJavaLangThread_group);
3495 if (groupObj != NULL) {
3496 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3497 "name", "Ljava/lang/String;");
3498 if (offset < 0) {
3499 LOGW("Unable to find 'name' field in ThreadGroup\n");
3500 } else {
3501 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3502 groupName = dvmCreateCstrFromString(nameStr);
3503 }
3504 }
3505 if (groupName == NULL)
3506 groupName = strdup("(BOGUS GROUP)");
3507
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003508 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003509 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003510 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003511 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3512#if defined(WITH_JIT)
3513 thread->inJitCodeCache ? " JIT" : ""
3514#else
3515 ""
3516#endif
3517 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003518 dvmPrintDebugMessage(target,
Andy McFadden2aa43612009-06-17 16:29:30 -07003519 " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003520 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden2aa43612009-06-17 16:29:30 -07003521 thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003522 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003523 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003524 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003525 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003526
3527#ifdef WITH_MONITOR_TRACKING
3528 if (!isRunning) {
3529 LockedObjectData* lod = thread->pLockedObjects;
3530 if (lod != NULL)
3531 dvmPrintDebugMessage(target, " | monitors held:\n");
3532 else
3533 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3534 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003535 Object* obj = lod->obj;
3536 if (obj->clazz == gDvm.classJavaLangClass) {
3537 ClassObject* clazz = (ClassObject*) obj;
3538 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3539 obj, lod->recursionCount, obj->clazz->descriptor,
3540 clazz->descriptor);
3541 } else {
3542 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3543 obj, lod->recursionCount, obj->clazz->descriptor);
3544 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003545 lod = lod->next;
3546 }
3547 }
3548#endif
3549
3550 if (isRunning)
3551 dvmDumpRunningThreadStack(target, thread);
3552 else
3553 dvmDumpThreadStack(target, thread);
3554
3555 free(threadName);
3556 free(groupName);
3557
3558}
3559
3560/*
3561 * Get the name of a thread.
3562 *
3563 * For correctness, the caller should hold the thread list lock to ensure
3564 * that the thread doesn't go away mid-call.
3565 *
3566 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3567 */
3568char* dvmGetThreadName(Thread* thread)
3569{
3570 StringObject* nameObj;
3571
3572 if (thread->threadObj == NULL) {
3573 LOGW("threadObj is NULL, name not available\n");
3574 return strdup("-unknown-");
3575 }
3576
3577 nameObj = (StringObject*)
3578 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3579 return dvmCreateCstrFromString(nameObj);
3580}
3581
3582/*
3583 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3584 * an output target.
3585 */
3586void dvmDumpAllThreads(bool grabLock)
3587{
3588 DebugOutputTarget target;
3589
3590 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3591 dvmDumpAllThreadsEx(&target, grabLock);
3592}
3593
3594/*
3595 * Print information about all known threads. Assumes they have been
3596 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3597 *
3598 * If "grabLock" is true, we grab the thread lock list. This is important
3599 * to do unless the caller already holds the lock.
3600 */
3601void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3602{
3603 Thread* thread;
3604
3605 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3606
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003607#ifdef HAVE_ANDROID_OS
3608 dvmPrintDebugMessage(target,
3609 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3610 gDvm.threadListLock.value,
3611 gDvm._threadSuspendLock.value,
3612 gDvm.threadSuspendCountLock.value,
3613 gDvm.gcHeapLock.value,
3614 gDvm.heapWorkerLock.value,
3615 gDvm.heapWorkerListLock.value);
3616#endif
3617
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003618 if (grabLock)
3619 dvmLockThreadList(dvmThreadSelf());
3620
3621 thread = gDvm.threadList;
3622 while (thread != NULL) {
3623 dvmDumpThreadEx(target, thread, false);
3624
3625 /* verify link */
3626 assert(thread->next == NULL || thread->next->prev == thread);
3627
3628 thread = thread->next;
3629 }
3630
3631 if (grabLock)
3632 dvmUnlockThreadList();
3633}
3634
Andy McFadden384ef6b2010-03-15 17:24:55 -07003635/*
3636 * Nuke the target thread from orbit.
3637 *
3638 * The idea is to send a "crash" signal to the target thread so that
3639 * debuggerd will take notice and dump an appropriate stack trace.
3640 * Because of the way debuggerd works, we have to throw the same signal
3641 * at it twice.
3642 *
3643 * This does not necessarily cause the entire process to stop, but once a
3644 * thread has been nuked the rest of the system is likely to be unstable.
3645 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003646 * performed, but it's advisable (and expected) to call dvmAbort soon.
3647 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003648 */
3649void dvmNukeThread(Thread* thread)
3650{
Andy McFaddena388a162010-03-18 16:27:14 -07003651 /* suppress the heapworker watchdog to assist anyone using a debugger */
3652 gDvm.nativeDebuggerActive = true;
3653
Andy McFadden384ef6b2010-03-15 17:24:55 -07003654 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003655 * Send the signals, separated by a brief interval to allow debuggerd
3656 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3657 * can be used instead of SIGSEGV to avoid making it look like the
3658 * code actually crashed at the current point of execution.
3659 *
3660 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3661 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3662 * you don't get the second stack trace; possibly something in the
3663 * kernel decides that a signal has already been sent and it's time
3664 * to just kill the process. The position in the current thread is
3665 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003666 *
Andy McFaddena388a162010-03-18 16:27:14 -07003667 * The target thread can continue to execute between the two signals.
3668 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003669 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003670 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3671 " cause debuggerd dump\n",
3672 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
3673 pthread_kill(thread->handle, SIGSTKFLT);
Andy McFaddena388a162010-03-18 16:27:14 -07003674 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddend4e09522010-03-23 12:34:43 -07003675 pthread_kill(thread->handle, SIGSTKFLT);
Andy McFadden7122d862010-03-19 15:18:57 -07003676 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003677 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003678
3679 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3680 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003681 LOGD("Continuing\n");
3682}
3683
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003684#ifdef WITH_MONITOR_TRACKING
3685/*
3686 * Count up the #of locked objects in the current thread.
3687 */
3688static int getThreadObjectCount(const Thread* self)
3689{
3690 LockedObjectData* lod;
3691 int count = 0;
3692
3693 lod = self->pLockedObjects;
3694 while (lod != NULL) {
3695 count++;
3696 lod = lod->next;
3697 }
3698 return count;
3699}
3700
3701/*
3702 * Add the object to the thread's locked object list if it doesn't already
3703 * exist. The most recently added object is the most likely to be released
3704 * next, so we insert at the head of the list.
3705 *
3706 * If it already exists, we increase the recursive lock count.
3707 *
3708 * The object's lock may be thin or fat.
3709 */
3710void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3711{
3712 LockedObjectData* newLod;
3713 LockedObjectData* lod;
3714 int* trace;
3715 int depth;
3716
3717 lod = self->pLockedObjects;
3718 while (lod != NULL) {
3719 if (lod->obj == obj) {
3720 lod->recursionCount++;
3721 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3722 return;
3723 }
3724 lod = lod->next;
3725 }
3726
3727 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3728 if (newLod == NULL) {
3729 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3730 return;
3731 }
3732 newLod->obj = obj;
3733 newLod->recursionCount = 0;
3734
3735 if (withTrace) {
3736 trace = dvmFillInStackTraceRaw(self, &depth);
3737 newLod->rawStackTrace = trace;
3738 newLod->stackDepth = depth;
3739 }
3740
3741 newLod->next = self->pLockedObjects;
3742 self->pLockedObjects = newLod;
3743
3744 LOGV("+++ threadid=%d: added %p, now %d\n",
3745 self->threadId, newLod, getThreadObjectCount(self));
3746}
3747
3748/*
3749 * Remove the object from the thread's locked object list. If the entry
3750 * has a nonzero recursion count, we just decrement the count instead.
3751 */
3752void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3753{
3754 LockedObjectData* lod;
3755 LockedObjectData* prevLod;
3756
3757 lod = self->pLockedObjects;
3758 prevLod = NULL;
3759 while (lod != NULL) {
3760 if (lod->obj == obj) {
3761 if (lod->recursionCount > 0) {
3762 lod->recursionCount--;
3763 LOGV("+++ -recursive lock %p -> %d\n",
3764 obj, lod->recursionCount);
3765 return;
3766 } else {
3767 break;
3768 }
3769 }
3770 prevLod = lod;
3771 lod = lod->next;
3772 }
3773
3774 if (lod == NULL) {
3775 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3776 return;
3777 }
3778 if (prevLod == NULL) {
3779 /* first item in list */
3780 assert(self->pLockedObjects == lod);
3781 self->pLockedObjects = lod->next;
3782 } else {
3783 /* middle/end of list */
3784 prevLod->next = lod->next;
3785 }
3786
3787 LOGV("+++ threadid=%d: removed %p, now %d\n",
3788 self->threadId, lod, getThreadObjectCount(self));
3789 free(lod->rawStackTrace);
3790 free(lod);
3791}
3792
3793/*
3794 * If the specified object is already in the thread's locked object list,
3795 * return the LockedObjectData struct. Otherwise return NULL.
3796 */
3797LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3798{
3799 LockedObjectData* lod;
3800
3801 lod = self->pLockedObjects;
3802 while (lod != NULL) {
3803 if (lod->obj == obj)
3804 return lod;
3805 lod = lod->next;
3806 }
3807 return NULL;
3808}
3809#endif /*WITH_MONITOR_TRACKING*/
3810
3811
3812/*
3813 * GC helper functions
3814 */
3815
The Android Open Source Project99409882009-03-18 22:20:24 -07003816/*
3817 * Add the contents of the registers from the interpreted call stack.
3818 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003819static void gcScanInterpStackReferences(Thread *thread)
3820{
3821 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003822#if WITH_EXTRA_GC_CHECKS > 1
3823 bool first = true;
3824#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003825
3826 framePtr = (const u4 *)thread->curFrame;
3827 while (framePtr != NULL) {
3828 const StackSaveArea *saveArea;
3829 const Method *method;
3830
3831 saveArea = SAVEAREA_FROM_FP(framePtr);
3832 method = saveArea->method;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003833 if (method != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003834#ifdef COUNT_PRECISE_METHODS
3835 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003836 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3837 LOGI("PGC: added %s.%s %p\n",
3838 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003839#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003840#if WITH_EXTRA_GC_CHECKS > 1
3841 /*
3842 * May also want to enable the memset() in the "invokeMethod"
3843 * goto target in the portable interpreter. That sets the stack
3844 * to a pattern that makes referring to uninitialized data
3845 * very obvious.
3846 */
3847
3848 if (first) {
3849 /*
3850 * First frame, isn't native, check the "alternate" saved PC
3851 * as a sanity check.
3852 *
3853 * It seems like we could check the second frame if the first
3854 * is native, since the PCs should be the same. It turns out
3855 * this doesn't always work. The problem is that we could
3856 * have calls in the sequence:
3857 * interp method #2
3858 * native method
3859 * interp method #1
3860 *
3861 * and then GC while in the native method after returning
3862 * from interp method #2. The currentPc on the stack is
3863 * for interp method #1, but thread->currentPc2 is still
3864 * set for the last thing interp method #2 did.
3865 *
3866 * This can also happen in normal execution:
3867 * - sget-object on not-yet-loaded class
3868 * - class init updates currentPc2
3869 * - static field init is handled by parsing annotations;
3870 * static String init requires creation of a String object,
3871 * which can cause a GC
3872 *
3873 * Essentially, any pattern that involves executing
3874 * interpreted code and then causes an allocation without
3875 * executing instructions in the original method will hit
3876 * this. These are rare enough that the test still has
3877 * some value.
3878 */
3879 if (saveArea->xtra.currentPc != thread->currentPc2) {
3880 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3881 saveArea->xtra.currentPc, thread->currentPc2,
3882 method->clazz->descriptor, method->name, method->insns);
3883 if (saveArea->xtra.currentPc != NULL)
3884 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3885 if (thread->currentPc2 != NULL)
3886 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3887 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003888 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003889 } else {
3890 /*
3891 * It's unusual, but not impossible, for a non-first frame
3892 * to be at something other than a method invocation. For
3893 * example, if we do a new-instance on a nonexistent class,
3894 * we'll have a lot of class loader activity on the stack
3895 * above the frame with the "new" operation. Could also
3896 * happen while we initialize a Throwable when an instruction
3897 * fails.
3898 *
3899 * So there's not much we can do here to verify the PC,
3900 * except to verify that it's a GC point.
3901 */
3902 }
3903 assert(saveArea->xtra.currentPc != NULL);
3904#endif
3905
3906 const RegisterMap* pMap;
3907 const u1* regVector;
3908 int i;
3909
Andy McFaddencf8b55c2009-04-13 15:26:03 -07003910 Method* nonConstMethod = (Method*) method; // quiet gcc
3911 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07003912 if (pMap != NULL) {
3913 /* found map, get registers for this address */
3914 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07003915 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07003916 if (regVector == NULL) {
3917 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
3918 method->clazz->descriptor, method->name, addr);
3919 } else {
3920 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
3921 method->clazz->descriptor, method->name, addr,
3922 thread->threadId);
3923 }
3924 } else {
3925 /*
3926 * No map found. If precise GC is disabled this is
3927 * expected -- we don't create pointers to the map data even
3928 * if it's present -- but if it's enabled it means we're
3929 * unexpectedly falling back on a conservative scan, so it's
3930 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07003931 */
3932 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07003933 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07003934 method->clazz->descriptor, method->name);
3935 }
3936 regVector = NULL;
3937 }
3938
3939 if (regVector == NULL) {
3940 /* conservative scan */
3941 for (i = method->registersSize - 1; i >= 0; i--) {
3942 u4 rval = *framePtr++;
3943 if (rval != 0 && (rval & 0x3) == 0) {
3944 dvmMarkIfObject((Object *)rval);
3945 }
3946 }
3947 } else {
3948 /*
3949 * Precise scan. v0 is at the lowest address on the
3950 * interpreted stack, and is the first bit in the register
3951 * vector, so we can walk through the register map and
3952 * memory in the same direction.
3953 *
3954 * A '1' bit indicates a live reference.
3955 */
3956 u2 bits = 1 << 1;
3957 for (i = method->registersSize - 1; i >= 0; i--) {
3958 u4 rval = *framePtr++;
3959
3960 bits >>= 1;
3961 if (bits == 1) {
3962 /* set bit 9 so we can tell when we're empty */
3963 bits = *regVector++ | 0x0100;
3964 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
3965 }
3966
3967 if (rval != 0 && (bits & 0x01) != 0) {
3968 /*
3969 * Non-null, register marked as live reference. This
3970 * should always be a valid object.
3971 */
3972#if WITH_EXTRA_GC_CHECKS > 0
3973 if ((rval & 0x3) != 0 ||
3974 !dvmIsValidObject((Object*) rval))
3975 {
3976 /* this is very bad */
3977 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
3978 method->registersSize-1 - i, rval);
3979 } else
3980#endif
3981 {
3982 dvmMarkObjectNonNull((Object *)rval);
3983 }
3984 } else {
3985 /*
3986 * Null or non-reference, do nothing at all.
3987 */
3988#if WITH_EXTRA_GC_CHECKS > 1
3989 if (dvmIsValidObject((Object*) rval)) {
3990 /* this is normal, but we feel chatty */
3991 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
3992 method->registersSize-1 - i, rval);
3993 }
3994#endif
3995 }
3996 }
3997 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003998 }
3999 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004000
The Android Open Source Project99409882009-03-18 22:20:24 -07004001#if WITH_EXTRA_GC_CHECKS > 1
4002 first = false;
4003#endif
4004
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004005 /* Don't fall into an infinite loop if things get corrupted.
4006 */
4007 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
4008 saveArea->prevFrame == NULL);
4009 framePtr = saveArea->prevFrame;
4010 }
4011}
4012
4013static void gcScanReferenceTable(ReferenceTable *refTable)
4014{
4015 Object **op;
4016
4017 //TODO: these asserts are overkill; turn them off when things stablize.
4018 assert(refTable != NULL);
4019 assert(refTable->table != NULL);
4020 assert(refTable->nextEntry != NULL);
4021 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
4022 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
4023
4024 op = refTable->table;
4025 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
4026 dvmMarkObjectNonNull(*(op++));
4027 }
4028}
4029
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004030#ifdef USE_INDIRECT_REF
Andy McFaddend5ab7262009-08-25 07:19:34 -07004031static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
4032{
4033 Object** op = pRefTable->table;
4034 int numEntries = dvmIndirectRefTableEntries(pRefTable);
4035 int i;
4036
4037 for (i = 0; i < numEntries; i++) {
4038 Object* obj = *op;
4039 if (obj != NULL)
4040 dvmMarkObjectNonNull(obj);
4041 op++;
4042 }
4043}
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004044#endif
Andy McFaddend5ab7262009-08-25 07:19:34 -07004045
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004046/*
4047 * Scan a Thread and mark any objects it references.
4048 */
4049static void gcScanThread(Thread *thread)
4050{
4051 assert(thread != NULL);
4052
4053 /*
4054 * The target thread must be suspended or in a state where it can't do
4055 * any harm (e.g. in Object.wait()). The only exception is the current
4056 * thread, which will still be active and in the "running" state.
4057 *
4058 * (Newly-created threads shouldn't be able to shift themselves to
4059 * RUNNING without a suspend-pending check, so this shouldn't cause
4060 * a false-positive.)
4061 */
Andy McFaddend40223e2009-12-07 15:35:51 -08004062 if (thread->status == THREAD_RUNNING && !thread->isSuspended &&
4063 thread != dvmThreadSelf())
4064 {
4065 Thread* self = dvmThreadSelf();
4066 LOGW("threadid=%d: BUG: GC scanning a running thread (%d)\n",
4067 self->threadId, thread->threadId);
4068 dvmDumpThread(thread, true);
4069 LOGW("Found by:\n");
4070 dvmDumpThread(self, false);
4071
4072 /* continue anyway? */
4073 dvmAbort();
4074 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004075
4076 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
4077
4078 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
4079
4080 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
4081
4082 dvmMarkObject(thread->exception); // usually NULL
4083 gcScanReferenceTable(&thread->internalLocalRefTable);
4084
4085 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
4086
Andy McFaddend5ab7262009-08-25 07:19:34 -07004087#ifdef USE_INDIRECT_REF
4088 gcScanIndirectRefTable(&thread->jniLocalRefTable);
4089#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004090 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07004091#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004092
4093 if (thread->jniMonitorRefTable.table != NULL) {
4094 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
4095
4096 gcScanReferenceTable(&thread->jniMonitorRefTable);
4097 }
4098
4099 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
4100
4101 gcScanInterpStackReferences(thread);
4102
4103 HPROF_CLEAR_GC_SCAN_STATE();
4104}
4105
4106static void gcScanAllThreads()
4107{
4108 Thread *thread;
4109
4110 /* Lock the thread list so we can safely use the
4111 * next/prev pointers.
4112 */
4113 dvmLockThreadList(dvmThreadSelf());
4114
4115 for (thread = gDvm.threadList; thread != NULL;
4116 thread = thread->next)
4117 {
4118 /* We need to scan our own stack, so don't special-case
4119 * the current thread.
4120 */
4121 gcScanThread(thread);
4122 }
4123
4124 dvmUnlockThreadList();
4125}
4126
4127void dvmGcScanRootThreadGroups()
4128{
4129 /* We scan the VM's list of threads instead of going
4130 * through the actual ThreadGroups, but it should be
4131 * equivalent.
4132 *
Jeff Hao97319a82009-08-12 16:57:15 -07004133 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004134 * the root set, which should always be true; it's
4135 * loaded by the built-in class loader, which is part
4136 * of the root set.
4137 */
4138 gcScanAllThreads();
4139}