blob: 9011a216ef043cd1e557d963c85d118b7daa56ea [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"
21
22#include "utils/threads.h" // need Android thread priorities
23
24#include <stdlib.h>
25#include <unistd.h>
26#include <sys/time.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070027#include <sys/types.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080028#include <sys/resource.h>
29#include <sys/mman.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070030#include <signal.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080031#include <errno.h>
Andy McFaddend62c0b52009-08-04 15:02:12 -070032#include <fcntl.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080033
34#if defined(HAVE_PRCTL)
35#include <sys/prctl.h>
36#endif
37
Ben Chengfe1be872009-08-21 16:18:46 -070038#if defined(WITH_SELF_VERIFICATION)
39#include "interp/Jit.h" // need for self verification
40#endif
41
42
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080043/* desktop Linux needs a little help with gettid() */
44#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
45#define __KERNEL__
46# include <linux/unistd.h>
47#ifdef _syscall0
48_syscall0(pid_t,gettid)
49#else
50pid_t gettid() { return syscall(__NR_gettid);}
51#endif
52#undef __KERNEL__
53#endif
54
San Mehat256fc152009-04-21 14:03:06 -070055// Change this to enable logging on cgroup errors
56#define ENABLE_CGROUP_ERR_LOGGING 0
57
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080058// change this to LOGV/LOGD to debug thread activity
59#define LOG_THREAD LOGVV
60
61/*
62Notes on Threading
63
64All threads are native pthreads. All threads, except the JDWP debugger
65thread, are visible to code running in the VM and to the debugger. (We
66don't want the debugger to try to manipulate the thread that listens for
67instructions from the debugger.) Internal VM threads are in the "system"
68ThreadGroup, all others are in the "main" ThreadGroup, per convention.
69
70The GC only runs when all threads have been suspended. Threads are
71expected to suspend themselves, using a "safe point" mechanism. We check
72for a suspend request at certain points in the main interpreter loop,
73and on requests coming in from native code (e.g. all JNI functions).
74Certain debugger events may inspire threads to self-suspend.
75
76Native methods must use JNI calls to modify object references to avoid
77clashes with the GC. JNI doesn't provide a way for native code to access
78arrays of objects as such -- code must always get/set individual entries --
79so it should be possible to fully control access through JNI.
80
81Internal native VM threads, such as the finalizer thread, must explicitly
82check for suspension periodically. In most cases they will be sound
83asleep on a condition variable, and won't notice the suspension anyway.
84
85Threads may be suspended by the GC, debugger, or the SIGQUIT listener
86thread. The debugger may suspend or resume individual threads, while the
87GC always suspends all threads. Each thread has a "suspend count" that
88is incremented on suspend requests and decremented on resume requests.
89When the count is zero, the thread is runnable. This allows us to fulfill
90a debugger requirement: if the debugger suspends a thread, the thread is
91not allowed to run again until the debugger resumes it (or disconnects,
92in which case we must resume all debugger-suspended threads).
93
94Paused threads sleep on a condition variable, and are awoken en masse.
95Certain "slow" VM operations, such as starting up a new thread, will be
96done in a separate "VMWAIT" state, so that the rest of the VM doesn't
97freeze up waiting for the operation to finish. Threads must check for
98pending suspension when leaving VMWAIT.
99
100Because threads suspend themselves while interpreting code or when native
101code makes JNI calls, there is no risk of suspending while holding internal
102VM locks. All threads can enter a suspended (or native-code-only) state.
103Also, we don't have to worry about object references existing solely
104in hardware registers.
105
106We do, however, have to worry about objects that were allocated internally
107and aren't yet visible to anything else in the VM. If we allocate an
108object, and then go to sleep on a mutex after changing to a non-RUNNING
109state (e.g. while trying to allocate a second object), the first object
110could be garbage-collected out from under us while we sleep. To manage
111this, we automatically add all allocated objects to an internal object
112tracking list, and only remove them when we know we won't be suspended
113before the object appears in the GC root set.
114
115The debugger may choose to suspend or resume a single thread, which can
116lead to application-level deadlocks; this is expected behavior. The VM
117will only check for suspension of single threads when the debugger is
118active (the java.lang.Thread calls for this are deprecated and hence are
119not supported). Resumption of a single thread is handled by decrementing
120the thread's suspend count and sending a broadcast signal to the condition
121variable. (This will cause all threads to wake up and immediately go back
122to sleep, which isn't tremendously efficient, but neither is having the
123debugger attached.)
124
125The debugger is not allowed to resume threads suspended by the GC. This
126is trivially enforced by ignoring debugger requests while the GC is running
127(the JDWP thread is suspended during GC).
128
129The VM maintains a Thread struct for every pthread known to the VM. There
130is a java/lang/Thread object associated with every Thread. At present,
131there is no safe way to go from a Thread object to a Thread struct except by
132locking and scanning the list; this is necessary because the lifetimes of
133the two are not closely coupled. We may want to change this behavior,
134though at present the only performance impact is on the debugger (see
135threadObjToThread()). See also notes about dvmDetachCurrentThread().
136*/
137/*
138Alternate implementation (signal-based):
139
140Threads run without safe points -- zero overhead. The VM uses a signal
141(e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
142
143The trouble with using signals to suspend threads is that it means a thread
144can be in the middle of an operation when garbage collection starts.
145To prevent some sticky situations, we have to introduce critical sections
146to the VM code.
147
148Critical sections temporarily block suspension for a given thread.
149The thread must move to a non-blocked state (and self-suspend) after
150finishing its current task. If the thread blocks on a resource held
151by a suspended thread, we're hosed.
152
153One approach is to require that no blocking operations, notably
154acquisition of mutexes, can be performed within a critical section.
155This is too limiting. For example, if thread A gets suspended while
156holding the thread list lock, it will prevent the GC or debugger from
157being able to safely access the thread list. We need to wrap the critical
158section around the entire operation (enter critical, get lock, do stuff,
159release lock, exit critical).
160
161A better approach is to declare that certain resources can only be held
162within critical sections. A thread that enters a critical section and
163then gets blocked on the thread list lock knows that the thread it is
164waiting for is also in a critical section, and will release the lock
165before suspending itself. Eventually all threads will complete their
166operations and self-suspend. For this to work, the VM must:
167
168 (1) Determine the set of resources that may be accessed from the GC or
169 debugger threads. The mutexes guarding those go into the "critical
170 resource set" (CRS).
171 (2) Ensure that no resource in the CRS can be acquired outside of a
172 critical section. This can be verified with an assert().
173 (3) Ensure that only resources in the CRS can be held while in a critical
174 section. This is harder to enforce.
175
176If any of these conditions are not met, deadlock can ensue when grabbing
177resources in the GC or debugger (#1) or waiting for threads to suspend
178(#2,#3). (You won't actually deadlock in the GC, because if the semantics
179above are followed you don't need to lock anything in the GC. The risk is
180rather that the GC will access data structures in an intermediate state.)
181
182This approach requires more care and awareness in the VM than
183safe-pointing. Because the GC and debugger are fairly intrusive, there
184really aren't any internal VM resources that aren't shared. Thus, the
185enter/exit critical calls can be added to internal mutex wrappers, which
186makes it easy to get #1 and #2 right.
187
188An ordering should be established for all locks to avoid deadlocks.
189
190Monitor locks, which are also implemented with pthread calls, should not
191cause any problems here. Threads fighting over such locks will not be in
192critical sections and can be suspended freely.
193
194This can get tricky if we ever need exclusive access to VM and non-VM
195resources at the same time. It's not clear if this is a real concern.
196
197There are (at least) two ways to handle the incoming signals:
198
199 (a) Always accept signals. If we're in a critical section, the signal
200 handler just returns without doing anything (the "suspend level"
201 should have been incremented before the signal was sent). Otherwise,
202 if the "suspend level" is nonzero, we go to sleep.
203 (b) Block signals in critical sections. This ensures that we can't be
204 interrupted in a critical section, but requires pthread_sigmask()
205 calls on entry and exit.
206
207This is a choice between blocking the message and blocking the messenger.
208Because UNIX signals are unreliable (you can only know that you have been
209signaled, not whether you were signaled once or 10 times), the choice is
210not significant for correctness. The choice depends on the efficiency
211of pthread_sigmask() and the desire to actually block signals. Either way,
212it is best to ensure that there is only one indication of "blocked";
213having two (i.e. block signals and set a flag, then only send a signal
214if the flag isn't set) can lead to race conditions.
215
216The signal handler must take care to copy registers onto the stack (via
217setjmp), so that stack scans find all references. Because we have to scan
218native stacks, "exact" GC is not possible with this approach.
219
220Some other concerns with flinging signals around:
221 - Odd interactions with some debuggers (e.g. gdb on the Mac)
222 - Restrictions on some standard library calls during GC (e.g. don't
223 use printf on stdout to print GC debug messages)
224*/
225
Carl Shapiro59a93122010-01-26 17:12:51 -0800226#define kMaxThreadId ((1 << 16) - 1)
227#define kMainThreadId 1
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800228
229
230static Thread* allocThread(int interpStackSize);
231static bool prepareThread(Thread* thread);
232static void setThreadSelf(Thread* thread);
233static void unlinkThread(Thread* thread);
234static void freeThread(Thread* thread);
235static void assignThreadId(Thread* thread);
236static bool createFakeEntryFrame(Thread* thread);
237static bool createFakeRunFrame(Thread* thread);
238static void* interpThreadStart(void* arg);
239static void* internalThreadStart(void* arg);
240static void threadExitUncaughtException(Thread* thread, Object* group);
241static void threadExitCheck(void* arg);
242static void waitForThreadSuspend(Thread* self, Thread* thread);
243static int getThreadPriorityFromSystem(void);
244
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700245/*
246 * The JIT needs to know if any thread is suspended. We do this by
247 * maintaining a global sum of all threads' suspend counts. All suspendCount
248 * updates should go through this after aquiring threadSuspendCountLock.
249 */
250static inline void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
251{
252 *pSuspendCount += delta;
253 gDvm.sumThreadSuspendCount += delta;
254}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800255
256/*
257 * Initialize thread list and main thread's environment. We need to set
258 * up some basic stuff so that dvmThreadSelf() will work when we start
259 * loading classes (e.g. to check for exceptions).
260 */
261bool dvmThreadStartup(void)
262{
263 Thread* thread;
264
265 /* allocate a TLS slot */
266 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
267 LOGE("ERROR: pthread_key_create failed\n");
268 return false;
269 }
270
271 /* test our pthread lib */
272 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
273 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
274
275 /* prep thread-related locks and conditions */
276 dvmInitMutex(&gDvm.threadListLock);
277 pthread_cond_init(&gDvm.threadStartCond, NULL);
278 //dvmInitMutex(&gDvm.vmExitLock);
279 pthread_cond_init(&gDvm.vmExitCond, NULL);
280 dvmInitMutex(&gDvm._threadSuspendLock);
281 dvmInitMutex(&gDvm.threadSuspendCountLock);
282 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
283#ifdef WITH_DEADLOCK_PREDICTION
284 dvmInitMutex(&gDvm.deadlockHistoryLock);
285#endif
286
287 /*
288 * Dedicated monitor for Thread.sleep().
289 * TODO: change this to an Object* so we don't have to expose this
290 * call, and we interact better with JDWP monitor calls. Requires
291 * deferring the object creation to much later (e.g. final "main"
292 * thread prep) or until first use.
293 */
294 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
295
296 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
297
298 thread = allocThread(gDvm.stackSize);
299 if (thread == NULL)
300 return false;
301
302 /* switch mode for when we run initializers */
303 thread->status = THREAD_RUNNING;
304
305 /*
306 * We need to assign the threadId early so we can lock/notify
307 * object monitors. We'll set the "threadObj" field later.
308 */
309 prepareThread(thread);
310 gDvm.threadList = thread;
311
312#ifdef COUNT_PRECISE_METHODS
313 gDvm.preciseMethods = dvmPointerSetAlloc(200);
314#endif
315
316 return true;
317}
318
319/*
320 * We're a little farther up now, and can load some basic classes.
321 *
322 * We're far enough along that we can poke at java.lang.Thread and friends,
323 * but should not assume that static initializers have run (or cause them
324 * to do so). That means no object allocations yet.
325 */
326bool dvmThreadObjStartup(void)
327{
328 /*
329 * Cache the locations of these classes. It's likely that we're the
330 * first to reference them, so they're being loaded now.
331 */
332 gDvm.classJavaLangThread =
333 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
334 gDvm.classJavaLangVMThread =
335 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
336 gDvm.classJavaLangThreadGroup =
337 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
338 if (gDvm.classJavaLangThread == NULL ||
339 gDvm.classJavaLangThreadGroup == NULL ||
340 gDvm.classJavaLangThreadGroup == NULL)
341 {
342 LOGE("Could not find one or more essential thread classes\n");
343 return false;
344 }
345
346 /*
347 * Cache field offsets. This makes things a little faster, at the
348 * expense of hard-coding non-public field names into the VM.
349 */
350 gDvm.offJavaLangThread_vmThread =
351 dvmFindFieldOffset(gDvm.classJavaLangThread,
352 "vmThread", "Ljava/lang/VMThread;");
353 gDvm.offJavaLangThread_group =
354 dvmFindFieldOffset(gDvm.classJavaLangThread,
355 "group", "Ljava/lang/ThreadGroup;");
356 gDvm.offJavaLangThread_daemon =
357 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
358 gDvm.offJavaLangThread_name =
359 dvmFindFieldOffset(gDvm.classJavaLangThread,
360 "name", "Ljava/lang/String;");
361 gDvm.offJavaLangThread_priority =
362 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
363
364 if (gDvm.offJavaLangThread_vmThread < 0 ||
365 gDvm.offJavaLangThread_group < 0 ||
366 gDvm.offJavaLangThread_daemon < 0 ||
367 gDvm.offJavaLangThread_name < 0 ||
368 gDvm.offJavaLangThread_priority < 0)
369 {
370 LOGE("Unable to find all fields in java.lang.Thread\n");
371 return false;
372 }
373
374 gDvm.offJavaLangVMThread_thread =
375 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
376 "thread", "Ljava/lang/Thread;");
377 gDvm.offJavaLangVMThread_vmData =
378 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
379 if (gDvm.offJavaLangVMThread_thread < 0 ||
380 gDvm.offJavaLangVMThread_vmData < 0)
381 {
382 LOGE("Unable to find all fields in java.lang.VMThread\n");
383 return false;
384 }
385
386 /*
387 * Cache the vtable offset for "run()".
388 *
389 * We don't want to keep the Method* because then we won't find see
390 * methods defined in subclasses.
391 */
392 Method* meth;
393 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
394 if (meth == NULL) {
395 LOGE("Unable to find run() in java.lang.Thread\n");
396 return false;
397 }
398 gDvm.voffJavaLangThread_run = meth->methodIndex;
399
400 /*
401 * Cache vtable offsets for ThreadGroup methods.
402 */
403 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
404 "removeThread", "(Ljava/lang/Thread;)V");
405 if (meth == NULL) {
406 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
407 return false;
408 }
409 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
410
411 return true;
412}
413
414/*
415 * All threads should be stopped by now. Clean up some thread globals.
416 */
417void dvmThreadShutdown(void)
418{
419 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700420 /*
421 * If we walk through the thread list and try to free the
422 * lingering thread structures (which should only be for daemon
423 * threads), the daemon threads may crash if they execute before
424 * the process dies. Let them leak.
425 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800426 freeThread(gDvm.threadList);
427 gDvm.threadList = NULL;
428 }
429
430 dvmFreeBitVector(gDvm.threadIdMap);
431
432 dvmFreeMonitorList();
433
434 pthread_key_delete(gDvm.pthreadKeySelf);
435}
436
437
438/*
439 * Grab the suspend count global lock.
440 */
441static inline void lockThreadSuspendCount(void)
442{
443 /*
444 * Don't try to change to VMWAIT here. When we change back to RUNNING
445 * we have to check for a pending suspend, which results in grabbing
446 * this lock recursively. Doesn't work with "fast" pthread mutexes.
447 *
448 * This lock is always held for very brief periods, so as long as
449 * mutex ordering is respected we shouldn't stall.
450 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700451 dvmLockMutex(&gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800452}
453
454/*
455 * Release the suspend count global lock.
456 */
457static inline void unlockThreadSuspendCount(void)
458{
459 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
460}
461
462/*
463 * Grab the thread list global lock.
464 *
465 * This is held while "suspend all" is trying to make everybody stop. If
466 * the shutdown is in progress, and somebody tries to grab the lock, they'll
467 * have to wait for the GC to finish. Therefore it's important that the
468 * thread not be in RUNNING mode.
469 *
470 * We don't have to check to see if we should be suspended once we have
471 * the lock. Nobody can suspend all threads without holding the thread list
472 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700473 *
Andy McFadden3469a7e2010-08-04 16:09:10 -0700474 * This function deliberately avoids the use of dvmChangeStatus(),
475 * which could grab threadSuspendCountLock. To avoid deadlock, threads
476 * are required to grab the thread list lock before the thread suspend
477 * count lock. (See comment in DvmGlobals.)
478 *
Andy McFadden44860362009-08-06 17:56:14 -0700479 * TODO: consider checking for suspend after acquiring the lock, and
480 * backing off if set. As stated above, it can't happen during normal
481 * execution, but it *can* happen during shutdown when daemon threads
482 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800483 */
484void dvmLockThreadList(Thread* self)
485{
486 ThreadStatus oldStatus;
487
488 if (self == NULL) /* try to get it from TLS */
489 self = dvmThreadSelf();
490
491 if (self != NULL) {
492 oldStatus = self->status;
493 self->status = THREAD_VMWAIT;
494 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700495 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800496 //LOGW("NULL self in dvmLockThreadList\n");
497 oldStatus = -1; // shut up gcc
498 }
499
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700500 dvmLockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800501
502 if (self != NULL)
503 self->status = oldStatus;
504}
505
506/*
507 * Release the thread list global lock.
508 */
509void dvmUnlockThreadList(void)
510{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700511 dvmUnlockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800512}
513
The Android Open Source Project99409882009-03-18 22:20:24 -0700514/*
515 * Convert SuspendCause to a string.
516 */
517static const char* getSuspendCauseStr(SuspendCause why)
518{
519 switch (why) {
520 case SUSPEND_NOT: return "NOT?";
521 case SUSPEND_FOR_GC: return "gc";
522 case SUSPEND_FOR_DEBUG: return "debug";
523 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
524 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700525 case SUSPEND_FOR_VERIFY: return "verify";
Ben Chenga8e64a72009-10-20 13:01:36 -0700526#if defined(WITH_JIT)
527 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
528 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800529 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800530 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700531#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700532 default: return "UNKNOWN";
533 }
534}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800535
536/*
537 * Grab the "thread suspend" lock. This is required to prevent the
538 * GC and the debugger from simultaneously suspending all threads.
539 *
540 * If we fail to get the lock, somebody else is trying to suspend all
541 * threads -- including us. If we go to sleep on the lock we'll deadlock
542 * the VM. Loop until we get it or somebody puts us to sleep.
543 */
544static void lockThreadSuspend(const char* who, SuspendCause why)
545{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546 const int kSpinSleepTime = 3*1000*1000; /* 3s */
547 u8 startWhen = 0; // init req'd to placate gcc
548 int sleepIter = 0;
549 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700550
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800551 do {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700552 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800553 if (cc != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700554 Thread* self = dvmThreadSelf();
555
556 if (!dvmCheckSuspendPending(self)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800557 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700558 * Could be that a resume-all is in progress, and something
559 * grabbed the CPU when the wakeup was broadcast. The thread
560 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700561 * thread suspend lock. (We release before the broadcast,
562 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700563 *
564 * Could be we hit the window as a suspend was started,
565 * and the lock has been grabbed but the suspend counts
566 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700567 *
568 * Could be an unusual JNI thread-attach thing.
569 *
570 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800571 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700572 *
573 * Could be two app threads both want to patch predicted
574 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800575 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700576 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
577 " it's held, no suspend pending\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700578 self->threadId, who, getSuspendCauseStr(why));
The Android Open Source Project99409882009-03-18 22:20:24 -0700579 } else {
580 /* we suspended; reset timeout */
581 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800582 }
583
584 /* give the lock-holder a chance to do some work */
585 if (sleepIter == 0)
586 startWhen = dvmGetRelativeTimeUsec();
587 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700588 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800589 " bailing\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700590 self->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700591 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800592 dvmDumpAllThreads(false);
593 dvmAbort();
594 }
595 }
596 } while (cc != 0);
597 assert(cc == 0);
598}
599
600/*
601 * Release the "thread suspend" lock.
602 */
603static inline void unlockThreadSuspend(void)
604{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700605 dvmUnlockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800606}
607
608
609/*
610 * Kill any daemon threads that still exist. All of ours should be
611 * stopped, so these should be Thread objects or JNI-attached threads
612 * started by the application. Actively-running threads are likely
613 * to crash the process if they continue to execute while the VM
614 * shuts down, so we really need to kill or suspend them. (If we want
615 * the VM to restart within this process, we need to kill them, but that
616 * leaves open the possibility of orphaned resources.)
617 *
618 * Waiting for the thread to suspend may be unwise at this point, but
619 * if one of these is wedged in a critical section then we probably
620 * would've locked up on the last GC attempt.
621 *
622 * It's possible for this function to get called after a failed
623 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700624 *
625 * This will be called from whatever thread calls DestroyJavaVM, usually
626 * but not necessarily the main thread. It's likely, but not guaranteed,
627 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800628 */
629void dvmSlayDaemons(void)
630{
Andy McFadden44860362009-08-06 17:56:14 -0700631 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800632 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700633 int threadId = 0;
634 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800635
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800636 dvmLockThreadList(self);
637
Andy McFadden44860362009-08-06 17:56:14 -0700638 if (self != NULL)
639 threadId = self->threadId;
640
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800641 target = gDvm.threadList;
642 while (target != NULL) {
643 if (target == self) {
644 target = target->next;
645 continue;
646 }
647
648 if (!dvmGetFieldBoolean(target->threadObj,
649 gDvm.offJavaLangThread_daemon))
650 {
Andy McFadden44860362009-08-06 17:56:14 -0700651 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800652 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700653 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800654 }
655
Andy McFadden44860362009-08-06 17:56:14 -0700656 char* threadName = dvmGetThreadName(target);
657 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
658 threadId, target->threadId, threadName);
659 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800660
Andy McFadden44860362009-08-06 17:56:14 -0700661 /* mark as suspended */
662 lockThreadSuspendCount();
663 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
664 unlockThreadSuspendCount();
665 doWait = true;
666
667 target = target->next;
668 }
669
670 //dvmDumpAllThreads(false);
671
672 /*
673 * Unlock the thread list, relocking it later if necessary. It's
674 * possible a thread is in VMWAIT after calling dvmLockThreadList,
675 * and that function *doesn't* check for pending suspend after
676 * acquiring the lock. We want to let them finish their business
677 * and see the pending suspend before we continue here.
678 *
679 * There's no guarantee of mutex fairness, so this might not work.
680 * (The alternative is to have dvmLockThreadList check for suspend
681 * after acquiring the lock and back off, something we should consider.)
682 */
683 dvmUnlockThreadList();
684
685 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800686 bool complained = false;
687
Andy McFadden44860362009-08-06 17:56:14 -0700688 usleep(200 * 1000);
689
690 dvmLockThreadList(self);
691
692 /*
693 * Sleep for a bit until the threads have suspended. We're trying
694 * to exit, so don't wait for too long.
695 */
696 int i;
697 for (i = 0; i < 10; i++) {
698 bool allSuspended = true;
699
700 target = gDvm.threadList;
701 while (target != NULL) {
702 if (target == self) {
703 target = target->next;
704 continue;
705 }
706
Andy McFadden6dce9962010-08-23 16:45:24 -0700707 if (target->status == THREAD_RUNNING) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800708 if (!complained)
709 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700710 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800711 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700712 }
713
714 target = target->next;
715 }
716
717 if (allSuspended) {
718 LOGD("threadid=%d: all daemons have suspended\n", threadId);
719 break;
720 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800721 if (!complained) {
722 complained = true;
723 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
724 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800725 }
Andy McFadden44860362009-08-06 17:56:14 -0700726 }
727
728 usleep(200 * 1000);
729 }
730 dvmUnlockThreadList();
731 }
732
733#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
734 /*
735 * Abandon the threads and recover their resources.
736 */
737 target = gDvm.threadList;
738 while (target != NULL) {
739 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800740 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800741 freeThread(target);
742 target = nextTarget;
743 }
Andy McFadden44860362009-08-06 17:56:14 -0700744#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800745
Andy McFadden44860362009-08-06 17:56:14 -0700746 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800747}
748
749
750/*
751 * Finish preparing the parts of the Thread struct required to support
752 * JNI registration.
753 */
754bool dvmPrepMainForJni(JNIEnv* pEnv)
755{
756 Thread* self;
757
758 /* main thread is always first in list at this point */
759 self = gDvm.threadList;
760 assert(self->threadId == kMainThreadId);
761
762 /* create a "fake" JNI frame at the top of the main thread interp stack */
763 if (!createFakeEntryFrame(self))
764 return false;
765
766 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
767 dvmSetJniEnvThreadId(pEnv, self);
768 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
769
770 return true;
771}
772
773
774/*
775 * Finish preparing the main thread, allocating some objects to represent
776 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700777 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800778 */
779bool dvmPrepMainThread(void)
780{
781 Thread* thread;
782 Object* groupObj;
783 Object* threadObj;
784 Object* vmThreadObj;
785 StringObject* threadNameStr;
786 Method* init;
787 JValue unused;
788
789 LOGV("+++ finishing prep on main VM thread\n");
790
791 /* main thread is always first in list at this point */
792 thread = gDvm.threadList;
793 assert(thread->threadId == kMainThreadId);
794
795 /*
796 * Make sure the classes are initialized. We have to do this before
797 * we create an instance of them.
798 */
799 if (!dvmInitClass(gDvm.classJavaLangClass)) {
800 LOGE("'Class' class failed to initialize\n");
801 return false;
802 }
803 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
804 !dvmInitClass(gDvm.classJavaLangThread) ||
805 !dvmInitClass(gDvm.classJavaLangVMThread))
806 {
807 LOGE("thread classes failed to initialize\n");
808 return false;
809 }
810
811 groupObj = dvmGetMainThreadGroup();
812 if (groupObj == NULL)
813 return false;
814
815 /*
816 * Allocate and construct a Thread with the internal-creation
817 * constructor.
818 */
819 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
820 if (threadObj == NULL) {
821 LOGE("unable to allocate main thread object\n");
822 return false;
823 }
824 dvmReleaseTrackedAlloc(threadObj, NULL);
825
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700826 threadNameStr = dvmCreateStringFromCstr("main");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800827 if (threadNameStr == NULL)
828 return false;
829 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
830
831 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
832 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
833 assert(init != NULL);
834 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
835 THREAD_NORM_PRIORITY, false);
836 if (dvmCheckException(thread)) {
837 LOGE("exception thrown while constructing main thread object\n");
838 return false;
839 }
840
841 /*
842 * Allocate and construct a VMThread.
843 */
844 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
845 if (vmThreadObj == NULL) {
846 LOGE("unable to allocate main vmthread object\n");
847 return false;
848 }
849 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
850
851 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
852 "(Ljava/lang/Thread;)V");
853 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
854 if (dvmCheckException(thread)) {
855 LOGE("exception thrown while constructing main vmthread object\n");
856 return false;
857 }
858
859 /* set the VMThread.vmData field to our Thread struct */
860 assert(gDvm.offJavaLangVMThread_vmData != 0);
861 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
862
863 /*
864 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700865 * Threads will see that this Thread is running (at least, they would,
866 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800867 */
868 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
869 vmThreadObj);
870
871 thread->threadObj = threadObj;
872
873 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700874 * Set the context class loader. This invokes a ClassLoader method,
875 * which could conceivably call Thread.currentThread(), so we want the
876 * Thread to be fully configured before we do this.
877 */
878 Object* systemLoader = dvmGetSystemClassLoader();
879 if (systemLoader == NULL) {
880 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
881 /* keep going */
882 }
883 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
884 "contextClassLoader", "Ljava/lang/ClassLoader;");
885 if (ctxtClassLoaderOffset < 0) {
886 LOGE("Unable to find contextClassLoader field in Thread\n");
887 return false;
888 }
889 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
Andy McFadden50cab512010-10-07 15:11:43 -0700890 dvmReleaseTrackedAlloc(systemLoader, NULL);
Andy McFaddena1a7a342009-05-04 13:29:30 -0700891
892 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800893 * Finish our thread prep.
894 */
895
896 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
897 gDvm.nonDaemonThreadCount++;
898
899 return true;
900}
901
902
903/*
904 * Alloc and initialize a Thread struct.
905 *
Andy McFaddene3346d82010-06-02 15:37:21 -0700906 * Does not create any objects, just stuff on the system (malloc) heap.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800907 */
908static Thread* allocThread(int interpStackSize)
909{
910 Thread* thread;
911 u1* stackBottom;
912
913 thread = (Thread*) calloc(1, sizeof(Thread));
914 if (thread == NULL)
915 return NULL;
916
Jeff Hao97319a82009-08-12 16:57:15 -0700917#if defined(WITH_SELF_VERIFICATION)
918 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
919 return NULL;
920#endif
921
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800922 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
923
924 thread->status = THREAD_INITIALIZING;
925 thread->suspendCount = 0;
926
927#ifdef WITH_ALLOC_LIMITS
928 thread->allocLimit = -1;
929#endif
930
931 /*
932 * Allocate and initialize the interpreted code stack. We essentially
933 * "lose" the alloc pointer, which points at the bottom of the stack,
934 * but we can get it back later because we know how big the stack is.
935 *
936 * The stack must be aligned on a 4-byte boundary.
937 */
938#ifdef MALLOC_INTERP_STACK
939 stackBottom = (u1*) malloc(interpStackSize);
940 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700941#if defined(WITH_SELF_VERIFICATION)
942 dvmSelfVerificationShadowSpaceFree(thread);
943#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800944 free(thread);
945 return NULL;
946 }
947 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
948#else
949 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
950 MAP_PRIVATE | MAP_ANON, -1, 0);
951 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700952#if defined(WITH_SELF_VERIFICATION)
953 dvmSelfVerificationShadowSpaceFree(thread);
954#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800955 free(thread);
956 return NULL;
957 }
958#endif
959
960 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
961 thread->interpStackSize = interpStackSize;
962 thread->interpStackStart = stackBottom + interpStackSize;
963 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
964
965 /* give the thread code a chance to set things up */
966 dvmInitInterpStack(thread, interpStackSize);
967
968 return thread;
969}
970
971/*
972 * Get a meaningful thread ID. At present this only has meaning under Linux,
973 * where getpid() and gettid() sometimes agree and sometimes don't depending
974 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
975 */
976pid_t dvmGetSysThreadId(void)
977{
978#ifdef HAVE_GETTID
979 return gettid();
980#else
981 return getpid();
982#endif
983}
984
985/*
986 * Finish initialization of a Thread struct.
987 *
988 * This must be called while executing in the new thread, but before the
989 * thread is added to the thread list.
990 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700991 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800992 * assignThreadId()).
993 */
994static bool prepareThread(Thread* thread)
995{
996 assignThreadId(thread);
997 thread->handle = pthread_self();
998 thread->systemTid = dvmGetSysThreadId();
999
1000 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1001 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001002 /*
1003 * If we were called by dvmAttachCurrentThread, the self value is
1004 * already correctly established as "thread".
1005 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001006 setThreadSelf(thread);
1007
1008 LOGV("threadid=%d: interp stack at %p\n",
1009 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1010
1011 /*
1012 * Initialize invokeReq.
1013 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001014 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001015 pthread_cond_init(&thread->invokeReq.cv, NULL);
1016
1017 /*
1018 * Initialize our reference tracking tables.
1019 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001020 * Most threads won't use jniMonitorRefTable, so we clear out the
1021 * structure but don't call the init function (which allocs storage).
1022 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001023#ifdef USE_INDIRECT_REF
1024 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1025 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1026 return false;
1027#else
1028 /*
1029 * The JNI local ref table *must* be fixed-size because we keep pointers
1030 * into the table in our stack frames.
1031 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001032 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1033 kJniLocalRefMax, kJniLocalRefMax))
1034 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001035#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001036 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1037 kInternalRefDefault, kInternalRefMax))
1038 return false;
1039
1040 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1041
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001042 pthread_cond_init(&thread->waitCond, NULL);
1043 dvmInitMutex(&thread->waitMutex);
1044
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001045 return true;
1046}
1047
1048/*
1049 * Remove a thread from the internal list.
1050 * Clear out the links to make it obvious that the thread is
1051 * no longer on the list. Caller must hold gDvm.threadListLock.
1052 */
1053static void unlinkThread(Thread* thread)
1054{
1055 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1056 if (thread == gDvm.threadList) {
1057 assert(thread->prev == NULL);
1058 gDvm.threadList = thread->next;
1059 } else {
1060 assert(thread->prev != NULL);
1061 thread->prev->next = thread->next;
1062 }
1063 if (thread->next != NULL)
1064 thread->next->prev = thread->prev;
1065 thread->prev = thread->next = NULL;
1066}
1067
1068/*
1069 * Free a Thread struct, and all the stuff allocated within.
1070 */
1071static void freeThread(Thread* thread)
1072{
1073 if (thread == NULL)
1074 return;
1075
1076 /* thread->threadId is zero at this point */
1077 LOGVV("threadid=%d: freeing\n", thread->threadId);
1078
1079 if (thread->interpStackStart != NULL) {
1080 u1* interpStackBottom;
1081
1082 interpStackBottom = thread->interpStackStart;
1083 interpStackBottom -= thread->interpStackSize;
1084#ifdef MALLOC_INTERP_STACK
1085 free(interpStackBottom);
1086#else
1087 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1088 LOGW("munmap(thread stack) failed\n");
1089#endif
1090 }
1091
Andy McFaddend5ab7262009-08-25 07:19:34 -07001092#ifdef USE_INDIRECT_REF
1093 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1094#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001095 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001096#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001097 dvmClearReferenceTable(&thread->internalLocalRefTable);
1098 if (&thread->jniMonitorRefTable.table != NULL)
1099 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1100
Jeff Hao97319a82009-08-12 16:57:15 -07001101#if defined(WITH_SELF_VERIFICATION)
1102 dvmSelfVerificationShadowSpaceFree(thread);
1103#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001104 free(thread);
1105}
1106
1107/*
1108 * Like pthread_self(), but on a Thread*.
1109 */
1110Thread* dvmThreadSelf(void)
1111{
1112 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1113}
1114
1115/*
1116 * Explore our sense of self. Stuffs the thread pointer into TLS.
1117 */
1118static void setThreadSelf(Thread* thread)
1119{
1120 int cc;
1121
1122 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1123 if (cc != 0) {
1124 /*
1125 * Sometimes this fails under Bionic with EINVAL during shutdown.
1126 * This can happen if the timing is just right, e.g. a thread
1127 * fails to attach during shutdown, but the "fail" path calls
1128 * here to ensure we clean up after ourselves.
1129 */
1130 if (thread != NULL) {
1131 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1132 dvmAbort(); /* the world is fundamentally hosed */
1133 }
1134 }
1135}
1136
1137/*
1138 * This is associated with the pthreadKeySelf key. It's called by the
1139 * pthread library when a thread is exiting and the "self" pointer in TLS
1140 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001141 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001142 *
1143 * This is mainly of use to ensure that we don't leak resources if, for
1144 * example, a thread attaches itself to us with AttachCurrentThread and
1145 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001146 *
1147 * We could do the detach here instead of aborting, but this will lead to
1148 * portability problems. Other implementations do not do this check and
1149 * will simply be unaware that the thread has exited, leading to resource
1150 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1151 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001152 *
1153 * Because some implementations may want to use the pthread destructor
1154 * to initiate the detach, and the ordering of destructors is not defined,
1155 * 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 -08001156 */
1157static void threadExitCheck(void* arg)
1158{
Andy McFadden909ce242009-12-10 16:38:30 -08001159 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001160
Andy McFadden909ce242009-12-10 16:38:30 -08001161 Thread* self = (Thread*) arg;
1162 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001163
Andy McFadden909ce242009-12-10 16:38:30 -08001164 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1165 self->threadId, arg, self->threadExitCheckCount);
1166
1167 if (self->status == THREAD_ZOMBIE) {
1168 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1169 self->threadId);
1170 return;
1171 }
1172
1173 if (self->threadExitCheckCount < kMaxCount) {
1174 /*
1175 * Spin a couple of times to let other destructors fire.
1176 */
1177 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1178 self->threadId, self->threadExitCheckCount);
1179 self->threadExitCheckCount++;
1180 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1181 if (cc != 0) {
1182 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1183 self->threadId);
1184 dvmAbort();
1185 }
1186 } else {
1187 LOGE("threadid=%d: native thread exited without detaching\n",
1188 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001189 dvmAbort();
1190 }
1191}
1192
1193
1194/*
1195 * Assign the threadId. This needs to be a small integer so that our
1196 * "thin" locks fit in a small number of bits.
1197 *
1198 * We reserve zero for use as an invalid ID.
1199 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001200 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001201 */
1202static void assignThreadId(Thread* thread)
1203{
Carl Shapiro59a93122010-01-26 17:12:51 -08001204 /*
1205 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001206 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1207 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001208 */
1209 int num = dvmAllocBit(gDvm.threadIdMap);
1210 if (num < 0) {
1211 LOGE("Ran out of thread IDs\n");
1212 dvmAbort(); // TODO: make this a non-fatal error result
1213 }
1214
Carl Shapiro59a93122010-01-26 17:12:51 -08001215 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001216
1217 assert(thread->threadId != 0);
1218 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1219}
1220
1221/*
1222 * Give back the thread ID.
1223 */
1224static void releaseThreadId(Thread* thread)
1225{
1226 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001227 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001228 thread->threadId = 0;
1229}
1230
1231
1232/*
1233 * Add a stack frame that makes it look like the native code in the main
1234 * thread was originally invoked from interpreted code. This gives us a
1235 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1236 * VM begins by executing "main" in a class, so in a way this brings us
1237 * closer to the spec.
1238 */
1239static bool createFakeEntryFrame(Thread* thread)
1240{
1241 assert(thread->threadId == kMainThreadId); // main thread only
1242
1243 /* find the method on first use */
1244 if (gDvm.methFakeNativeEntry == NULL) {
1245 ClassObject* nativeStart;
1246 Method* mainMeth;
1247
1248 nativeStart = dvmFindSystemClassNoInit(
1249 "Ldalvik/system/NativeStart;");
1250 if (nativeStart == NULL) {
1251 LOGE("Unable to find dalvik.system.NativeStart class\n");
1252 return false;
1253 }
1254
1255 /*
1256 * Because we are creating a frame that represents application code, we
1257 * want to stuff the application class loader into the method's class
1258 * loader field, even though we're using the system class loader to
1259 * load it. This makes life easier over in JNI FindClass (though it
1260 * could bite us in other ways).
1261 *
1262 * Unfortunately this is occurring too early in the initialization,
1263 * of necessity coming before JNI is initialized, and we're not quite
1264 * ready to set up the application class loader.
1265 *
1266 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1267 * and check it in FindClass. The method is private so nobody else
1268 * can call it.
1269 */
1270 //nativeStart->classLoader = dvmGetSystemClassLoader();
1271
1272 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1273 "main", "([Ljava/lang/String;)V");
1274 if (mainMeth == NULL) {
1275 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1276 return false;
1277 }
1278
1279 gDvm.methFakeNativeEntry = mainMeth;
1280 }
1281
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001282 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1283 return false;
1284
1285 /*
1286 * Null out the "String[] args" argument.
1287 */
1288 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1289 u4* framePtr = (u4*) thread->curFrame;
1290 framePtr[0] = 0;
1291
1292 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001293}
1294
1295
1296/*
1297 * Add a stack frame that makes it look like the native thread has been
1298 * executing interpreted code. This gives us a place to hang JNI local
1299 * references.
1300 */
1301static bool createFakeRunFrame(Thread* thread)
1302{
1303 ClassObject* nativeStart;
1304 Method* runMeth;
1305
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001306 /*
1307 * TODO: cache this result so we don't have to dig for it every time
1308 * somebody attaches a thread to the VM. Also consider changing this
1309 * to a static method so we don't have a null "this" pointer in the
1310 * "ins" on the stack. (Does it really need to look like a Runnable?)
1311 */
1312 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001313 if (nativeStart == NULL) {
1314 LOGE("Unable to find dalvik.system.NativeStart class\n");
1315 return false;
1316 }
1317
1318 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1319 if (runMeth == NULL) {
1320 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1321 return false;
1322 }
1323
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001324 if (!dvmPushJNIFrame(thread, runMeth))
1325 return false;
1326
1327 /*
1328 * Provide a NULL 'this' argument. The method we've put at the top of
1329 * the stack looks like a virtual call to run() in a Runnable class.
1330 * (If we declared the method static, it wouldn't take any arguments
1331 * and we wouldn't have to do this.)
1332 */
1333 assert(runMeth->registersSize == 1);
1334 u4* framePtr = (u4*) thread->curFrame;
1335 framePtr[0] = 0;
1336
1337 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001338}
1339
1340/*
1341 * Helper function to set the name of the current thread
1342 */
1343static void setThreadName(const char *threadName)
1344{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001345 int hasAt = 0;
1346 int hasDot = 0;
1347 const char *s = threadName;
1348 while (*s) {
1349 if (*s == '.') hasDot = 1;
1350 else if (*s == '@') hasAt = 1;
1351 s++;
1352 }
1353 int len = s - threadName;
1354 if (len < 15 || hasAt || !hasDot) {
1355 s = threadName;
1356 } else {
1357 s = threadName + len - 15;
1358 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001359#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001360 /* pthread_setname_np fails rather than truncating long strings */
1361 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1362 strncpy(buf, s, sizeof(buf)-1);
1363 buf[sizeof(buf)-1] = '\0';
1364 int err = pthread_setname_np(pthread_self(), buf);
1365 if (err != 0) {
1366 LOGW("Unable to set the name of current thread to '%s': %s\n",
1367 buf, strerror(err));
1368 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001369#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001370 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001371#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001372 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001373#endif
1374}
1375
1376/*
1377 * Create a thread as a result of java.lang.Thread.start().
1378 *
1379 * We do have to worry about some concurrency problems, e.g. programs
1380 * that try to call Thread.start() on the same object from multiple threads.
1381 * (This will fail for all but one, but we have to make sure that it succeeds
1382 * for exactly one.)
1383 *
1384 * Some of the complexity here arises from our desire to mimic the
1385 * Thread vs. VMThread class decomposition we inherited. We've been given
1386 * a Thread, and now we need to create a VMThread and then populate both
1387 * objects. We also need to create one of our internal Thread objects.
1388 *
1389 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001390 *
1391 * The "threadObj" reference must be pinned by the caller to prevent the GC
1392 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001393 */
1394bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1395{
1396 pthread_attr_t threadAttr;
1397 pthread_t threadHandle;
1398 Thread* self;
1399 Thread* newThread = NULL;
1400 Object* vmThreadObj = NULL;
1401 int stackSize;
1402
1403 assert(threadObj != NULL);
1404
1405 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001406 // Allow the sampling profiler thread. We shut it down before forking.
1407 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1408 gDvm.offJavaLangThread_name);
1409 char* threadName = dvmCreateCstrFromString(nameStr);
1410 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1411 free(threadName);
1412 if (!profilerThread) {
1413 dvmThrowException("Ljava/lang/IllegalStateException;",
1414 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001415
Bob Lee9dc72a32009-09-04 18:28:16 -07001416 goto fail;
1417 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001418 }
1419
1420 self = dvmThreadSelf();
1421 if (reqStackSize == 0)
1422 stackSize = gDvm.stackSize;
1423 else if (reqStackSize < kMinStackSize)
1424 stackSize = kMinStackSize;
1425 else if (reqStackSize > kMaxStackSize)
1426 stackSize = kMaxStackSize;
1427 else
1428 stackSize = reqStackSize;
1429
1430 pthread_attr_init(&threadAttr);
1431 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1432
1433 /*
1434 * To minimize the time spent in the critical section, we allocate the
1435 * vmThread object here.
1436 */
1437 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1438 if (vmThreadObj == NULL)
1439 goto fail;
1440
1441 newThread = allocThread(stackSize);
1442 if (newThread == NULL)
1443 goto fail;
1444 newThread->threadObj = threadObj;
1445
1446 assert(newThread->status == THREAD_INITIALIZING);
1447
1448 /*
1449 * We need to lock out other threads while we test and set the
1450 * "vmThread" field in java.lang.Thread, because we use that to determine
1451 * if this thread has been started before. We use the thread list lock
1452 * because it's handy and we're going to need to grab it again soon
1453 * anyway.
1454 */
1455 dvmLockThreadList(self);
1456
1457 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1458 dvmUnlockThreadList();
1459 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1460 "thread has already been started");
1461 goto fail;
1462 }
1463
1464 /*
1465 * There are actually three data structures: Thread (object), VMThread
1466 * (object), and Thread (C struct). All of them point to at least one
1467 * other.
1468 *
1469 * As soon as "VMThread.vmData" is assigned, other threads can start
1470 * making calls into us (e.g. setPriority).
1471 */
1472 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1473 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1474
1475 /*
1476 * Thread creation might take a while, so release the lock.
1477 */
1478 dvmUnlockThreadList();
1479
Carl Shapiro5617ad32010-07-02 10:50:57 -07001480 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1481 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001482 newThread);
1483 oldStatus = dvmChangeStatus(self, oldStatus);
1484
1485 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001486 /*
1487 * Failure generally indicates that we have exceeded system
1488 * resource limits. VirtualMachineError is probably too severe,
1489 * so use OutOfMemoryError.
1490 */
1491 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1492
1493 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1494
1495 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1496 "thread creation failed");
1497 goto fail;
1498 }
1499
1500 /*
1501 * We need to wait for the thread to start. Otherwise, depending on
1502 * the whims of the OS scheduler, we could return and the code in our
1503 * thread could try to do operations on the new thread before it had
1504 * finished starting.
1505 *
1506 * The new thread will lock the thread list, change its state to
1507 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1508 * on gDvm.threadStartCond (which uses the thread list lock). This
1509 * thread (the parent) will either see that the thread is already ready
1510 * after we grab the thread list lock, or will be awakened from the
1511 * condition variable on the broadcast.
1512 *
1513 * We don't want to stall the rest of the VM while the new thread
1514 * starts, which can happen if the GC wakes up at the wrong moment.
1515 * So, we change our own status to VMWAIT, and self-suspend if
1516 * necessary after we finish adding the new thread.
1517 *
1518 *
1519 * We have to deal with an odd race with the GC/debugger suspension
1520 * mechanism when creating a new thread. The information about whether
1521 * or not a thread should be suspended is contained entirely within
1522 * the Thread struct; this is usually cleaner to deal with than having
1523 * one or more globally-visible suspension flags. The trouble is that
1524 * we could create the thread while the VM is trying to suspend all
1525 * threads. The suspend-count won't be nonzero for the new thread,
1526 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1527 *
1528 * The easiest way to deal with this is to prevent the new thread from
1529 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001530 * following (correct) sequence of events for a "badly timed" GC
1531 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001532 *
1533 * - call pthread_create()
1534 * - lock thread list
1535 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1536 * - sleep on condition var (mutex = thread list lock) until child starts
1537 * + GC triggered by another thread
1538 * + thread list locked; suspend counts updated; thread list unlocked
1539 * + loop waiting for all runnable threads to suspend
1540 * + success, start GC
1541 * o child thread wakes, signals condition var to wake parent
1542 * o child waits for parent ack on condition variable
1543 * - we wake up, locking thread list
1544 * - add child to thread list
1545 * - unlock thread list
1546 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1547 * + GC finishes; all threads in thread list are resumed
1548 * - lock thread list
1549 * - set child to THREAD_VMWAIT, and signal it to start
1550 * - unlock thread list
1551 * o child resumes
1552 * o child changes state to THREAD_RUNNING
1553 *
1554 * The above shows the GC starting up during thread creation, but if
1555 * it starts anywhere after VMThread.create() is called it will
1556 * produce the same series of events.
1557 *
1558 * Once the child is in the thread list, it will be suspended and
1559 * resumed like any other thread. In the above scenario the resume-all
1560 * code will try to resume the new thread, which was never actually
1561 * suspended, and try to decrement the child's thread suspend count to -1.
1562 * We can catch this in the resume-all code.
1563 *
1564 * Bouncing back and forth between threads like this adds a small amount
1565 * of scheduler overhead to thread startup.
1566 *
1567 * One alternative to having the child wait for the parent would be
1568 * to have the child inherit the parents' suspension count. This
1569 * would work for a GC, since we can safely assume that the parent
1570 * thread didn't cause it, but we must only do so if the parent suspension
1571 * was caused by a suspend-all. If the parent was being asked to
1572 * suspend singly by the debugger, the child should not inherit the value.
1573 *
1574 * We could also have a global "new thread suspend count" that gets
1575 * picked up by new threads before changing state to THREAD_RUNNING.
1576 * This would be protected by the thread list lock and set by a
1577 * suspend-all.
1578 */
1579 dvmLockThreadList(self);
1580 assert(self->status == THREAD_RUNNING);
1581 self->status = THREAD_VMWAIT;
1582 while (newThread->status != THREAD_STARTING)
1583 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1584
1585 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1586 newThread->next = gDvm.threadList->next;
1587 if (newThread->next != NULL)
1588 newThread->next->prev = newThread;
1589 newThread->prev = gDvm.threadList;
1590 gDvm.threadList->next = newThread;
1591
1592 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1593 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1594
1595 dvmUnlockThreadList();
1596
1597 /* change status back to RUNNING, self-suspending if necessary */
1598 dvmChangeStatus(self, THREAD_RUNNING);
1599
1600 /*
1601 * Tell the new thread to start.
1602 *
1603 * We must hold the thread list lock before messing with another thread.
1604 * In the general case we would also need to verify that newThread was
1605 * still in the thread list, but in our case the thread has not started
1606 * executing user code and therefore has not had a chance to exit.
1607 *
1608 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1609 * comes with a suspend-pending check.
1610 */
1611 dvmLockThreadList(self);
1612
1613 assert(newThread->status == THREAD_STARTING);
1614 newThread->status = THREAD_VMWAIT;
1615 pthread_cond_broadcast(&gDvm.threadStartCond);
1616
1617 dvmUnlockThreadList();
1618
1619 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1620 return true;
1621
1622fail:
1623 freeThread(newThread);
1624 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1625 return false;
1626}
1627
1628/*
1629 * pthread entry function for threads started from interpreted code.
1630 */
1631static void* interpThreadStart(void* arg)
1632{
1633 Thread* self = (Thread*) arg;
1634
1635 char *threadName = dvmGetThreadName(self);
1636 setThreadName(threadName);
1637 free(threadName);
1638
1639 /*
1640 * Finish initializing the Thread struct.
1641 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001642 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001643 prepareThread(self);
1644
1645 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1646
1647 /*
1648 * Change our status and wake our parent, who will add us to the
1649 * thread list and advance our state to VMWAIT.
1650 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001651 self->status = THREAD_STARTING;
1652 pthread_cond_broadcast(&gDvm.threadStartCond);
1653
1654 /*
1655 * Wait until the parent says we can go. Assuming there wasn't a
1656 * suspend pending, this will happen immediately. When it completes,
1657 * we're full-fledged citizens of the VM.
1658 *
1659 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1660 * because the pthread_cond_wait below needs to reacquire a lock that
1661 * suspend-all is also interested in. If we get unlucky, the parent could
1662 * change us to THREAD_RUNNING, then a GC could start before we get
1663 * signaled, and suspend-all will grab the thread list lock and then
1664 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1665 * trying to get the lock.
1666 */
1667 while (self->status != THREAD_VMWAIT)
1668 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1669
1670 dvmUnlockThreadList();
1671
1672 /*
1673 * Add a JNI context.
1674 */
1675 self->jniEnv = dvmCreateJNIEnv(self);
1676
1677 /*
1678 * Change our state so the GC will wait for us from now on. If a GC is
1679 * in progress this call will suspend us.
1680 */
1681 dvmChangeStatus(self, THREAD_RUNNING);
1682
1683 /*
1684 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001685 * us to suspend ourselves (and others). The thread state may change
1686 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001687 */
1688 if (gDvm.debuggerConnected)
1689 dvmDbgPostThreadStart(self);
1690
1691 /*
1692 * Set the system thread priority according to the Thread object's
1693 * priority level. We don't usually need to do this, because both the
1694 * Thread object and system thread priorities inherit from parents. The
1695 * tricky case is when somebody creates a Thread object, calls
1696 * setPriority(), and then starts the thread. We could manage this with
1697 * a "needs priority update" flag to avoid the redundant call.
1698 */
Andy McFadden4879df92009-08-07 14:49:40 -07001699 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001700 gDvm.offJavaLangThread_priority);
1701 dvmChangeThreadPriority(self, priority);
1702
1703 /*
1704 * Execute the "run" method.
1705 *
1706 * At this point our stack is empty, so somebody who comes looking for
1707 * stack traces right now won't have much to look at. This is normal.
1708 */
1709 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1710 JValue unused;
1711
1712 LOGV("threadid=%d: calling run()\n", self->threadId);
1713 assert(strcmp(run->name, "run") == 0);
1714 dvmCallMethod(self, run, self->threadObj, &unused);
1715 LOGV("threadid=%d: exiting\n", self->threadId);
1716
1717 /*
1718 * Remove the thread from various lists, report its death, and free
1719 * its resources.
1720 */
1721 dvmDetachCurrentThread();
1722
1723 return NULL;
1724}
1725
1726/*
1727 * The current thread is exiting with an uncaught exception. The
1728 * Java programming language allows the application to provide a
1729 * thread-exit-uncaught-exception handler for the VM, for a specific
1730 * Thread, and for all threads in a ThreadGroup.
1731 *
1732 * Version 1.5 added the per-thread handler. We need to call
1733 * "uncaughtException" in the handler object, which is either the
1734 * ThreadGroup object or the Thread-specific handler.
1735 */
1736static void threadExitUncaughtException(Thread* self, Object* group)
1737{
1738 Object* exception;
1739 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001740 Method* uncaughtHandler = NULL;
1741 InstField* threadHandler;
1742
1743 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1744 self->threadId, group);
1745 assert(group != NULL);
1746
1747 /*
1748 * Get a pointer to the exception, then clear out the one in the
1749 * thread. We don't want to have it set when executing interpreted code.
1750 */
1751 exception = dvmGetException(self);
1752 dvmAddTrackedAlloc(exception, self);
1753 dvmClearException(self);
1754
1755 /*
1756 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1757 * else use "group" (which is an instance of UncaughtExceptionHandler).
1758 */
1759 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1760 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1761 if (threadHandler == NULL) {
1762 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1763 goto bail;
1764 }
1765 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1766 if (handlerObj == NULL)
1767 handlerObj = group;
1768
1769 /*
1770 * Find the "uncaughtHandler" field in this object.
1771 */
1772 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1773 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1774
1775 if (uncaughtHandler != NULL) {
1776 //LOGI("+++ calling %s.uncaughtException\n",
1777 // handlerObj->clazz->descriptor);
1778 JValue unused;
1779 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1780 self->threadObj, exception);
1781 } else {
1782 /* restore it and dump a stack trace */
1783 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1784 handlerObj->clazz->descriptor);
1785 dvmSetException(self, exception);
1786 dvmLogExceptionStackTrace();
1787 }
1788
1789bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001790#if defined(WITH_JIT)
1791 /* Remove this thread's suspendCount from global suspendCount sum */
1792 lockThreadSuspendCount();
1793 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1794 unlockThreadSuspendCount();
1795#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001796 dvmReleaseTrackedAlloc(exception, self);
1797}
1798
1799
1800/*
1801 * Create an internal VM thread, for things like JDWP and finalizers.
1802 *
1803 * The easiest way to do this is create a new thread and then use the
1804 * JNI AttachCurrentThread implementation.
1805 *
1806 * This does not return until after the new thread has begun executing.
1807 */
1808bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1809 InternalThreadStart func, void* funcArg)
1810{
1811 InternalStartArgs* pArgs;
1812 Object* systemGroup;
1813 pthread_attr_t threadAttr;
1814 volatile Thread* newThread = NULL;
1815 volatile int createStatus = 0;
1816
1817 systemGroup = dvmGetSystemThreadGroup();
1818 if (systemGroup == NULL)
1819 return false;
1820
1821 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1822 pArgs->func = func;
1823 pArgs->funcArg = funcArg;
1824 pArgs->name = strdup(name); // storage will be owned by new thread
1825 pArgs->group = systemGroup;
1826 pArgs->isDaemon = true;
1827 pArgs->pThread = &newThread;
1828 pArgs->pCreateStatus = &createStatus;
1829
1830 pthread_attr_init(&threadAttr);
1831 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1832
1833 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1834 pArgs) != 0)
1835 {
1836 LOGE("internal thread creation failed\n");
1837 free(pArgs->name);
1838 free(pArgs);
1839 return false;
1840 }
1841
1842 /*
1843 * Wait for the child to start. This gives us an opportunity to make
1844 * sure that the thread started correctly, and allows our caller to
1845 * assume that the thread has started running.
1846 *
1847 * Because we aren't holding a lock across the thread creation, it's
1848 * possible that the child will already have completed its
1849 * initialization. Because the child only adjusts "createStatus" while
1850 * holding the thread list lock, the initial condition on the "while"
1851 * loop will correctly avoid the wait if this occurs.
1852 *
1853 * It's also possible that we'll have to wait for the thread to finish
1854 * being created, and as part of allocating a Thread object it might
1855 * need to initiate a GC. We switch to VMWAIT while we pause.
1856 */
1857 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001858 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001859 dvmLockThreadList(self);
1860 while (createStatus == 0)
1861 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1862
1863 if (newThread == NULL) {
1864 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1865 assert(createStatus < 0);
1866 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1867 dvmUnlockThreadList();
1868 dvmChangeStatus(self, oldStatus);
1869 return false;
1870 }
1871
1872 /* thread could be in any state now (except early init states) */
1873 //assert(newThread->status == THREAD_RUNNING);
1874
1875 dvmUnlockThreadList();
1876 dvmChangeStatus(self, oldStatus);
1877
1878 return true;
1879}
1880
1881/*
1882 * pthread entry function for internally-created threads.
1883 *
1884 * We are expected to free "arg" and its contents. If we're a daemon
1885 * thread, and we get cancelled abruptly when the VM shuts down, the
1886 * storage won't be freed. If this becomes a concern we can make a copy
1887 * on the stack.
1888 */
1889static void* internalThreadStart(void* arg)
1890{
1891 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1892 JavaVMAttachArgs jniArgs;
1893
1894 jniArgs.version = JNI_VERSION_1_2;
1895 jniArgs.name = pArgs->name;
1896 jniArgs.group = pArgs->group;
1897
1898 setThreadName(pArgs->name);
1899
1900 /* use local jniArgs as stack top */
1901 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1902 /*
1903 * Tell the parent of our success.
1904 *
1905 * threadListLock is the mutex for threadStartCond.
1906 */
1907 dvmLockThreadList(dvmThreadSelf());
1908 *pArgs->pCreateStatus = 1;
1909 *pArgs->pThread = dvmThreadSelf();
1910 pthread_cond_broadcast(&gDvm.threadStartCond);
1911 dvmUnlockThreadList();
1912
1913 LOG_THREAD("threadid=%d: internal '%s'\n",
1914 dvmThreadSelf()->threadId, pArgs->name);
1915
1916 /* execute */
1917 (*pArgs->func)(pArgs->funcArg);
1918
1919 /* detach ourselves */
1920 dvmDetachCurrentThread();
1921 } else {
1922 /*
1923 * Tell the parent of our failure. We don't have a Thread struct,
1924 * so we can't be suspended, so we don't need to enter a critical
1925 * section.
1926 */
1927 dvmLockThreadList(dvmThreadSelf());
1928 *pArgs->pCreateStatus = -1;
1929 assert(*pArgs->pThread == NULL);
1930 pthread_cond_broadcast(&gDvm.threadStartCond);
1931 dvmUnlockThreadList();
1932
1933 assert(*pArgs->pThread == NULL);
1934 }
1935
1936 free(pArgs->name);
1937 free(pArgs);
1938 return NULL;
1939}
1940
1941/*
1942 * Attach the current thread to the VM.
1943 *
1944 * Used for internally-created threads and JNI's AttachCurrentThread.
1945 */
1946bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1947{
1948 Thread* self = NULL;
1949 Object* threadObj = NULL;
1950 Object* vmThreadObj = NULL;
1951 StringObject* threadNameStr = NULL;
1952 Method* init;
1953 bool ok, ret;
1954
Andy McFaddene3346d82010-06-02 15:37:21 -07001955 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001956 self = allocThread(gDvm.stackSize);
1957 if (self == NULL)
1958 goto fail;
1959 setThreadSelf(self);
1960
1961 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001962 * Finish our thread prep. We need to do this before adding ourselves
1963 * to the thread list or invoking any interpreted code. prepareThread()
1964 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001965 */
1966 dvmLockThreadList(self);
1967 ok = prepareThread(self);
1968 dvmUnlockThreadList();
1969 if (!ok)
1970 goto fail;
1971
1972 self->jniEnv = dvmCreateJNIEnv(self);
1973 if (self->jniEnv == NULL)
1974 goto fail;
1975
1976 /*
1977 * Create a "fake" JNI frame at the top of the main thread interp stack.
1978 * It isn't really necessary for the internal threads, but it gives
1979 * the debugger something to show. It is essential for the JNI-attached
1980 * threads.
1981 */
1982 if (!createFakeRunFrame(self))
1983 goto fail;
1984
1985 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001986 * The native side of the thread is ready; add it to the list. Once
1987 * 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 -08001988 */
1989 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1990
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001991 dvmLockThreadList(self);
1992
1993 self->next = gDvm.threadList->next;
1994 if (self->next != NULL)
1995 self->next->prev = self;
1996 self->prev = gDvm.threadList;
1997 gDvm.threadList->next = self;
1998 if (!isDaemon)
1999 gDvm.nonDaemonThreadCount++;
2000
2001 dvmUnlockThreadList();
2002
2003 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002004 * Switch state from initializing to running.
2005 *
2006 * It's possible that a GC began right before we added ourselves
2007 * to the thread list, and is still going. That means our thread
2008 * suspend count won't reflect the fact that we should be suspended.
2009 * To deal with this, we transition to VMWAIT, pulse the heap lock,
2010 * and then advance to RUNNING. That will ensure that we stall until
2011 * the GC completes.
2012 *
2013 * Once we're in RUNNING, we're like any other thread in the VM (except
2014 * for the lack of an initialized threadObj). We're then free to
2015 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002016 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002017 assert(self->status == THREAD_INITIALIZING);
2018 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002019 dvmLockMutex(&gDvm.gcHeapLock);
2020 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002021 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002022
2023 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002024 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002025 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002026 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2027 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2028 if (threadObj == NULL || vmThreadObj == NULL)
2029 goto fail_unlink;
2030
2031 /*
2032 * This makes threadObj visible to the GC. We still have it in the
2033 * tracked allocation table, so it can't move around on us.
2034 */
2035 self->threadObj = threadObj;
2036 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2037
2038 /*
2039 * Create a string for the thread name.
2040 */
2041 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002042 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002043 if (threadNameStr == NULL) {
2044 assert(dvmCheckException(dvmThreadSelf()));
2045 goto fail_unlink;
2046 }
2047 }
2048
2049 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2050 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2051 if (init == NULL) {
2052 assert(dvmCheckException(self));
2053 goto fail_unlink;
2054 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002055
2056 /*
2057 * Now we're ready to run some interpreted code.
2058 *
2059 * We need to construct the Thread object and set the VMThread field.
2060 * Setting VMThread tells interpreted code that we're alive.
2061 *
2062 * Call the (group, name, priority, daemon) constructor on the Thread.
2063 * This sets the thread's name and adds it to the specified group, and
2064 * provides values for priority and daemon (which are normally inherited
2065 * from the current thread).
2066 */
2067 JValue unused;
2068 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2069 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2070 if (dvmCheckException(self)) {
2071 LOGE("exception thrown while constructing attached thread object\n");
2072 goto fail_unlink;
2073 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002074
2075 /*
2076 * Set the VMThread field, which tells interpreted code that we're alive.
2077 *
2078 * The risk of a thread start collision here is very low; somebody
2079 * would have to be deliberately polling the ThreadGroup list and
2080 * trying to start threads against anything it sees, which would
2081 * generally cause problems for all thread creation. However, for
2082 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002083 *
2084 * TODO: this still has a race, it's just smaller. Not sure this is
2085 * worth putting effort into fixing. Need to hold a lock while
2086 * fiddling with the field, or maybe initialize the Thread object in a
2087 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002088 */
2089 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002090 LOGW("WOW: thread start hijack\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002091 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2092 "thread has already been started");
2093 /* We don't want to free anything associated with the thread
2094 * because someone is obviously interested in it. Just let
2095 * it go and hope it will clean itself up when its finished.
2096 * This case should never happen anyway.
2097 *
2098 * Since we're letting it live, we need to finish setting it up.
2099 * We just have to let the caller know that the intended operation
2100 * has failed.
2101 *
2102 * [ This seems strange -- stepping on the vmThread object that's
2103 * already present seems like a bad idea. TODO: figure this out. ]
2104 */
2105 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002106 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002107 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002108 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002109 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2110
Andy McFaddene3346d82010-06-02 15:37:21 -07002111 /* we can now safely un-pin these */
2112 dvmReleaseTrackedAlloc(threadObj, self);
2113 dvmReleaseTrackedAlloc(vmThreadObj, self);
2114 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002115
2116 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2117 self->threadId, pArgs->name);
2118
2119 /* tell the debugger & DDM */
2120 if (gDvm.debuggerConnected)
2121 dvmDbgPostThreadStart(self);
2122
2123 return ret;
2124
2125fail_unlink:
2126 dvmLockThreadList(self);
2127 unlinkThread(self);
2128 if (!isDaemon)
2129 gDvm.nonDaemonThreadCount--;
2130 dvmUnlockThreadList();
2131 /* fall through to "fail" */
2132fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002133 dvmReleaseTrackedAlloc(threadObj, self);
2134 dvmReleaseTrackedAlloc(vmThreadObj, self);
2135 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002136 if (self != NULL) {
2137 if (self->jniEnv != NULL) {
2138 dvmDestroyJNIEnv(self->jniEnv);
2139 self->jniEnv = NULL;
2140 }
2141 freeThread(self);
2142 }
2143 setThreadSelf(NULL);
2144 return false;
2145}
2146
2147/*
2148 * Detach the thread from the various data structures, notify other threads
2149 * that are waiting to "join" it, and free up all heap-allocated storage.
2150 *
2151 * Used for all threads.
2152 *
2153 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2154 * requires us to enforce this for the DetachCurrentThread call, probably
2155 * because it also says that DetachCurrentThread causes all monitors
2156 * associated with the thread to be released. (Because the stack is empty,
2157 * we only have to worry about explicit JNI calls to MonitorEnter.)
2158 *
2159 * THOUGHT:
2160 * We might want to avoid freeing our internal Thread structure until the
2161 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2162 * get to once the thread shuts down, but there is a small possibility of
2163 * an operation starting in another thread before this thread halts, and
2164 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2165 * We don't want something like Thread.isInterrupted() crawling through
2166 * freed storage. Can do with a Thread finalizer, or by creating a
2167 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2168 * state into that.
2169 */
2170void dvmDetachCurrentThread(void)
2171{
2172 Thread* self = dvmThreadSelf();
2173 Object* vmThread;
2174 Object* group;
2175
2176 /*
2177 * Make sure we're not detaching a thread that's still running. (This
2178 * could happen with an explicit JNI detach call.)
2179 *
2180 * A thread created by interpreted code will finish with a depth of
2181 * zero, while a JNI-attached thread will have the synthetic "stack
2182 * starter" native method at the top.
2183 */
2184 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2185 if (curDepth != 0) {
2186 bool topIsNative = false;
2187
2188 if (curDepth == 1) {
2189 /* not expecting a lingering break frame; just look at curFrame */
2190 assert(!dvmIsBreakFrame(self->curFrame));
2191 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2192 if (dvmIsNativeMethod(ssa->method))
2193 topIsNative = true;
2194 }
2195
2196 if (!topIsNative) {
2197 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2198 curDepth);
2199 dvmDumpThread(self, false);
2200 dvmAbort();
2201 }
2202 }
2203
2204 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2205 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2206
2207 /*
2208 * Release any held monitors. Since there are no interpreted stack
2209 * frames, the only thing left are the monitors held by JNI MonitorEnter
2210 * calls.
2211 */
2212 dvmReleaseJniMonitors(self);
2213
2214 /*
2215 * Do some thread-exit uncaught exception processing if necessary.
2216 */
2217 if (dvmCheckException(self))
2218 threadExitUncaughtException(self, group);
2219
2220 /*
2221 * Remove the thread from the thread group.
2222 */
2223 if (group != NULL) {
2224 Method* removeThread =
2225 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2226 JValue unused;
2227 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2228 }
2229
2230 /*
2231 * Clear the vmThread reference in the Thread object. Interpreted code
2232 * will now see that this Thread is not running. As this may be the
2233 * only reference to the VMThread object that the VM knows about, we
2234 * have to create an internal reference to it first.
2235 */
2236 vmThread = dvmGetFieldObject(self->threadObj,
2237 gDvm.offJavaLangThread_vmThread);
2238 dvmAddTrackedAlloc(vmThread, self);
2239 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2240
2241 /* clear out our struct Thread pointer, since it's going away */
2242 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2243
2244 /*
2245 * Tell the debugger & DDM. This may cause the current thread or all
2246 * threads to suspend.
2247 *
2248 * The JDWP spec is somewhat vague about when this happens, other than
2249 * that it's issued by the dying thread, which may still appear in
2250 * an "all threads" listing.
2251 */
2252 if (gDvm.debuggerConnected)
2253 dvmDbgPostThreadDeath(self);
2254
2255 /*
2256 * Thread.join() is implemented as an Object.wait() on the VMThread
2257 * object. Signal anyone who is waiting.
2258 */
2259 dvmLockObject(self, vmThread);
2260 dvmObjectNotifyAll(self, vmThread);
2261 dvmUnlockObject(self, vmThread);
2262
2263 dvmReleaseTrackedAlloc(vmThread, self);
2264 vmThread = NULL;
2265
2266 /*
2267 * We're done manipulating objects, so it's okay if the GC runs in
2268 * parallel with us from here out. It's important to do this if
2269 * profiling is enabled, since we can wait indefinitely.
2270 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002271 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002272
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002273 /*
2274 * If we're doing method trace profiling, we don't want threads to exit,
2275 * because if they do we'll end up reusing thread IDs. This complicates
2276 * analysis and makes it impossible to have reasonable output in the
2277 * "threads" section of the "key" file.
2278 *
2279 * We need to do this after Thread.join() completes, or other threads
2280 * could get wedged. Since self->threadObj is still valid, the Thread
2281 * object will not get GCed even though we're no longer in the ThreadGroup
2282 * list (which is important since the profiling thread needs to get
2283 * the thread's name).
2284 */
2285 MethodTraceState* traceState = &gDvm.methodTrace;
2286
2287 dvmLockMutex(&traceState->startStopLock);
2288 if (traceState->traceEnabled) {
2289 LOGI("threadid=%d: waiting for method trace to finish\n",
2290 self->threadId);
2291 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002292 dvmWaitCond(&traceState->threadExitCond,
2293 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002294 }
2295 }
2296 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002297
2298 dvmLockThreadList(self);
2299
2300 /*
2301 * Lose the JNI context.
2302 */
2303 dvmDestroyJNIEnv(self->jniEnv);
2304 self->jniEnv = NULL;
2305
2306 self->status = THREAD_ZOMBIE;
2307
2308 /*
2309 * Remove ourselves from the internal thread list.
2310 */
2311 unlinkThread(self);
2312
2313 /*
2314 * If we're the last one standing, signal anybody waiting in
2315 * DestroyJavaVM that it's okay to exit.
2316 */
2317 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2318 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2319
2320 if (gDvm.nonDaemonThreadCount == 0) {
2321 int cc;
2322
2323 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2324 //dvmDumpAllThreads(false);
2325 // cond var guarded by threadListLock, which we already hold
2326 cc = pthread_cond_signal(&gDvm.vmExitCond);
2327 assert(cc == 0);
2328 }
2329 }
2330
2331 LOGV("threadid=%d: bye!\n", self->threadId);
2332 releaseThreadId(self);
2333 dvmUnlockThreadList();
2334
2335 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002336
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002337 freeThread(self);
2338}
2339
2340
2341/*
2342 * Suspend a single thread. Do not use to suspend yourself.
2343 *
2344 * This is used primarily for debugger/DDMS activity. Does not return
2345 * until the thread has suspended or is in a "safe" state (e.g. executing
2346 * native code outside the VM).
2347 *
2348 * The thread list lock should be held before calling here -- it's not
2349 * entirely safe to hang on to a Thread* from another thread otherwise.
2350 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2351 */
2352void dvmSuspendThread(Thread* thread)
2353{
2354 assert(thread != NULL);
2355 assert(thread != dvmThreadSelf());
2356 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2357
2358 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002359 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002360 thread->dbgSuspendCount++;
2361
2362 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2363 thread->threadId, thread->suspendCount);
2364 unlockThreadSuspendCount();
2365
2366 waitForThreadSuspend(dvmThreadSelf(), thread);
2367}
2368
2369/*
2370 * Reduce the suspend count of a thread. If it hits zero, tell it to
2371 * resume.
2372 *
2373 * Used primarily for debugger/DDMS activity. The thread in question
2374 * might have been suspended singly or as part of a suspend-all operation.
2375 *
2376 * The thread list lock should be held before calling here -- it's not
2377 * entirely safe to hang on to a Thread* from another thread otherwise.
2378 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2379 */
2380void dvmResumeThread(Thread* thread)
2381{
2382 assert(thread != NULL);
2383 assert(thread != dvmThreadSelf());
2384 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2385
2386 lockThreadSuspendCount();
2387 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002388 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002389 thread->dbgSuspendCount--;
2390 } else {
2391 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2392 thread->threadId);
2393 }
2394
2395 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2396 thread->threadId, thread->suspendCount);
2397
2398 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002399 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002400 }
2401
2402 unlockThreadSuspendCount();
2403}
2404
2405/*
2406 * Suspend yourself, as a result of debugger activity.
2407 */
2408void dvmSuspendSelf(bool jdwpActivity)
2409{
2410 Thread* self = dvmThreadSelf();
2411
Andy McFadden6dce9962010-08-23 16:45:24 -07002412 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002413 assert(gDvm.jdwpState != NULL);
2414 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2415 assert(false);
2416 return;
2417 }
2418
2419 /*
2420 * Collisions with other suspends aren't really interesting. We want
2421 * to ensure that we're the only one fiddling with the suspend count
2422 * though.
2423 */
2424 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002425 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002426 self->dbgSuspendCount++;
2427
2428 /*
2429 * Suspend ourselves.
2430 */
2431 assert(self->suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002432 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002433 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2434
2435 /*
2436 * Tell JDWP that we've completed suspension. The JDWP thread can't
2437 * tell us to resume before we're fully asleep because we hold the
2438 * suspend count lock.
2439 *
2440 * If we got here via waitForDebugger(), don't do this part.
2441 */
2442 if (jdwpActivity) {
2443 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2444 // self->threadId, (int) self->handle);
2445 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2446 }
2447
2448 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002449 dvmWaitCond(&gDvm.threadSuspendCountCond,
2450 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002451 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002452 /*
2453 * The condition was signaled but we're still suspended. This
2454 * can happen if the debugger lets go while a SIGQUIT thread
2455 * dump event is pending (assuming SignalCatcher was resumed for
2456 * just long enough to try to grab the thread-suspend lock).
2457 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002458 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
2459 self->threadId, self->suspendCount, self->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002460 }
2461 }
2462 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002463 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002464 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2465 self->threadId, self->status);
2466
2467 unlockThreadSuspendCount();
2468}
2469
2470
2471#ifdef HAVE_GLIBC
2472# define NUM_FRAMES 20
2473# include <execinfo.h>
2474/*
2475 * glibc-only stack dump function. Requires link with "--export-dynamic".
2476 *
2477 * TODO: move this into libs/cutils and make it work for all platforms.
2478 */
2479static void printBackTrace(void)
2480{
2481 void* array[NUM_FRAMES];
2482 size_t size;
2483 char** strings;
2484 size_t i;
2485
2486 size = backtrace(array, NUM_FRAMES);
2487 strings = backtrace_symbols(array, size);
2488
2489 LOGW("Obtained %zd stack frames.\n", size);
2490
2491 for (i = 0; i < size; i++)
2492 LOGW("%s\n", strings[i]);
2493
2494 free(strings);
2495}
2496#else
2497static void printBackTrace(void) {}
2498#endif
2499
2500/*
2501 * Dump the state of the current thread and that of another thread that
2502 * we think is wedged.
2503 */
2504static void dumpWedgedThread(Thread* thread)
2505{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002506 dvmDumpThread(dvmThreadSelf(), false);
2507 printBackTrace();
2508
2509 // dumping a running thread is risky, but could be useful
2510 dvmDumpThread(thread, true);
2511
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002512 // stop now and get a core dump
2513 //abort();
2514}
2515
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002516/*
2517 * If the thread is running at below-normal priority, temporarily elevate
2518 * it to "normal".
2519 *
2520 * Returns zero if no changes were made. Otherwise, returns bit flags
2521 * indicating what was changed, storing the previous values in the
2522 * provided locations.
2523 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002524int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002525 SchedPolicy* pSavedThreadPolicy)
2526{
2527 errno = 0;
2528 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2529 if (errno != 0) {
2530 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2531 thread->threadId, thread->systemTid);
2532 return 0;
2533 }
2534 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2535 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2536 thread->threadId, thread->systemTid);
2537 return 0;
2538 }
2539
2540 int changeFlags = 0;
2541
2542 /*
2543 * Change the priority if we're in the background group.
2544 */
2545 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2546 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2547 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2548 } else {
2549 changeFlags |= kChangedPolicy;
2550 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2551 thread->systemTid, *pSavedThreadPolicy);
2552 }
2553 }
2554
2555 /*
2556 * getpriority() returns the "nice" value, so larger numbers indicate
2557 * lower priority, with 0 being normal.
2558 */
2559 if (*pSavedThreadPrio > 0) {
2560 const int kHigher = 0;
2561 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2562 LOGW("Couldn't raise priority on tid %d to %d\n",
2563 thread->systemTid, kHigher);
2564 } else {
2565 changeFlags |= kChangedPriority;
2566 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2567 thread->systemTid, *pSavedThreadPrio, kHigher);
2568 }
2569 }
2570
2571 return changeFlags;
2572}
2573
2574/*
2575 * Reset the priority values for the thread in question.
2576 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002577void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002578 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2579{
2580 if ((changeFlags & kChangedPolicy) != 0) {
2581 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2582 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2583 thread->systemTid, savedThreadPolicy);
2584 } else {
2585 LOGD("Restored policy of %d to %d\n",
2586 thread->systemTid, savedThreadPolicy);
2587 }
2588 }
2589
2590 if ((changeFlags & kChangedPriority) != 0) {
2591 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2592 {
2593 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2594 thread->systemTid, savedThreadPrio);
2595 } else {
2596 LOGD("Restored priority on %d to %d\n",
2597 thread->systemTid, savedThreadPrio);
2598 }
2599 }
2600}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002601
2602/*
2603 * Wait for another thread to see the pending suspension and stop running.
2604 * It can either suspend itself or go into a non-running state such as
2605 * VMWAIT or NATIVE in which it cannot interact with the GC.
2606 *
2607 * If we're running at a higher priority, sched_yield() may not do anything,
2608 * so we need to sleep for "long enough" to guarantee that the other
2609 * thread has a chance to finish what it's doing. Sleeping for too short
2610 * a period (e.g. less than the resolution of the sleep clock) might cause
2611 * the scheduler to return immediately, so we want to start with a
2612 * "reasonable" value and expand.
2613 *
2614 * This does not return until the other thread has stopped running.
2615 * Eventually we time out and the VM aborts.
2616 *
2617 * This does not try to detect the situation where two threads are
2618 * waiting for each other to suspend. In normal use this is part of a
2619 * suspend-all, which implies that the suspend-all lock is held, or as
2620 * part of a debugger action in which the JDWP thread is always the one
2621 * doing the suspending. (We may need to re-evaluate this now that
2622 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2623 *
2624 * TODO: track basic stats about time required to suspend VM.
2625 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002626#define FIRST_SLEEP (250*1000) /* 0.25s */
2627#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002628static void waitForThreadSuspend(Thread* self, Thread* thread)
2629{
2630 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002631 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002632 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002633 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002634 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002635 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002636
2637 int sleepIter = 0;
2638 int retryCount = 0;
2639 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002640 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002641
Andy McFadden6dce9962010-08-23 16:45:24 -07002642 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002643 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002644 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002645 if (firstStartWhen == 0) // first iteration of first attempt
2646 firstStartWhen = startWhen;
2647
2648 /*
2649 * After waiting for a bit, check to see if the target thread is
2650 * running at a reduced priority. If so, bump it up temporarily
2651 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002652 */
2653 if (retryCount == 2) {
2654 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002655 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002656 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002657 }
2658 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002659
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002660#if defined (WITH_JIT)
2661 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002662 * If we're still waiting after the first timeout, unchain all
2663 * translations iff:
2664 * 1) There are new chains formed since the last unchain
2665 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002666 */
Ben Cheng6999d842010-01-26 16:46:15 -08002667 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2668 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002669 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002670 dvmJitUnchainAll();
2671 }
2672#endif
2673
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002674 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002675 * Sleep briefly. The iterative sleep call returns false if we've
2676 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002677 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002678 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002679 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002680 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002681 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002682 thread->threadId, priChangeFlags);
2683 if (retryCount > 1) {
2684 /* stack trace logging is slow; skip on first iter */
2685 dumpWedgedThread(thread);
2686 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002687 complained = true;
2688 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002689
2690 // keep going; could be slow due to valgrind
2691 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002692 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002693
2694 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002695 LOGE("Fatal spin-on-suspend, dumping threads\n");
2696 dvmDumpAllThreads(false);
2697
2698 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002699 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2700 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002701
2702 /* try to get a debuggerd dump from the spinning thread */
2703 dvmNukeThread(thread);
2704 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002705 dvmAbort();
2706 }
2707 }
2708 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002709
2710 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002711 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2712 self->threadId,
2713 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002714 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2715 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002716 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002717 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002718 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002719 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002720}
2721
2722/*
2723 * Suspend all threads except the current one. This is used by the GC,
2724 * the debugger, and by any thread that hits a "suspend all threads"
2725 * debugger event (e.g. breakpoint or exception).
2726 *
2727 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2728 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2729 * create objects and even execute arbitrary code. The "why" argument
2730 * allows the caller to say why the suspension is taking place.
2731 *
2732 * This can be called when a global suspend has already happened, due to
2733 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2734 * doesn't work.
2735 *
2736 * DO NOT grab any locks before calling here. We grab & release the thread
2737 * lock and suspend lock here (and we're not using recursive threads), and
2738 * we might have to self-suspend if somebody else beats us here.
2739 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002740 * We know the current thread is in the thread list, because we attach the
2741 * thread before doing anything that could cause VM suspension (like object
2742 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002743 */
2744void dvmSuspendAllThreads(SuspendCause why)
2745{
2746 Thread* self = dvmThreadSelf();
2747 Thread* thread;
2748
2749 assert(why != 0);
2750
2751 /*
2752 * Start by grabbing the thread suspend lock. If we can't get it, most
2753 * likely somebody else is in the process of performing a suspend or
2754 * resume, so lockThreadSuspend() will cause us to self-suspend.
2755 *
2756 * We keep the lock until all other threads are suspended.
2757 */
2758 lockThreadSuspend("susp-all", why);
2759
2760 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2761
2762 /*
2763 * This is possible if the current thread was in VMWAIT mode when a
2764 * suspend-all happened, and then decided to do its own suspend-all.
2765 * This can happen when a couple of threads have simultaneous events
2766 * of interest to the debugger.
2767 */
2768 //assert(self->suspendCount == 0);
2769
2770 /*
2771 * Increment everybody's suspend count (except our own).
2772 */
2773 dvmLockThreadList(self);
2774
2775 lockThreadSuspendCount();
2776 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2777 if (thread == self)
2778 continue;
2779
2780 /* debugger events don't suspend JDWP thread */
2781 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2782 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2783 continue;
2784
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002785 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002786 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2787 thread->dbgSuspendCount++;
2788 }
2789 unlockThreadSuspendCount();
2790
2791 /*
2792 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2793 * indicate the code is either running natively or sleeping quietly.
2794 * Any attempt to transition back to THREAD_RUNNING will cause a check
2795 * for suspension, so it should be impossible for anything to execute
2796 * interpreted code or modify objects (assuming native code plays nicely).
2797 *
2798 * It's also okay if the thread transitions to a non-RUNNING state.
2799 *
2800 * Note we released the threadSuspendCountLock before getting here,
2801 * so if another thread is fiddling with its suspend count (perhaps
2802 * self-suspending for the debugger) it won't block while we're waiting
2803 * in here.
2804 */
2805 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2806 if (thread == self)
2807 continue;
2808
2809 /* debugger events don't suspend JDWP thread */
2810 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2811 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2812 continue;
2813
2814 /* wait for the other thread to see the pending suspend */
2815 waitForThreadSuspend(self, thread);
2816
Andy McFadden6dce9962010-08-23 16:45:24 -07002817 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002818 self->threadId,
2819 thread->threadId, thread->status, thread->suspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07002820 thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002821 }
2822
2823 dvmUnlockThreadList();
2824 unlockThreadSuspend();
2825
2826 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2827}
2828
2829/*
2830 * Resume all threads that are currently suspended.
2831 *
2832 * The "why" must match with the previous suspend.
2833 */
2834void dvmResumeAllThreads(SuspendCause why)
2835{
2836 Thread* self = dvmThreadSelf();
2837 Thread* thread;
2838 int cc;
2839
2840 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2841 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2842
2843 /*
2844 * Decrement the suspend counts for all threads. No need for atomic
2845 * writes, since nobody should be moving until we decrement the count.
2846 * We do need to hold the thread list because of JNI attaches.
2847 */
2848 dvmLockThreadList(self);
2849 lockThreadSuspendCount();
2850 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2851 if (thread == self)
2852 continue;
2853
2854 /* debugger events don't suspend JDWP thread */
2855 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2856 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002857 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002858 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002859 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002860
2861 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002862 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002863 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2864 thread->dbgSuspendCount--;
2865 } else {
2866 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2867 thread->threadId);
2868 }
2869 }
2870 unlockThreadSuspendCount();
2871 dvmUnlockThreadList();
2872
2873 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002874 * In some ways it makes sense to continue to hold the thread-suspend
2875 * lock while we issue the wakeup broadcast. It allows us to complete
2876 * one operation before moving on to the next, which simplifies the
2877 * thread activity debug traces.
2878 *
2879 * This approach caused us some difficulty under Linux, because the
2880 * condition variable broadcast not only made the threads runnable,
2881 * but actually caused them to execute, and it was a while before
2882 * the thread performing the wakeup had an opportunity to release the
2883 * thread-suspend lock.
2884 *
2885 * This is a problem because, when a thread tries to acquire that
2886 * lock, it times out after 3 seconds. If at some point the thread
2887 * is told to suspend, the clock resets; but since the VM is still
2888 * theoretically mid-resume, there's no suspend pending. If, for
2889 * example, the GC was waking threads up while the SIGQUIT handler
2890 * was trying to acquire the lock, we would occasionally time out on
2891 * a busy system and SignalCatcher would abort.
2892 *
2893 * We now perform the unlock before the wakeup broadcast. The next
2894 * suspend can't actually start until the broadcast completes and
2895 * returns, because we're holding the thread-suspend-count lock, but the
2896 * suspending thread is now able to make progress and we avoid the abort.
2897 *
2898 * (Technically there is a narrow window between when we release
2899 * the thread-suspend lock and grab the thread-suspend-count lock.
2900 * This could cause us to send a broadcast to threads with nonzero
2901 * suspend counts, but this is expected and they'll all just fall
2902 * right back to sleep. It's probably safe to grab the suspend-count
2903 * lock before releasing thread-suspend, since we're still following
2904 * the correct order of acquisition, but it feels weird.)
2905 */
2906
2907 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2908 unlockThreadSuspend();
2909
2910 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002911 * Broadcast a notification to all suspended threads, some or all of
2912 * which may choose to wake up. No need to wait for them.
2913 */
2914 lockThreadSuspendCount();
2915 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2916 assert(cc == 0);
2917 unlockThreadSuspendCount();
2918
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002919 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2920}
2921
2922/*
2923 * Undo any debugger suspensions. This is called when the debugger
2924 * disconnects.
2925 */
2926void dvmUndoDebuggerSuspensions(void)
2927{
2928 Thread* self = dvmThreadSelf();
2929 Thread* thread;
2930 int cc;
2931
2932 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2933 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2934
2935 /*
2936 * Decrement the suspend counts for all threads. No need for atomic
2937 * writes, since nobody should be moving until we decrement the count.
2938 * We do need to hold the thread list because of JNI attaches.
2939 */
2940 dvmLockThreadList(self);
2941 lockThreadSuspendCount();
2942 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2943 if (thread == self)
2944 continue;
2945
2946 /* debugger events don't suspend JDWP thread */
2947 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2948 assert(thread->dbgSuspendCount == 0);
2949 continue;
2950 }
2951
2952 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002953 dvmAddToThreadSuspendCount(&thread->suspendCount,
2954 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002955 thread->dbgSuspendCount = 0;
2956 }
2957 unlockThreadSuspendCount();
2958 dvmUnlockThreadList();
2959
2960 /*
2961 * Broadcast a notification to all suspended threads, some or all of
2962 * which may choose to wake up. No need to wait for them.
2963 */
2964 lockThreadSuspendCount();
2965 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2966 assert(cc == 0);
2967 unlockThreadSuspendCount();
2968
2969 unlockThreadSuspend();
2970
2971 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2972}
2973
2974/*
2975 * Determine if a thread is suspended.
2976 *
2977 * As with all operations on foreign threads, the caller should hold
2978 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002979 *
2980 * If the thread is suspending or waking, these fields could be changing
2981 * out from under us (or the thread could change state right after we
2982 * examine it), making this generally unreliable. This is chiefly
2983 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002984 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002985bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002986{
2987 /*
2988 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07002989 * (1) Running happily. status is RUNNING, suspendCount is zero.
2990 * Return "false".
2991 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
2992 * Return "false".
2993 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002994 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07002995 * (4) Waking up. suspendCount is zero, status is SUSPENDED
2996 * Return "false" (since it could change out from under us, unless
2997 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002998 */
2999
Andy McFadden6dce9962010-08-23 16:45:24 -07003000 return (thread->suspendCount != 0 && thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003001}
3002
3003/*
3004 * Wait until another thread self-suspends. This is specifically for
3005 * synchronization between the JDWP thread and a thread that has decided
3006 * to suspend itself after sending an event to the debugger.
3007 *
3008 * Threads that encounter "suspend all" events work as well -- the thread
3009 * in question suspends everybody else and then itself.
3010 *
3011 * We can't hold a thread lock here or in the caller, because we could
3012 * get here just before the to-be-waited-for-thread issues a "suspend all".
3013 * There's an opportunity for badness if the thread we're waiting for exits
3014 * and gets cleaned up, but since the thread in question is processing a
3015 * debugger event, that's not really a possibility. (To avoid deadlock,
3016 * it's important that we not be in THREAD_RUNNING while we wait.)
3017 */
3018void dvmWaitForSuspend(Thread* thread)
3019{
3020 Thread* self = dvmThreadSelf();
3021
3022 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3023 self->threadId, thread->threadId);
3024
3025 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3026 assert(thread != self);
3027 assert(self->status != THREAD_RUNNING);
3028
3029 waitForThreadSuspend(self, thread);
3030
3031 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3032 self->threadId, thread->threadId);
3033}
3034
3035/*
3036 * Check to see if we need to suspend ourselves. If so, go to sleep on
3037 * a condition variable.
3038 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003039 * Returns "true" if we suspended ourselves.
3040 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003041static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003042{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003043 assert(self != NULL);
3044 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003045
Andy McFadden6dce9962010-08-23 16:45:24 -07003046 /*
3047 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
3048 * access to self->suspendCount.
3049 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003050 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3051
Andy McFadden6dce9962010-08-23 16:45:24 -07003052 bool needSuspend = (self->suspendCount != 0);
3053 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07003054 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07003055 ThreadStatus oldStatus = self->status; /* should be RUNNING */
3056 self->status = THREAD_SUSPENDED;
3057
Andy McFadden3469a7e2010-08-04 16:09:10 -07003058 while (self->suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003059 /*
3060 * Wait for wakeup signal, releasing lock. The act of releasing
3061 * and re-acquiring the lock provides the memory barriers we
3062 * need for correct behavior on SMP.
3063 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07003064 dvmWaitCond(&gDvm.threadSuspendCountCond,
3065 &gDvm.threadSuspendCountLock);
3066 }
3067 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07003068 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07003069 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3070 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003071 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003072
3073 unlockThreadSuspendCount();
3074
Andy McFadden6dce9962010-08-23 16:45:24 -07003075 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003076}
3077
3078/*
Andy McFadden6dce9962010-08-23 16:45:24 -07003079 * Check to see if a suspend is pending. If so, suspend the current
3080 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003081 */
3082bool dvmCheckSuspendPending(Thread* self)
3083{
Andy McFadden6dce9962010-08-23 16:45:24 -07003084 assert(self != NULL);
3085 if (self->suspendCount == 0) {
3086 return false;
3087 } else {
3088 return fullSuspendCheck(self);
3089 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003090}
3091
3092/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003093 * Update our status.
3094 *
3095 * The "self" argument, which may be NULL, is accepted as an optimization.
3096 *
3097 * Returns the old status.
3098 */
3099ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3100{
3101 ThreadStatus oldStatus;
3102
3103 if (self == NULL)
3104 self = dvmThreadSelf();
3105
3106 LOGVV("threadid=%d: (status %d -> %d)\n",
3107 self->threadId, self->status, newStatus);
3108
3109 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07003110 if (oldStatus == newStatus)
3111 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003112
3113 if (newStatus == THREAD_RUNNING) {
3114 /*
3115 * Change our status to THREAD_RUNNING. The transition requires
3116 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003117 * us to be "asleep" in all other states, and another thread could
3118 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003119 *
Andy McFadden6dce9962010-08-23 16:45:24 -07003120 * The order of operations is very significant here. One way to
3121 * do this wrong is:
3122 *
3123 * GCing thread Our thread (in NATIVE)
3124 * ------------ ----------------------
3125 * check suspend count (== 0)
3126 * dvmSuspendAllThreads()
3127 * grab suspend-count lock
3128 * increment all suspend counts
3129 * release suspend-count lock
3130 * check thread state (== NATIVE)
3131 * all are suspended, begin GC
3132 * set state to RUNNING
3133 * (continue executing)
3134 *
3135 * We can correct this by grabbing the suspend-count lock and
3136 * performing both of our operations (check suspend count, set
3137 * state) while holding it, now we need to grab a mutex on every
3138 * transition to RUNNING.
3139 *
3140 * What we do instead is change the order of operations so that
3141 * the transition to RUNNING happens first. If we then detect
3142 * that the suspend count is nonzero, we switch to SUSPENDED.
3143 *
3144 * Appropriate compiler and memory barriers are required to ensure
3145 * that the operations are observed in the expected order.
3146 *
3147 * This does create a small window of opportunity where a GC in
3148 * progress could observe what appears to be a running thread (if
3149 * it happens to look between when we set to RUNNING and when we
3150 * switch to SUSPENDED). At worst this only affects assertions
3151 * and thread logging. (We could work around it with some sort
3152 * of intermediate "pre-running" state that is generally treated
3153 * as equivalent to running, but that doesn't seem worthwhile.)
3154 *
3155 * We can also solve this by combining the "status" and "suspend
3156 * count" fields into a single 32-bit value. This trades the
3157 * store/load barrier on transition to RUNNING for an atomic RMW
3158 * op on all transitions and all suspend count updates (also, all
3159 * accesses to status or the thread count require bit-fiddling).
3160 * It also eliminates the brief transition through RUNNING when
3161 * the thread is supposed to be suspended. This is possibly faster
3162 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003163 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003164 android_atomic_acquire_store(newStatus, &self->status);
3165 if (self->suspendCount != 0) {
3166 fullSuspendCheck(self);
3167 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003168 } else {
3169 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003170 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003171 *
3172 * We use a releasing store to ensure that, if we were RUNNING,
3173 * any updates we previously made to objects on the managed heap
3174 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003175 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003176 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003177 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003178 }
3179
3180 return oldStatus;
3181}
3182
3183/*
3184 * Get a statically defined thread group from a field in the ThreadGroup
3185 * Class object. Expected arguments are "mMain" and "mSystem".
3186 */
3187static Object* getStaticThreadGroup(const char* fieldName)
3188{
3189 StaticField* groupField;
3190 Object* groupObj;
3191
3192 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3193 fieldName, "Ljava/lang/ThreadGroup;");
3194 if (groupField == NULL) {
3195 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3196 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3197 return NULL;
3198 }
3199 groupObj = dvmGetStaticFieldObject(groupField);
3200 if (groupObj == NULL) {
3201 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3202 dvmThrowException("Ljava/lang/InternalError;", NULL);
3203 return NULL;
3204 }
3205
3206 return groupObj;
3207}
3208Object* dvmGetSystemThreadGroup(void)
3209{
3210 return getStaticThreadGroup("mSystem");
3211}
3212Object* dvmGetMainThreadGroup(void)
3213{
3214 return getStaticThreadGroup("mMain");
3215}
3216
3217/*
3218 * Given a VMThread object, return the associated Thread*.
3219 *
3220 * NOTE: if the thread detaches, the struct Thread will disappear, and
3221 * we will be touching invalid data. For safety, lock the thread list
3222 * before calling this.
3223 */
3224Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3225{
3226 int vmData;
3227
3228 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003229
3230 if (false) {
3231 Thread* thread = gDvm.threadList;
3232 while (thread != NULL) {
3233 if ((Thread*)vmData == thread)
3234 break;
3235
3236 thread = thread->next;
3237 }
3238
3239 if (thread == NULL) {
3240 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3241 vmThreadObj, (Thread*)vmData);
3242 vmData = 0;
3243 }
3244 }
3245
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003246 return (Thread*) vmData;
3247}
3248
Andy McFadden2b94b302010-03-09 16:38:36 -08003249/*
3250 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003251 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003252 *
3253 * Returns NULL if the thread was not found.
3254 */
3255Thread* dvmGetThreadByHandle(pthread_t handle)
3256{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003257 Thread* thread;
3258 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003259 if (thread->handle == handle)
3260 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003261 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003262 return thread;
3263}
Andy McFadden2b94b302010-03-09 16:38:36 -08003264
Andy McFadden0a24ef92010-03-12 13:39:59 -08003265/*
3266 * Given a threadId, return the associated Thread*.
3267 * Caller must hold the thread list lock.
3268 *
3269 * Returns NULL if the thread was not found.
3270 */
3271Thread* dvmGetThreadByThreadId(u4 threadId)
3272{
3273 Thread* thread;
3274 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3275 if (thread->threadId == threadId)
3276 break;
3277 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003278 return thread;
3279}
3280
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003281
3282/*
3283 * Conversion map for "nice" values.
3284 *
3285 * We use Android thread priority constants to be consistent with the rest
3286 * of the system. In some cases adjacent entries may overlap.
3287 */
3288static const int kNiceValues[10] = {
3289 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3290 ANDROID_PRIORITY_BACKGROUND + 6,
3291 ANDROID_PRIORITY_BACKGROUND + 3,
3292 ANDROID_PRIORITY_BACKGROUND,
3293 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3294 ANDROID_PRIORITY_NORMAL - 2,
3295 ANDROID_PRIORITY_NORMAL - 4,
3296 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3297 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3298 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3299};
3300
3301/*
3302 * Change the priority of a system thread to match that of the Thread object.
3303 *
3304 * We map a priority value from 1-10 to Linux "nice" values, where lower
3305 * numbers indicate higher priority.
3306 */
3307void dvmChangeThreadPriority(Thread* thread, int newPriority)
3308{
3309 pid_t pid = thread->systemTid;
3310 int newNice;
3311
3312 if (newPriority < 1 || newPriority > 10) {
3313 LOGW("bad priority %d\n", newPriority);
3314 newPriority = 5;
3315 }
3316 newNice = kNiceValues[newPriority-1];
3317
Andy McFaddend62c0b52009-08-04 15:02:12 -07003318 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003319 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003320 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003321 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003322 }
3323
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003324 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3325 char* str = dvmGetThreadName(thread);
3326 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3327 pid, str, newPriority, newNice, strerror(errno));
3328 free(str);
3329 } else {
3330 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3331 pid, newPriority, newNice);
3332 }
3333}
3334
3335/*
3336 * Get the thread priority for the current thread by querying the system.
3337 * This is useful when attaching a thread through JNI.
3338 *
3339 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3340 */
3341static int getThreadPriorityFromSystem(void)
3342{
3343 int i, sysprio, jprio;
3344
3345 errno = 0;
3346 sysprio = getpriority(PRIO_PROCESS, 0);
3347 if (sysprio == -1 && errno != 0) {
3348 LOGW("getpriority() failed: %s\n", strerror(errno));
3349 return THREAD_NORM_PRIORITY;
3350 }
3351
3352 jprio = THREAD_MIN_PRIORITY;
3353 for (i = 0; i < NELEM(kNiceValues); i++) {
3354 if (sysprio >= kNiceValues[i])
3355 break;
3356 jprio++;
3357 }
3358 if (jprio > THREAD_MAX_PRIORITY)
3359 jprio = THREAD_MAX_PRIORITY;
3360
3361 return jprio;
3362}
3363
3364
3365/*
3366 * Return true if the thread is on gDvm.threadList.
3367 * Caller should not hold gDvm.threadListLock.
3368 */
3369bool dvmIsOnThreadList(const Thread* thread)
3370{
3371 bool ret = false;
3372
3373 dvmLockThreadList(NULL);
3374 if (thread == gDvm.threadList) {
3375 ret = true;
3376 } else {
3377 ret = thread->prev != NULL || thread->next != NULL;
3378 }
3379 dvmUnlockThreadList();
3380
3381 return ret;
3382}
3383
3384/*
3385 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3386 * output target.
3387 */
3388void dvmDumpThread(Thread* thread, bool isRunning)
3389{
3390 DebugOutputTarget target;
3391
3392 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3393 dvmDumpThreadEx(&target, thread, isRunning);
3394}
3395
3396/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003397 * Try to get the scheduler group.
3398 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003399 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003400 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003401 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003402 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003403 * We return the part on the "cpu" line after the '/', which will be an
3404 * empty string for the default cgroup. If the string is longer than
3405 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003406 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003407 * On error, -1 is returned, and an error description will be stored in
3408 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003409 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003410static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003411{
3412#ifdef HAVE_ANDROID_OS
3413 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003414 char lineBuf[256];
3415 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003416
Andy McFadden7f64ede2010-03-03 15:37:10 -08003417 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003418 if ((fp = fopen(pathBuf, "r")) == NULL) {
3419 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003420 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003421 }
3422
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003423 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3424 char* subsys;
3425 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003426 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003427
Andy McFadden7f64ede2010-03-03 15:37:10 -08003428 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003429 subsys = strchr(lineBuf, ':');
3430 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003431 goto out_bad_data;
3432 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003433
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003434 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003435 /* Not the subsys we're looking for */
3436 continue;
3437 }
3438
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003439 grp = strchr(subsys, '/');
3440 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003441 goto out_bad_data;
3442 }
3443 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003444
Andy McFadden7f64ede2010-03-03 15:37:10 -08003445 len = strlen(grp);
3446 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3447
3448 if (bufLen <= len) {
3449 len = bufLen - 1;
3450 }
3451 strncpy(buf, grp, len);
3452 buf[len] = '\0';
3453 fclose(fp);
3454 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003455 }
3456
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003457 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003458 fclose(fp);
3459 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003460
3461out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003462 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003463 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003464 fclose(fp);
3465 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003466
Andy McFaddend62c0b52009-08-04 15:02:12 -07003467#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003468 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003469 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003470#endif
3471}
3472
3473/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003474 * Convert ThreadStatus to a string.
3475 */
3476const char* dvmGetThreadStatusStr(ThreadStatus status)
3477{
3478 switch (status) {
3479 case THREAD_ZOMBIE: return "ZOMBIE";
3480 case THREAD_RUNNING: return "RUNNABLE";
3481 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3482 case THREAD_MONITOR: return "MONITOR";
3483 case THREAD_WAIT: return "WAIT";
3484 case THREAD_INITIALIZING: return "INITIALIZING";
3485 case THREAD_STARTING: return "STARTING";
3486 case THREAD_NATIVE: return "NATIVE";
3487 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003488 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003489 default: return "UNKNOWN";
3490 }
3491}
3492
3493/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003494 * Print information about the specified thread.
3495 *
3496 * Works best when the thread in question is "self" or has been suspended.
3497 * When dumping a separate thread that's still running, set "isRunning" to
3498 * use a more cautious thread dump function.
3499 */
3500void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3501 bool isRunning)
3502{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003503 Object* threadObj;
3504 Object* groupObj;
3505 StringObject* nameStr;
3506 char* threadName = NULL;
3507 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003508 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003509 bool isDaemon;
3510 int priority; // java.lang.Thread priority
3511 int policy; // pthread policy
3512 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003513 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003514
Andy McFaddene3346d82010-06-02 15:37:21 -07003515 /*
3516 * Get the java.lang.Thread object. This function gets called from
3517 * some weird debug contexts, so it's possible that there's a GC in
3518 * progress on some other thread. To decrease the chances of the
3519 * thread object being moved out from under us, we add the reference
3520 * to the tracked allocation list, which pins it in place.
3521 *
3522 * If threadObj is NULL, the thread is still in the process of being
3523 * attached to the VM, and there's really nothing interesting to
3524 * say about it yet.
3525 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003526 threadObj = thread->threadObj;
3527 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003528 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003529 return;
3530 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003531 dvmAddTrackedAlloc(threadObj, NULL);
3532
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003533 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3534 gDvm.offJavaLangThread_name);
3535 threadName = dvmCreateCstrFromString(nameStr);
3536
3537 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3538 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3539
3540 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3541 LOGW("Warning: pthread_getschedparam failed\n");
3542 policy = -1;
3543 sp.sched_priority = -1;
3544 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003545 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003546 sizeof(schedulerGroupBuf)) == 0 &&
3547 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003548 strcpy(schedulerGroupBuf, "default");
3549 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003550
3551 /* a null value for group is not expected, but deal with it anyway */
3552 groupObj = (Object*) dvmGetFieldObject(threadObj,
3553 gDvm.offJavaLangThread_group);
3554 if (groupObj != NULL) {
3555 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3556 "name", "Ljava/lang/String;");
3557 if (offset < 0) {
3558 LOGW("Unable to find 'name' field in ThreadGroup\n");
3559 } else {
3560 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3561 groupName = dvmCreateCstrFromString(nameStr);
3562 }
3563 }
3564 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003565 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003566
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003567 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003568 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003569 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003570 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3571#if defined(WITH_JIT)
3572 thread->inJitCodeCache ? " JIT" : ""
3573#else
3574 ""
3575#endif
3576 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003577 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003578 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003579 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07003580 thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003581 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003582 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003583 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003584 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003585
Andy McFadden0a3f6982010-08-31 13:50:08 -07003586 /* get some bits from /proc/self/stat */
3587 ProcStatData procStatData;
3588 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3589 /* failed, use zeroed values */
3590 memset(&procStatData, 0, sizeof(procStatData));
3591 }
3592
3593 /* grab the scheduler stats for this thread */
3594 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3595 thread->systemTid);
3596 int schedstatFd = open(schedstatBuf, O_RDONLY);
3597 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003598 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003599 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003600 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3601 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003602 if (bytes >= 1) {
3603 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003604 }
3605 }
3606
Andy McFadden0a3f6982010-08-31 13:50:08 -07003607 /* show what we got */
3608 dvmPrintDebugMessage(target,
3609 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3610 schedstatBuf, procStatData.utime, procStatData.stime,
3611 procStatData.processor);
3612
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003613#ifdef WITH_MONITOR_TRACKING
3614 if (!isRunning) {
3615 LockedObjectData* lod = thread->pLockedObjects;
3616 if (lod != NULL)
3617 dvmPrintDebugMessage(target, " | monitors held:\n");
3618 else
3619 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3620 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003621 Object* obj = lod->obj;
3622 if (obj->clazz == gDvm.classJavaLangClass) {
3623 ClassObject* clazz = (ClassObject*) obj;
3624 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3625 obj, lod->recursionCount, obj->clazz->descriptor,
3626 clazz->descriptor);
3627 } else {
3628 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3629 obj, lod->recursionCount, obj->clazz->descriptor);
3630 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003631 lod = lod->next;
3632 }
3633 }
3634#endif
3635
3636 if (isRunning)
3637 dvmDumpRunningThreadStack(target, thread);
3638 else
3639 dvmDumpThreadStack(target, thread);
3640
Andy McFaddene3346d82010-06-02 15:37:21 -07003641 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003642 free(threadName);
3643 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003644}
3645
3646/*
3647 * Get the name of a thread.
3648 *
3649 * For correctness, the caller should hold the thread list lock to ensure
3650 * that the thread doesn't go away mid-call.
3651 *
3652 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3653 */
3654char* dvmGetThreadName(Thread* thread)
3655{
3656 StringObject* nameObj;
3657
3658 if (thread->threadObj == NULL) {
3659 LOGW("threadObj is NULL, name not available\n");
3660 return strdup("-unknown-");
3661 }
3662
3663 nameObj = (StringObject*)
3664 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3665 return dvmCreateCstrFromString(nameObj);
3666}
3667
3668/*
3669 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3670 * an output target.
3671 */
3672void dvmDumpAllThreads(bool grabLock)
3673{
3674 DebugOutputTarget target;
3675
3676 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3677 dvmDumpAllThreadsEx(&target, grabLock);
3678}
3679
3680/*
3681 * Print information about all known threads. Assumes they have been
3682 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3683 *
3684 * If "grabLock" is true, we grab the thread lock list. This is important
3685 * to do unless the caller already holds the lock.
3686 */
3687void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3688{
3689 Thread* thread;
3690
3691 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3692
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003693#ifdef HAVE_ANDROID_OS
3694 dvmPrintDebugMessage(target,
3695 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3696 gDvm.threadListLock.value,
3697 gDvm._threadSuspendLock.value,
3698 gDvm.threadSuspendCountLock.value,
3699 gDvm.gcHeapLock.value,
3700 gDvm.heapWorkerLock.value,
3701 gDvm.heapWorkerListLock.value);
3702#endif
3703
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003704 if (grabLock)
3705 dvmLockThreadList(dvmThreadSelf());
3706
3707 thread = gDvm.threadList;
3708 while (thread != NULL) {
3709 dvmDumpThreadEx(target, thread, false);
3710
3711 /* verify link */
3712 assert(thread->next == NULL || thread->next->prev == thread);
3713
3714 thread = thread->next;
3715 }
3716
3717 if (grabLock)
3718 dvmUnlockThreadList();
3719}
3720
Andy McFadden384ef6b2010-03-15 17:24:55 -07003721/*
3722 * Nuke the target thread from orbit.
3723 *
3724 * The idea is to send a "crash" signal to the target thread so that
3725 * debuggerd will take notice and dump an appropriate stack trace.
3726 * Because of the way debuggerd works, we have to throw the same signal
3727 * at it twice.
3728 *
3729 * This does not necessarily cause the entire process to stop, but once a
3730 * thread has been nuked the rest of the system is likely to be unstable.
3731 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003732 * performed, but it's advisable (and expected) to call dvmAbort soon.
3733 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003734 */
3735void dvmNukeThread(Thread* thread)
3736{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003737 int killResult;
3738
Andy McFaddena388a162010-03-18 16:27:14 -07003739 /* suppress the heapworker watchdog to assist anyone using a debugger */
3740 gDvm.nativeDebuggerActive = true;
3741
Andy McFadden384ef6b2010-03-15 17:24:55 -07003742 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003743 * Send the signals, separated by a brief interval to allow debuggerd
3744 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3745 * can be used instead of SIGSEGV to avoid making it look like the
3746 * code actually crashed at the current point of execution.
3747 *
3748 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3749 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3750 * you don't get the second stack trace; possibly something in the
3751 * kernel decides that a signal has already been sent and it's time
3752 * to just kill the process. The position in the current thread is
3753 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003754 *
Andy McFaddena388a162010-03-18 16:27:14 -07003755 * The target thread can continue to execute between the two signals.
3756 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003757 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003758 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3759 " cause debuggerd dump\n",
3760 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003761 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3762 if (killResult != 0) {
3763 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3764 }
Andy McFaddena388a162010-03-18 16:27:14 -07003765 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003766 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3767 if (killResult != 0) {
3768 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3769 }
Andy McFadden7122d862010-03-19 15:18:57 -07003770 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003771 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003772
3773 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3774 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003775 LOGD("Continuing\n");
3776}
3777
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003778#ifdef WITH_MONITOR_TRACKING
3779/*
3780 * Count up the #of locked objects in the current thread.
3781 */
3782static int getThreadObjectCount(const Thread* self)
3783{
3784 LockedObjectData* lod;
3785 int count = 0;
3786
3787 lod = self->pLockedObjects;
3788 while (lod != NULL) {
3789 count++;
3790 lod = lod->next;
3791 }
3792 return count;
3793}
3794
3795/*
3796 * Add the object to the thread's locked object list if it doesn't already
3797 * exist. The most recently added object is the most likely to be released
3798 * next, so we insert at the head of the list.
3799 *
3800 * If it already exists, we increase the recursive lock count.
3801 *
3802 * The object's lock may be thin or fat.
3803 */
3804void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3805{
3806 LockedObjectData* newLod;
3807 LockedObjectData* lod;
3808 int* trace;
3809 int depth;
3810
3811 lod = self->pLockedObjects;
3812 while (lod != NULL) {
3813 if (lod->obj == obj) {
3814 lod->recursionCount++;
3815 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3816 return;
3817 }
3818 lod = lod->next;
3819 }
3820
3821 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3822 if (newLod == NULL) {
3823 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3824 return;
3825 }
3826 newLod->obj = obj;
3827 newLod->recursionCount = 0;
3828
3829 if (withTrace) {
3830 trace = dvmFillInStackTraceRaw(self, &depth);
3831 newLod->rawStackTrace = trace;
3832 newLod->stackDepth = depth;
3833 }
3834
3835 newLod->next = self->pLockedObjects;
3836 self->pLockedObjects = newLod;
3837
3838 LOGV("+++ threadid=%d: added %p, now %d\n",
3839 self->threadId, newLod, getThreadObjectCount(self));
3840}
3841
3842/*
3843 * Remove the object from the thread's locked object list. If the entry
3844 * has a nonzero recursion count, we just decrement the count instead.
3845 */
3846void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3847{
3848 LockedObjectData* lod;
3849 LockedObjectData* prevLod;
3850
3851 lod = self->pLockedObjects;
3852 prevLod = NULL;
3853 while (lod != NULL) {
3854 if (lod->obj == obj) {
3855 if (lod->recursionCount > 0) {
3856 lod->recursionCount--;
3857 LOGV("+++ -recursive lock %p -> %d\n",
3858 obj, lod->recursionCount);
3859 return;
3860 } else {
3861 break;
3862 }
3863 }
3864 prevLod = lod;
3865 lod = lod->next;
3866 }
3867
3868 if (lod == NULL) {
3869 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3870 return;
3871 }
3872 if (prevLod == NULL) {
3873 /* first item in list */
3874 assert(self->pLockedObjects == lod);
3875 self->pLockedObjects = lod->next;
3876 } else {
3877 /* middle/end of list */
3878 prevLod->next = lod->next;
3879 }
3880
3881 LOGV("+++ threadid=%d: removed %p, now %d\n",
3882 self->threadId, lod, getThreadObjectCount(self));
3883 free(lod->rawStackTrace);
3884 free(lod);
3885}
3886
3887/*
3888 * If the specified object is already in the thread's locked object list,
3889 * return the LockedObjectData struct. Otherwise return NULL.
3890 */
3891LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3892{
3893 LockedObjectData* lod;
3894
3895 lod = self->pLockedObjects;
3896 while (lod != NULL) {
3897 if (lod->obj == obj)
3898 return lod;
3899 lod = lod->next;
3900 }
3901 return NULL;
3902}
3903#endif /*WITH_MONITOR_TRACKING*/
3904
3905
3906/*
3907 * GC helper functions
3908 */
3909
The Android Open Source Project99409882009-03-18 22:20:24 -07003910/*
3911 * Add the contents of the registers from the interpreted call stack.
3912 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003913static void gcScanInterpStackReferences(Thread *thread)
3914{
3915 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003916#if WITH_EXTRA_GC_CHECKS > 1
3917 bool first = true;
3918#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003919
3920 framePtr = (const u4 *)thread->curFrame;
3921 while (framePtr != NULL) {
3922 const StackSaveArea *saveArea;
3923 const Method *method;
3924
3925 saveArea = SAVEAREA_FROM_FP(framePtr);
3926 method = saveArea->method;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003927 if (method != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003928#ifdef COUNT_PRECISE_METHODS
3929 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003930 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3931 LOGI("PGC: added %s.%s %p\n",
3932 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003933#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003934#if WITH_EXTRA_GC_CHECKS > 1
3935 /*
3936 * May also want to enable the memset() in the "invokeMethod"
3937 * goto target in the portable interpreter. That sets the stack
3938 * to a pattern that makes referring to uninitialized data
3939 * very obvious.
3940 */
3941
3942 if (first) {
3943 /*
3944 * First frame, isn't native, check the "alternate" saved PC
3945 * as a sanity check.
3946 *
3947 * It seems like we could check the second frame if the first
3948 * is native, since the PCs should be the same. It turns out
3949 * this doesn't always work. The problem is that we could
3950 * have calls in the sequence:
3951 * interp method #2
3952 * native method
3953 * interp method #1
3954 *
3955 * and then GC while in the native method after returning
3956 * from interp method #2. The currentPc on the stack is
3957 * for interp method #1, but thread->currentPc2 is still
3958 * set for the last thing interp method #2 did.
3959 *
3960 * This can also happen in normal execution:
3961 * - sget-object on not-yet-loaded class
3962 * - class init updates currentPc2
3963 * - static field init is handled by parsing annotations;
3964 * static String init requires creation of a String object,
3965 * which can cause a GC
3966 *
3967 * Essentially, any pattern that involves executing
3968 * interpreted code and then causes an allocation without
3969 * executing instructions in the original method will hit
3970 * this. These are rare enough that the test still has
3971 * some value.
3972 */
3973 if (saveArea->xtra.currentPc != thread->currentPc2) {
3974 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3975 saveArea->xtra.currentPc, thread->currentPc2,
3976 method->clazz->descriptor, method->name, method->insns);
3977 if (saveArea->xtra.currentPc != NULL)
3978 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3979 if (thread->currentPc2 != NULL)
3980 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3981 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003982 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003983 } else {
3984 /*
3985 * It's unusual, but not impossible, for a non-first frame
3986 * to be at something other than a method invocation. For
3987 * example, if we do a new-instance on a nonexistent class,
3988 * we'll have a lot of class loader activity on the stack
3989 * above the frame with the "new" operation. Could also
3990 * happen while we initialize a Throwable when an instruction
3991 * fails.
3992 *
3993 * So there's not much we can do here to verify the PC,
3994 * except to verify that it's a GC point.
3995 */
3996 }
3997 assert(saveArea->xtra.currentPc != NULL);
3998#endif
3999
4000 const RegisterMap* pMap;
4001 const u1* regVector;
4002 int i;
4003
Andy McFaddencf8b55c2009-04-13 15:26:03 -07004004 Method* nonConstMethod = (Method*) method; // quiet gcc
4005 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07004006 if (pMap != NULL) {
4007 /* found map, get registers for this address */
4008 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07004009 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07004010 if (regVector == NULL) {
4011 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
4012 method->clazz->descriptor, method->name, addr);
4013 } else {
4014 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
4015 method->clazz->descriptor, method->name, addr,
4016 thread->threadId);
4017 }
4018 } else {
4019 /*
4020 * No map found. If precise GC is disabled this is
4021 * expected -- we don't create pointers to the map data even
4022 * if it's present -- but if it's enabled it means we're
4023 * unexpectedly falling back on a conservative scan, so it's
4024 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07004025 */
4026 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07004027 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07004028 method->clazz->descriptor, method->name);
4029 }
4030 regVector = NULL;
4031 }
4032
4033 if (regVector == NULL) {
4034 /* conservative scan */
4035 for (i = method->registersSize - 1; i >= 0; i--) {
4036 u4 rval = *framePtr++;
4037 if (rval != 0 && (rval & 0x3) == 0) {
4038 dvmMarkIfObject((Object *)rval);
4039 }
4040 }
4041 } else {
4042 /*
4043 * Precise scan. v0 is at the lowest address on the
4044 * interpreted stack, and is the first bit in the register
4045 * vector, so we can walk through the register map and
4046 * memory in the same direction.
4047 *
4048 * A '1' bit indicates a live reference.
4049 */
4050 u2 bits = 1 << 1;
4051 for (i = method->registersSize - 1; i >= 0; i--) {
4052 u4 rval = *framePtr++;
4053
4054 bits >>= 1;
4055 if (bits == 1) {
4056 /* set bit 9 so we can tell when we're empty */
4057 bits = *regVector++ | 0x0100;
4058 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
4059 }
4060
4061 if (rval != 0 && (bits & 0x01) != 0) {
4062 /*
4063 * Non-null, register marked as live reference. This
4064 * should always be a valid object.
4065 */
4066#if WITH_EXTRA_GC_CHECKS > 0
4067 if ((rval & 0x3) != 0 ||
4068 !dvmIsValidObject((Object*) rval))
4069 {
4070 /* this is very bad */
4071 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
4072 method->registersSize-1 - i, rval);
4073 } else
4074#endif
4075 {
4076 dvmMarkObjectNonNull((Object *)rval);
4077 }
4078 } else {
4079 /*
4080 * Null or non-reference, do nothing at all.
4081 */
4082#if WITH_EXTRA_GC_CHECKS > 1
4083 if (dvmIsValidObject((Object*) rval)) {
4084 /* this is normal, but we feel chatty */
4085 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
4086 method->registersSize-1 - i, rval);
4087 }
4088#endif
4089 }
4090 }
4091 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004092 }
4093 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004094
The Android Open Source Project99409882009-03-18 22:20:24 -07004095#if WITH_EXTRA_GC_CHECKS > 1
4096 first = false;
4097#endif
4098
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004099 /* Don't fall into an infinite loop if things get corrupted.
4100 */
4101 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
4102 saveArea->prevFrame == NULL);
4103 framePtr = saveArea->prevFrame;
4104 }
4105}
4106
4107static void gcScanReferenceTable(ReferenceTable *refTable)
4108{
4109 Object **op;
4110
4111 //TODO: these asserts are overkill; turn them off when things stablize.
4112 assert(refTable != NULL);
4113 assert(refTable->table != NULL);
4114 assert(refTable->nextEntry != NULL);
4115 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
4116 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
4117
4118 op = refTable->table;
4119 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
4120 dvmMarkObjectNonNull(*(op++));
4121 }
4122}
4123
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004124#ifdef USE_INDIRECT_REF
Andy McFaddend5ab7262009-08-25 07:19:34 -07004125static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
4126{
4127 Object** op = pRefTable->table;
4128 int numEntries = dvmIndirectRefTableEntries(pRefTable);
4129 int i;
4130
4131 for (i = 0; i < numEntries; i++) {
4132 Object* obj = *op;
4133 if (obj != NULL)
4134 dvmMarkObjectNonNull(obj);
4135 op++;
4136 }
4137}
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004138#endif
Andy McFaddend5ab7262009-08-25 07:19:34 -07004139
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004140/*
4141 * Scan a Thread and mark any objects it references.
4142 */
4143static void gcScanThread(Thread *thread)
4144{
4145 assert(thread != NULL);
4146
4147 /*
4148 * The target thread must be suspended or in a state where it can't do
4149 * any harm (e.g. in Object.wait()). The only exception is the current
4150 * thread, which will still be active and in the "running" state.
4151 *
Andy McFadden6dce9962010-08-23 16:45:24 -07004152 * It's possible to encounter a false-positive here because a thread
4153 * transitioning to running from (say) vmwait or native will briefly
4154 * set their status to running before switching to suspended. This
4155 * is highly unlikely, but does mean that we don't want to abort if
4156 * the situation arises.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004157 */
Andy McFadden6dce9962010-08-23 16:45:24 -07004158 if (thread->status == THREAD_RUNNING && thread != dvmThreadSelf()) {
Andy McFaddend40223e2009-12-07 15:35:51 -08004159 Thread* self = dvmThreadSelf();
Andy McFadden6dce9962010-08-23 16:45:24 -07004160 LOGW("threadid=%d: Warning: GC scanning a running thread (%d)\n",
Andy McFaddend40223e2009-12-07 15:35:51 -08004161 self->threadId, thread->threadId);
4162 dvmDumpThread(thread, true);
4163 LOGW("Found by:\n");
4164 dvmDumpThread(self, false);
4165
Andy McFadden6dce9962010-08-23 16:45:24 -07004166 /* continue anyway */
Andy McFaddend40223e2009-12-07 15:35:51 -08004167 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004168
4169 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
4170
4171 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
4172
4173 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
4174
4175 dvmMarkObject(thread->exception); // usually NULL
4176 gcScanReferenceTable(&thread->internalLocalRefTable);
4177
4178 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
4179
Andy McFaddend5ab7262009-08-25 07:19:34 -07004180#ifdef USE_INDIRECT_REF
4181 gcScanIndirectRefTable(&thread->jniLocalRefTable);
4182#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004183 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07004184#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004185
4186 if (thread->jniMonitorRefTable.table != NULL) {
4187 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
4188
4189 gcScanReferenceTable(&thread->jniMonitorRefTable);
4190 }
4191
4192 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
4193
4194 gcScanInterpStackReferences(thread);
4195
4196 HPROF_CLEAR_GC_SCAN_STATE();
4197}
4198
4199static void gcScanAllThreads()
4200{
4201 Thread *thread;
4202
4203 /* Lock the thread list so we can safely use the
4204 * next/prev pointers.
4205 */
4206 dvmLockThreadList(dvmThreadSelf());
4207
4208 for (thread = gDvm.threadList; thread != NULL;
4209 thread = thread->next)
4210 {
4211 /* We need to scan our own stack, so don't special-case
4212 * the current thread.
4213 */
4214 gcScanThread(thread);
4215 }
4216
4217 dvmUnlockThreadList();
4218}
4219
4220void dvmGcScanRootThreadGroups()
4221{
4222 /* We scan the VM's list of threads instead of going
4223 * through the actual ThreadGroups, but it should be
4224 * equivalent.
4225 *
Jeff Hao97319a82009-08-12 16:57:15 -07004226 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004227 * the root set, which should always be true; it's
4228 * loaded by the built-in class loader, which is part
4229 * of the root set.
4230 */
4231 gcScanAllThreads();
4232}