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