blob: b340f0bb7e4c451f78cdbd29a47473e2552d7e0a [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/*
buzbeecb3081f2011-01-14 13:37:31 -0800246 * If there is any thread suspend request outstanding,
247 * we need to mark it in interpState to signal the interpreter that
248 * something is pending. We do this by maintaining a global sum of
249 * all threads' suspend counts. All suspendCount updates should go
250 * through this after aquiring threadSuspendCountLock.
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700251 */
buzbeecb3081f2011-01-14 13:37:31 -0800252static void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700253{
254 *pSuspendCount += delta;
255 gDvm.sumThreadSuspendCount += delta;
buzbeecb3081f2011-01-14 13:37:31 -0800256 dvmUpdateInterpBreak(kSubModeSuspendRequest,
257 (gDvm.sumThreadSuspendCount != 0));
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700258}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800259
260/*
261 * Initialize thread list and main thread's environment. We need to set
262 * up some basic stuff so that dvmThreadSelf() will work when we start
263 * loading classes (e.g. to check for exceptions).
264 */
265bool dvmThreadStartup(void)
266{
267 Thread* thread;
268
269 /* allocate a TLS slot */
270 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
271 LOGE("ERROR: pthread_key_create failed\n");
272 return false;
273 }
274
275 /* test our pthread lib */
276 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
277 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
278
279 /* prep thread-related locks and conditions */
280 dvmInitMutex(&gDvm.threadListLock);
281 pthread_cond_init(&gDvm.threadStartCond, NULL);
282 //dvmInitMutex(&gDvm.vmExitLock);
283 pthread_cond_init(&gDvm.vmExitCond, NULL);
284 dvmInitMutex(&gDvm._threadSuspendLock);
285 dvmInitMutex(&gDvm.threadSuspendCountLock);
286 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800287
288 /*
289 * Dedicated monitor for Thread.sleep().
290 * TODO: change this to an Object* so we don't have to expose this
291 * call, and we interact better with JDWP monitor calls. Requires
292 * deferring the object creation to much later (e.g. final "main"
293 * thread prep) or until first use.
294 */
295 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
296
297 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
298
299 thread = allocThread(gDvm.stackSize);
300 if (thread == NULL)
301 return false;
302
303 /* switch mode for when we run initializers */
304 thread->status = THREAD_RUNNING;
305
306 /*
307 * We need to assign the threadId early so we can lock/notify
308 * object monitors. We'll set the "threadObj" field later.
309 */
310 prepareThread(thread);
311 gDvm.threadList = thread;
312
313#ifdef COUNT_PRECISE_METHODS
314 gDvm.preciseMethods = dvmPointerSetAlloc(200);
315#endif
316
317 return true;
318}
319
320/*
321 * We're a little farther up now, and can load some basic classes.
322 *
323 * We're far enough along that we can poke at java.lang.Thread and friends,
324 * but should not assume that static initializers have run (or cause them
325 * to do so). That means no object allocations yet.
326 */
327bool dvmThreadObjStartup(void)
328{
329 /*
330 * Cache the locations of these classes. It's likely that we're the
331 * first to reference them, so they're being loaded now.
332 */
333 gDvm.classJavaLangThread =
334 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
335 gDvm.classJavaLangVMThread =
336 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
337 gDvm.classJavaLangThreadGroup =
338 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
339 if (gDvm.classJavaLangThread == NULL ||
340 gDvm.classJavaLangThreadGroup == NULL ||
341 gDvm.classJavaLangThreadGroup == NULL)
342 {
343 LOGE("Could not find one or more essential thread classes\n");
344 return false;
345 }
346
347 /*
348 * Cache field offsets. This makes things a little faster, at the
349 * expense of hard-coding non-public field names into the VM.
350 */
351 gDvm.offJavaLangThread_vmThread =
352 dvmFindFieldOffset(gDvm.classJavaLangThread,
353 "vmThread", "Ljava/lang/VMThread;");
354 gDvm.offJavaLangThread_group =
355 dvmFindFieldOffset(gDvm.classJavaLangThread,
356 "group", "Ljava/lang/ThreadGroup;");
357 gDvm.offJavaLangThread_daemon =
358 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
359 gDvm.offJavaLangThread_name =
360 dvmFindFieldOffset(gDvm.classJavaLangThread,
361 "name", "Ljava/lang/String;");
362 gDvm.offJavaLangThread_priority =
363 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
364
365 if (gDvm.offJavaLangThread_vmThread < 0 ||
366 gDvm.offJavaLangThread_group < 0 ||
367 gDvm.offJavaLangThread_daemon < 0 ||
368 gDvm.offJavaLangThread_name < 0 ||
369 gDvm.offJavaLangThread_priority < 0)
370 {
371 LOGE("Unable to find all fields in java.lang.Thread\n");
372 return false;
373 }
374
375 gDvm.offJavaLangVMThread_thread =
376 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
377 "thread", "Ljava/lang/Thread;");
378 gDvm.offJavaLangVMThread_vmData =
379 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
380 if (gDvm.offJavaLangVMThread_thread < 0 ||
381 gDvm.offJavaLangVMThread_vmData < 0)
382 {
383 LOGE("Unable to find all fields in java.lang.VMThread\n");
384 return false;
385 }
386
387 /*
388 * Cache the vtable offset for "run()".
389 *
390 * We don't want to keep the Method* because then we won't find see
391 * methods defined in subclasses.
392 */
393 Method* meth;
394 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
395 if (meth == NULL) {
396 LOGE("Unable to find run() in java.lang.Thread\n");
397 return false;
398 }
399 gDvm.voffJavaLangThread_run = meth->methodIndex;
400
401 /*
402 * Cache vtable offsets for ThreadGroup methods.
403 */
404 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
405 "removeThread", "(Ljava/lang/Thread;)V");
406 if (meth == NULL) {
407 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
408 return false;
409 }
410 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
411
412 return true;
413}
414
415/*
416 * All threads should be stopped by now. Clean up some thread globals.
417 */
418void dvmThreadShutdown(void)
419{
420 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700421 /*
422 * If we walk through the thread list and try to free the
423 * lingering thread structures (which should only be for daemon
424 * threads), the daemon threads may crash if they execute before
425 * the process dies. Let them leak.
426 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800427 freeThread(gDvm.threadList);
428 gDvm.threadList = NULL;
429 }
430
431 dvmFreeBitVector(gDvm.threadIdMap);
432
433 dvmFreeMonitorList();
434
435 pthread_key_delete(gDvm.pthreadKeySelf);
436}
437
438
439/*
440 * Grab the suspend count global lock.
441 */
442static inline void lockThreadSuspendCount(void)
443{
444 /*
445 * Don't try to change to VMWAIT here. When we change back to RUNNING
446 * we have to check for a pending suspend, which results in grabbing
447 * this lock recursively. Doesn't work with "fast" pthread mutexes.
448 *
449 * This lock is always held for very brief periods, so as long as
450 * mutex ordering is respected we shouldn't stall.
451 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700452 dvmLockMutex(&gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800453}
454
455/*
456 * Release the suspend count global lock.
457 */
458static inline void unlockThreadSuspendCount(void)
459{
460 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
461}
462
463/*
464 * Grab the thread list global lock.
465 *
466 * This is held while "suspend all" is trying to make everybody stop. If
467 * the shutdown is in progress, and somebody tries to grab the lock, they'll
468 * have to wait for the GC to finish. Therefore it's important that the
469 * thread not be in RUNNING mode.
470 *
471 * We don't have to check to see if we should be suspended once we have
472 * the lock. Nobody can suspend all threads without holding the thread list
473 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700474 *
Andy McFadden3469a7e2010-08-04 16:09:10 -0700475 * This function deliberately avoids the use of dvmChangeStatus(),
476 * which could grab threadSuspendCountLock. To avoid deadlock, threads
477 * are required to grab the thread list lock before the thread suspend
478 * count lock. (See comment in DvmGlobals.)
479 *
Andy McFadden44860362009-08-06 17:56:14 -0700480 * TODO: consider checking for suspend after acquiring the lock, and
481 * backing off if set. As stated above, it can't happen during normal
482 * execution, but it *can* happen during shutdown when daemon threads
483 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800484 */
485void dvmLockThreadList(Thread* self)
486{
487 ThreadStatus oldStatus;
488
489 if (self == NULL) /* try to get it from TLS */
490 self = dvmThreadSelf();
491
492 if (self != NULL) {
493 oldStatus = self->status;
494 self->status = THREAD_VMWAIT;
495 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700496 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800497 //LOGW("NULL self in dvmLockThreadList\n");
498 oldStatus = -1; // shut up gcc
499 }
500
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700501 dvmLockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800502
503 if (self != NULL)
504 self->status = oldStatus;
505}
506
507/*
Andy McFaddend19988d2010-10-22 13:32:12 -0700508 * Try to lock the thread list.
509 *
510 * Returns "true" if we locked it. This is a "fast" mutex, so if the
511 * current thread holds the lock this will fail.
512 */
513bool dvmTryLockThreadList(void)
514{
515 return (dvmTryLockMutex(&gDvm.threadListLock) == 0);
516}
517
518/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800519 * Release the thread list global lock.
520 */
521void dvmUnlockThreadList(void)
522{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700523 dvmUnlockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800524}
525
The Android Open Source Project99409882009-03-18 22:20:24 -0700526/*
527 * Convert SuspendCause to a string.
528 */
529static const char* getSuspendCauseStr(SuspendCause why)
530{
531 switch (why) {
532 case SUSPEND_NOT: return "NOT?";
533 case SUSPEND_FOR_GC: return "gc";
534 case SUSPEND_FOR_DEBUG: return "debug";
535 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
536 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700537 case SUSPEND_FOR_VERIFY: return "verify";
Carl Shapiro07018e22010-10-26 21:07:41 -0700538 case SUSPEND_FOR_HPROF: return "hprof";
Ben Chenga8e64a72009-10-20 13:01:36 -0700539#if defined(WITH_JIT)
540 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
541 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800542 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800543 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700544#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700545 default: return "UNKNOWN";
546 }
547}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800548
549/*
550 * Grab the "thread suspend" lock. This is required to prevent the
551 * GC and the debugger from simultaneously suspending all threads.
552 *
553 * If we fail to get the lock, somebody else is trying to suspend all
554 * threads -- including us. If we go to sleep on the lock we'll deadlock
555 * the VM. Loop until we get it or somebody puts us to sleep.
556 */
557static void lockThreadSuspend(const char* who, SuspendCause why)
558{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800559 const int kSpinSleepTime = 3*1000*1000; /* 3s */
560 u8 startWhen = 0; // init req'd to placate gcc
561 int sleepIter = 0;
562 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700563
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800564 do {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700565 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800566 if (cc != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700567 Thread* self = dvmThreadSelf();
568
569 if (!dvmCheckSuspendPending(self)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800570 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700571 * Could be that a resume-all is in progress, and something
572 * grabbed the CPU when the wakeup was broadcast. The thread
573 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700574 * thread suspend lock. (We release before the broadcast,
575 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700576 *
577 * Could be we hit the window as a suspend was started,
578 * and the lock has been grabbed but the suspend counts
579 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700580 *
581 * Could be an unusual JNI thread-attach thing.
582 *
583 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800584 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700585 *
586 * Could be two app threads both want to patch predicted
587 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800588 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700589 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
590 " it's held, no suspend pending\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700591 self->threadId, who, getSuspendCauseStr(why));
The Android Open Source Project99409882009-03-18 22:20:24 -0700592 } else {
593 /* we suspended; reset timeout */
594 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800595 }
596
597 /* give the lock-holder a chance to do some work */
598 if (sleepIter == 0)
599 startWhen = dvmGetRelativeTimeUsec();
600 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700601 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800602 " bailing\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700603 self->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700604 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800605 dvmDumpAllThreads(false);
606 dvmAbort();
607 }
608 }
609 } while (cc != 0);
610 assert(cc == 0);
611}
612
613/*
614 * Release the "thread suspend" lock.
615 */
616static inline void unlockThreadSuspend(void)
617{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700618 dvmUnlockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800619}
620
621
622/*
623 * Kill any daemon threads that still exist. All of ours should be
624 * stopped, so these should be Thread objects or JNI-attached threads
625 * started by the application. Actively-running threads are likely
626 * to crash the process if they continue to execute while the VM
627 * shuts down, so we really need to kill or suspend them. (If we want
628 * the VM to restart within this process, we need to kill them, but that
629 * leaves open the possibility of orphaned resources.)
630 *
631 * Waiting for the thread to suspend may be unwise at this point, but
632 * if one of these is wedged in a critical section then we probably
633 * would've locked up on the last GC attempt.
634 *
635 * It's possible for this function to get called after a failed
636 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700637 *
638 * This will be called from whatever thread calls DestroyJavaVM, usually
639 * but not necessarily the main thread. It's likely, but not guaranteed,
640 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800641 */
642void dvmSlayDaemons(void)
643{
Andy McFadden44860362009-08-06 17:56:14 -0700644 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800645 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700646 int threadId = 0;
647 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800648
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800649 dvmLockThreadList(self);
650
Andy McFadden44860362009-08-06 17:56:14 -0700651 if (self != NULL)
652 threadId = self->threadId;
653
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800654 target = gDvm.threadList;
655 while (target != NULL) {
656 if (target == self) {
657 target = target->next;
658 continue;
659 }
660
661 if (!dvmGetFieldBoolean(target->threadObj,
662 gDvm.offJavaLangThread_daemon))
663 {
Andy McFadden44860362009-08-06 17:56:14 -0700664 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800665 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700666 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800667 }
668
Andy McFadden44860362009-08-06 17:56:14 -0700669 char* threadName = dvmGetThreadName(target);
670 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
671 threadId, target->threadId, threadName);
672 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800673
Andy McFadden44860362009-08-06 17:56:14 -0700674 /* mark as suspended */
675 lockThreadSuspendCount();
676 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
677 unlockThreadSuspendCount();
678 doWait = true;
679
680 target = target->next;
681 }
682
683 //dvmDumpAllThreads(false);
684
685 /*
686 * Unlock the thread list, relocking it later if necessary. It's
687 * possible a thread is in VMWAIT after calling dvmLockThreadList,
688 * and that function *doesn't* check for pending suspend after
689 * acquiring the lock. We want to let them finish their business
690 * and see the pending suspend before we continue here.
691 *
692 * There's no guarantee of mutex fairness, so this might not work.
693 * (The alternative is to have dvmLockThreadList check for suspend
694 * after acquiring the lock and back off, something we should consider.)
695 */
696 dvmUnlockThreadList();
697
698 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800699 bool complained = false;
700
Andy McFadden44860362009-08-06 17:56:14 -0700701 usleep(200 * 1000);
702
703 dvmLockThreadList(self);
704
705 /*
706 * Sleep for a bit until the threads have suspended. We're trying
707 * to exit, so don't wait for too long.
708 */
709 int i;
710 for (i = 0; i < 10; i++) {
711 bool allSuspended = true;
712
713 target = gDvm.threadList;
714 while (target != NULL) {
715 if (target == self) {
716 target = target->next;
717 continue;
718 }
719
Andy McFadden6dce9962010-08-23 16:45:24 -0700720 if (target->status == THREAD_RUNNING) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800721 if (!complained)
722 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700723 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800724 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700725 }
726
727 target = target->next;
728 }
729
730 if (allSuspended) {
731 LOGD("threadid=%d: all daemons have suspended\n", threadId);
732 break;
733 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800734 if (!complained) {
735 complained = true;
736 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
737 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800738 }
Andy McFadden44860362009-08-06 17:56:14 -0700739 }
740
741 usleep(200 * 1000);
742 }
743 dvmUnlockThreadList();
744 }
745
746#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
747 /*
748 * Abandon the threads and recover their resources.
749 */
750 target = gDvm.threadList;
751 while (target != NULL) {
752 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800753 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800754 freeThread(target);
755 target = nextTarget;
756 }
Andy McFadden44860362009-08-06 17:56:14 -0700757#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800758
Andy McFadden44860362009-08-06 17:56:14 -0700759 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800760}
761
762
763/*
764 * Finish preparing the parts of the Thread struct required to support
765 * JNI registration.
766 */
767bool dvmPrepMainForJni(JNIEnv* pEnv)
768{
769 Thread* self;
770
771 /* main thread is always first in list at this point */
772 self = gDvm.threadList;
773 assert(self->threadId == kMainThreadId);
774
775 /* create a "fake" JNI frame at the top of the main thread interp stack */
776 if (!createFakeEntryFrame(self))
777 return false;
778
779 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
780 dvmSetJniEnvThreadId(pEnv, self);
781 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
782
783 return true;
784}
785
786
787/*
788 * Finish preparing the main thread, allocating some objects to represent
789 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700790 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800791 */
792bool dvmPrepMainThread(void)
793{
794 Thread* thread;
795 Object* groupObj;
796 Object* threadObj;
797 Object* vmThreadObj;
798 StringObject* threadNameStr;
799 Method* init;
800 JValue unused;
801
802 LOGV("+++ finishing prep on main VM thread\n");
803
804 /* main thread is always first in list at this point */
805 thread = gDvm.threadList;
806 assert(thread->threadId == kMainThreadId);
807
808 /*
809 * Make sure the classes are initialized. We have to do this before
810 * we create an instance of them.
811 */
812 if (!dvmInitClass(gDvm.classJavaLangClass)) {
813 LOGE("'Class' class failed to initialize\n");
814 return false;
815 }
816 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
817 !dvmInitClass(gDvm.classJavaLangThread) ||
818 !dvmInitClass(gDvm.classJavaLangVMThread))
819 {
820 LOGE("thread classes failed to initialize\n");
821 return false;
822 }
823
824 groupObj = dvmGetMainThreadGroup();
825 if (groupObj == NULL)
826 return false;
827
828 /*
829 * Allocate and construct a Thread with the internal-creation
830 * constructor.
831 */
832 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
833 if (threadObj == NULL) {
834 LOGE("unable to allocate main thread object\n");
835 return false;
836 }
837 dvmReleaseTrackedAlloc(threadObj, NULL);
838
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700839 threadNameStr = dvmCreateStringFromCstr("main");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800840 if (threadNameStr == NULL)
841 return false;
842 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
843
844 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
845 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
846 assert(init != NULL);
847 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
848 THREAD_NORM_PRIORITY, false);
849 if (dvmCheckException(thread)) {
850 LOGE("exception thrown while constructing main thread object\n");
851 return false;
852 }
853
854 /*
855 * Allocate and construct a VMThread.
856 */
857 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
858 if (vmThreadObj == NULL) {
859 LOGE("unable to allocate main vmthread object\n");
860 return false;
861 }
862 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
863
864 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
865 "(Ljava/lang/Thread;)V");
866 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
867 if (dvmCheckException(thread)) {
868 LOGE("exception thrown while constructing main vmthread object\n");
869 return false;
870 }
871
872 /* set the VMThread.vmData field to our Thread struct */
873 assert(gDvm.offJavaLangVMThread_vmData != 0);
874 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
875
876 /*
877 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700878 * Threads will see that this Thread is running (at least, they would,
879 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800880 */
881 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
882 vmThreadObj);
883
884 thread->threadObj = threadObj;
885
886 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700887 * Set the context class loader. This invokes a ClassLoader method,
888 * which could conceivably call Thread.currentThread(), so we want the
889 * Thread to be fully configured before we do this.
890 */
891 Object* systemLoader = dvmGetSystemClassLoader();
892 if (systemLoader == NULL) {
893 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
894 /* keep going */
895 }
896 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
897 "contextClassLoader", "Ljava/lang/ClassLoader;");
898 if (ctxtClassLoaderOffset < 0) {
899 LOGE("Unable to find contextClassLoader field in Thread\n");
900 return false;
901 }
902 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
Andy McFadden50cab512010-10-07 15:11:43 -0700903 dvmReleaseTrackedAlloc(systemLoader, NULL);
Andy McFaddena1a7a342009-05-04 13:29:30 -0700904
905 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800906 * Finish our thread prep.
907 */
908
909 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
910 gDvm.nonDaemonThreadCount++;
911
912 return true;
913}
914
915
916/*
917 * Alloc and initialize a Thread struct.
918 *
Andy McFaddene3346d82010-06-02 15:37:21 -0700919 * Does not create any objects, just stuff on the system (malloc) heap.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800920 */
921static Thread* allocThread(int interpStackSize)
922{
923 Thread* thread;
924 u1* stackBottom;
925
926 thread = (Thread*) calloc(1, sizeof(Thread));
927 if (thread == NULL)
928 return NULL;
929
Jeff Hao97319a82009-08-12 16:57:15 -0700930#if defined(WITH_SELF_VERIFICATION)
931 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
932 return NULL;
933#endif
934
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800935 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
936
937 thread->status = THREAD_INITIALIZING;
938 thread->suspendCount = 0;
939
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800940 /*
941 * Allocate and initialize the interpreted code stack. We essentially
942 * "lose" the alloc pointer, which points at the bottom of the stack,
943 * but we can get it back later because we know how big the stack is.
944 *
945 * The stack must be aligned on a 4-byte boundary.
946 */
947#ifdef MALLOC_INTERP_STACK
948 stackBottom = (u1*) malloc(interpStackSize);
949 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700950#if defined(WITH_SELF_VERIFICATION)
951 dvmSelfVerificationShadowSpaceFree(thread);
952#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800953 free(thread);
954 return NULL;
955 }
956 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
957#else
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800958 stackBottom = (u1*) mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800959 MAP_PRIVATE | MAP_ANON, -1, 0);
960 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700961#if defined(WITH_SELF_VERIFICATION)
962 dvmSelfVerificationShadowSpaceFree(thread);
963#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800964 free(thread);
965 return NULL;
966 }
967#endif
968
969 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
970 thread->interpStackSize = interpStackSize;
971 thread->interpStackStart = stackBottom + interpStackSize;
972 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
973
974 /* give the thread code a chance to set things up */
975 dvmInitInterpStack(thread, interpStackSize);
976
buzbee9f601a92011-02-11 17:48:20 -0800977 /* One-time setup for interpreter/JIT state */
978 dvmInitInterpreterState(thread);
979
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800980 return thread;
981}
982
983/*
984 * Get a meaningful thread ID. At present this only has meaning under Linux,
985 * where getpid() and gettid() sometimes agree and sometimes don't depending
986 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
987 */
988pid_t dvmGetSysThreadId(void)
989{
990#ifdef HAVE_GETTID
991 return gettid();
992#else
993 return getpid();
994#endif
995}
996
997/*
998 * Finish initialization of a Thread struct.
999 *
1000 * This must be called while executing in the new thread, but before the
1001 * thread is added to the thread list.
1002 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001003 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001004 * assignThreadId()).
1005 */
1006static bool prepareThread(Thread* thread)
1007{
1008 assignThreadId(thread);
1009 thread->handle = pthread_self();
1010 thread->systemTid = dvmGetSysThreadId();
1011
1012 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1013 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001014 /*
1015 * If we were called by dvmAttachCurrentThread, the self value is
1016 * already correctly established as "thread".
1017 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001018 setThreadSelf(thread);
1019
1020 LOGV("threadid=%d: interp stack at %p\n",
1021 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1022
1023 /*
1024 * Initialize invokeReq.
1025 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001026 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001027 pthread_cond_init(&thread->invokeReq.cv, NULL);
1028
1029 /*
1030 * Initialize our reference tracking tables.
1031 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001032 * Most threads won't use jniMonitorRefTable, so we clear out the
1033 * structure but don't call the init function (which allocs storage).
1034 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001035#ifdef USE_INDIRECT_REF
1036 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1037 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1038 return false;
1039#else
1040 /*
1041 * The JNI local ref table *must* be fixed-size because we keep pointers
1042 * into the table in our stack frames.
1043 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001044 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1045 kJniLocalRefMax, kJniLocalRefMax))
1046 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001047#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001048 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1049 kInternalRefDefault, kInternalRefMax))
1050 return false;
1051
1052 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1053
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001054 pthread_cond_init(&thread->waitCond, NULL);
1055 dvmInitMutex(&thread->waitMutex);
1056
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001057 return true;
1058}
1059
1060/*
1061 * Remove a thread from the internal list.
1062 * Clear out the links to make it obvious that the thread is
1063 * no longer on the list. Caller must hold gDvm.threadListLock.
1064 */
1065static void unlinkThread(Thread* thread)
1066{
1067 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1068 if (thread == gDvm.threadList) {
1069 assert(thread->prev == NULL);
1070 gDvm.threadList = thread->next;
1071 } else {
1072 assert(thread->prev != NULL);
1073 thread->prev->next = thread->next;
1074 }
1075 if (thread->next != NULL)
1076 thread->next->prev = thread->prev;
1077 thread->prev = thread->next = NULL;
1078}
1079
1080/*
1081 * Free a Thread struct, and all the stuff allocated within.
1082 */
1083static void freeThread(Thread* thread)
1084{
1085 if (thread == NULL)
1086 return;
1087
1088 /* thread->threadId is zero at this point */
1089 LOGVV("threadid=%d: freeing\n", thread->threadId);
1090
1091 if (thread->interpStackStart != NULL) {
1092 u1* interpStackBottom;
1093
1094 interpStackBottom = thread->interpStackStart;
1095 interpStackBottom -= thread->interpStackSize;
1096#ifdef MALLOC_INTERP_STACK
1097 free(interpStackBottom);
1098#else
1099 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1100 LOGW("munmap(thread stack) failed\n");
1101#endif
1102 }
1103
Andy McFaddend5ab7262009-08-25 07:19:34 -07001104#ifdef USE_INDIRECT_REF
1105 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1106#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001107 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001108#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001109 dvmClearReferenceTable(&thread->internalLocalRefTable);
1110 if (&thread->jniMonitorRefTable.table != NULL)
1111 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1112
Jeff Hao97319a82009-08-12 16:57:15 -07001113#if defined(WITH_SELF_VERIFICATION)
1114 dvmSelfVerificationShadowSpaceFree(thread);
1115#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001116 free(thread);
1117}
1118
1119/*
1120 * Like pthread_self(), but on a Thread*.
1121 */
1122Thread* dvmThreadSelf(void)
1123{
1124 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1125}
1126
1127/*
1128 * Explore our sense of self. Stuffs the thread pointer into TLS.
1129 */
1130static void setThreadSelf(Thread* thread)
1131{
1132 int cc;
1133
1134 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1135 if (cc != 0) {
1136 /*
1137 * Sometimes this fails under Bionic with EINVAL during shutdown.
1138 * This can happen if the timing is just right, e.g. a thread
1139 * fails to attach during shutdown, but the "fail" path calls
1140 * here to ensure we clean up after ourselves.
1141 */
1142 if (thread != NULL) {
1143 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1144 dvmAbort(); /* the world is fundamentally hosed */
1145 }
1146 }
1147}
1148
1149/*
1150 * This is associated with the pthreadKeySelf key. It's called by the
1151 * pthread library when a thread is exiting and the "self" pointer in TLS
1152 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001153 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001154 *
1155 * This is mainly of use to ensure that we don't leak resources if, for
1156 * example, a thread attaches itself to us with AttachCurrentThread and
1157 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001158 *
1159 * We could do the detach here instead of aborting, but this will lead to
1160 * portability problems. Other implementations do not do this check and
1161 * will simply be unaware that the thread has exited, leading to resource
1162 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1163 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001164 *
1165 * Because some implementations may want to use the pthread destructor
1166 * to initiate the detach, and the ordering of destructors is not defined,
1167 * 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 -08001168 */
1169static void threadExitCheck(void* arg)
1170{
Andy McFadden909ce242009-12-10 16:38:30 -08001171 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001172
Andy McFadden909ce242009-12-10 16:38:30 -08001173 Thread* self = (Thread*) arg;
1174 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001175
Andy McFadden909ce242009-12-10 16:38:30 -08001176 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1177 self->threadId, arg, self->threadExitCheckCount);
1178
1179 if (self->status == THREAD_ZOMBIE) {
1180 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1181 self->threadId);
1182 return;
1183 }
1184
1185 if (self->threadExitCheckCount < kMaxCount) {
1186 /*
1187 * Spin a couple of times to let other destructors fire.
1188 */
1189 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1190 self->threadId, self->threadExitCheckCount);
1191 self->threadExitCheckCount++;
1192 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1193 if (cc != 0) {
1194 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1195 self->threadId);
1196 dvmAbort();
1197 }
1198 } else {
1199 LOGE("threadid=%d: native thread exited without detaching\n",
1200 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001201 dvmAbort();
1202 }
1203}
1204
1205
1206/*
1207 * Assign the threadId. This needs to be a small integer so that our
1208 * "thin" locks fit in a small number of bits.
1209 *
1210 * We reserve zero for use as an invalid ID.
1211 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001212 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001213 */
1214static void assignThreadId(Thread* thread)
1215{
Carl Shapiro59a93122010-01-26 17:12:51 -08001216 /*
1217 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001218 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1219 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001220 */
1221 int num = dvmAllocBit(gDvm.threadIdMap);
1222 if (num < 0) {
1223 LOGE("Ran out of thread IDs\n");
1224 dvmAbort(); // TODO: make this a non-fatal error result
1225 }
1226
Carl Shapiro59a93122010-01-26 17:12:51 -08001227 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001228
1229 assert(thread->threadId != 0);
1230 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1231}
1232
1233/*
1234 * Give back the thread ID.
1235 */
1236static void releaseThreadId(Thread* thread)
1237{
1238 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001239 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001240 thread->threadId = 0;
1241}
1242
1243
1244/*
1245 * Add a stack frame that makes it look like the native code in the main
1246 * thread was originally invoked from interpreted code. This gives us a
1247 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1248 * VM begins by executing "main" in a class, so in a way this brings us
1249 * closer to the spec.
1250 */
1251static bool createFakeEntryFrame(Thread* thread)
1252{
1253 assert(thread->threadId == kMainThreadId); // main thread only
1254
1255 /* find the method on first use */
1256 if (gDvm.methFakeNativeEntry == NULL) {
1257 ClassObject* nativeStart;
1258 Method* mainMeth;
1259
1260 nativeStart = dvmFindSystemClassNoInit(
1261 "Ldalvik/system/NativeStart;");
1262 if (nativeStart == NULL) {
1263 LOGE("Unable to find dalvik.system.NativeStart class\n");
1264 return false;
1265 }
1266
1267 /*
1268 * Because we are creating a frame that represents application code, we
1269 * want to stuff the application class loader into the method's class
1270 * loader field, even though we're using the system class loader to
1271 * load it. This makes life easier over in JNI FindClass (though it
1272 * could bite us in other ways).
1273 *
1274 * Unfortunately this is occurring too early in the initialization,
1275 * of necessity coming before JNI is initialized, and we're not quite
1276 * ready to set up the application class loader.
1277 *
1278 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1279 * and check it in FindClass. The method is private so nobody else
1280 * can call it.
1281 */
1282 //nativeStart->classLoader = dvmGetSystemClassLoader();
1283
1284 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1285 "main", "([Ljava/lang/String;)V");
1286 if (mainMeth == NULL) {
1287 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1288 return false;
1289 }
1290
1291 gDvm.methFakeNativeEntry = mainMeth;
1292 }
1293
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001294 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1295 return false;
1296
1297 /*
1298 * Null out the "String[] args" argument.
1299 */
1300 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1301 u4* framePtr = (u4*) thread->curFrame;
1302 framePtr[0] = 0;
1303
1304 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001305}
1306
1307
1308/*
1309 * Add a stack frame that makes it look like the native thread has been
1310 * executing interpreted code. This gives us a place to hang JNI local
1311 * references.
1312 */
1313static bool createFakeRunFrame(Thread* thread)
1314{
1315 ClassObject* nativeStart;
1316 Method* runMeth;
1317
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001318 /*
1319 * TODO: cache this result so we don't have to dig for it every time
1320 * somebody attaches a thread to the VM. Also consider changing this
1321 * to a static method so we don't have a null "this" pointer in the
1322 * "ins" on the stack. (Does it really need to look like a Runnable?)
1323 */
1324 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001325 if (nativeStart == NULL) {
1326 LOGE("Unable to find dalvik.system.NativeStart class\n");
1327 return false;
1328 }
1329
1330 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1331 if (runMeth == NULL) {
1332 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1333 return false;
1334 }
1335
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001336 if (!dvmPushJNIFrame(thread, runMeth))
1337 return false;
1338
1339 /*
1340 * Provide a NULL 'this' argument. The method we've put at the top of
1341 * the stack looks like a virtual call to run() in a Runnable class.
1342 * (If we declared the method static, it wouldn't take any arguments
1343 * and we wouldn't have to do this.)
1344 */
1345 assert(runMeth->registersSize == 1);
1346 u4* framePtr = (u4*) thread->curFrame;
1347 framePtr[0] = 0;
1348
1349 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001350}
1351
1352/*
1353 * Helper function to set the name of the current thread
1354 */
1355static void setThreadName(const char *threadName)
1356{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001357 int hasAt = 0;
1358 int hasDot = 0;
1359 const char *s = threadName;
1360 while (*s) {
1361 if (*s == '.') hasDot = 1;
1362 else if (*s == '@') hasAt = 1;
1363 s++;
1364 }
1365 int len = s - threadName;
1366 if (len < 15 || hasAt || !hasDot) {
1367 s = threadName;
1368 } else {
1369 s = threadName + len - 15;
1370 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001371#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001372 /* pthread_setname_np fails rather than truncating long strings */
1373 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1374 strncpy(buf, s, sizeof(buf)-1);
1375 buf[sizeof(buf)-1] = '\0';
1376 int err = pthread_setname_np(pthread_self(), buf);
1377 if (err != 0) {
1378 LOGW("Unable to set the name of current thread to '%s': %s\n",
1379 buf, strerror(err));
1380 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001381#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001382 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001383#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001384 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001385#endif
1386}
1387
1388/*
1389 * Create a thread as a result of java.lang.Thread.start().
1390 *
1391 * We do have to worry about some concurrency problems, e.g. programs
1392 * that try to call Thread.start() on the same object from multiple threads.
1393 * (This will fail for all but one, but we have to make sure that it succeeds
1394 * for exactly one.)
1395 *
1396 * Some of the complexity here arises from our desire to mimic the
1397 * Thread vs. VMThread class decomposition we inherited. We've been given
1398 * a Thread, and now we need to create a VMThread and then populate both
1399 * objects. We also need to create one of our internal Thread objects.
1400 *
1401 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001402 *
1403 * The "threadObj" reference must be pinned by the caller to prevent the GC
1404 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001405 */
1406bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1407{
1408 pthread_attr_t threadAttr;
1409 pthread_t threadHandle;
1410 Thread* self;
1411 Thread* newThread = NULL;
1412 Object* vmThreadObj = NULL;
1413 int stackSize;
1414
1415 assert(threadObj != NULL);
1416
1417 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001418 // Allow the sampling profiler thread. We shut it down before forking.
1419 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1420 gDvm.offJavaLangThread_name);
1421 char* threadName = dvmCreateCstrFromString(nameStr);
1422 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
Bob Lee9dc72a32009-09-04 18:28:16 -07001423 if (!profilerThread) {
Brian Carlstrom33dab962010-12-01 13:46:50 -08001424 dvmThrowExceptionFmt("Ljava/lang/IllegalStateException;",
1425 "No new threads in -Xzygote mode. "
1426 "Found thread named '%s'", threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001427
Brian Carlstrom33dab962010-12-01 13:46:50 -08001428 free(threadName);
Bob Lee9dc72a32009-09-04 18:28:16 -07001429 goto fail;
1430 }
Brian Carlstrom33dab962010-12-01 13:46:50 -08001431 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001432 }
1433
1434 self = dvmThreadSelf();
1435 if (reqStackSize == 0)
1436 stackSize = gDvm.stackSize;
1437 else if (reqStackSize < kMinStackSize)
1438 stackSize = kMinStackSize;
1439 else if (reqStackSize > kMaxStackSize)
1440 stackSize = kMaxStackSize;
1441 else
1442 stackSize = reqStackSize;
1443
1444 pthread_attr_init(&threadAttr);
1445 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1446
1447 /*
1448 * To minimize the time spent in the critical section, we allocate the
1449 * vmThread object here.
1450 */
1451 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1452 if (vmThreadObj == NULL)
1453 goto fail;
1454
1455 newThread = allocThread(stackSize);
1456 if (newThread == NULL)
1457 goto fail;
1458 newThread->threadObj = threadObj;
1459
1460 assert(newThread->status == THREAD_INITIALIZING);
1461
1462 /*
1463 * We need to lock out other threads while we test and set the
1464 * "vmThread" field in java.lang.Thread, because we use that to determine
1465 * if this thread has been started before. We use the thread list lock
1466 * because it's handy and we're going to need to grab it again soon
1467 * anyway.
1468 */
1469 dvmLockThreadList(self);
1470
1471 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1472 dvmUnlockThreadList();
1473 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1474 "thread has already been started");
1475 goto fail;
1476 }
1477
1478 /*
1479 * There are actually three data structures: Thread (object), VMThread
1480 * (object), and Thread (C struct). All of them point to at least one
1481 * other.
1482 *
1483 * As soon as "VMThread.vmData" is assigned, other threads can start
1484 * making calls into us (e.g. setPriority).
1485 */
1486 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1487 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1488
1489 /*
1490 * Thread creation might take a while, so release the lock.
1491 */
1492 dvmUnlockThreadList();
1493
Carl Shapiro5617ad32010-07-02 10:50:57 -07001494 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1495 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001496 newThread);
1497 oldStatus = dvmChangeStatus(self, oldStatus);
1498
1499 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001500 /*
1501 * Failure generally indicates that we have exceeded system
1502 * resource limits. VirtualMachineError is probably too severe,
1503 * so use OutOfMemoryError.
1504 */
1505 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1506
1507 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1508
1509 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1510 "thread creation failed");
1511 goto fail;
1512 }
1513
1514 /*
1515 * We need to wait for the thread to start. Otherwise, depending on
1516 * the whims of the OS scheduler, we could return and the code in our
1517 * thread could try to do operations on the new thread before it had
1518 * finished starting.
1519 *
1520 * The new thread will lock the thread list, change its state to
1521 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1522 * on gDvm.threadStartCond (which uses the thread list lock). This
1523 * thread (the parent) will either see that the thread is already ready
1524 * after we grab the thread list lock, or will be awakened from the
1525 * condition variable on the broadcast.
1526 *
1527 * We don't want to stall the rest of the VM while the new thread
1528 * starts, which can happen if the GC wakes up at the wrong moment.
1529 * So, we change our own status to VMWAIT, and self-suspend if
1530 * necessary after we finish adding the new thread.
1531 *
1532 *
1533 * We have to deal with an odd race with the GC/debugger suspension
1534 * mechanism when creating a new thread. The information about whether
1535 * or not a thread should be suspended is contained entirely within
1536 * the Thread struct; this is usually cleaner to deal with than having
1537 * one or more globally-visible suspension flags. The trouble is that
1538 * we could create the thread while the VM is trying to suspend all
1539 * threads. The suspend-count won't be nonzero for the new thread,
1540 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1541 *
1542 * The easiest way to deal with this is to prevent the new thread from
1543 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001544 * following (correct) sequence of events for a "badly timed" GC
1545 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001546 *
1547 * - call pthread_create()
1548 * - lock thread list
1549 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1550 * - sleep on condition var (mutex = thread list lock) until child starts
1551 * + GC triggered by another thread
1552 * + thread list locked; suspend counts updated; thread list unlocked
1553 * + loop waiting for all runnable threads to suspend
1554 * + success, start GC
1555 * o child thread wakes, signals condition var to wake parent
1556 * o child waits for parent ack on condition variable
1557 * - we wake up, locking thread list
1558 * - add child to thread list
1559 * - unlock thread list
1560 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1561 * + GC finishes; all threads in thread list are resumed
1562 * - lock thread list
1563 * - set child to THREAD_VMWAIT, and signal it to start
1564 * - unlock thread list
1565 * o child resumes
1566 * o child changes state to THREAD_RUNNING
1567 *
1568 * The above shows the GC starting up during thread creation, but if
1569 * it starts anywhere after VMThread.create() is called it will
1570 * produce the same series of events.
1571 *
1572 * Once the child is in the thread list, it will be suspended and
1573 * resumed like any other thread. In the above scenario the resume-all
1574 * code will try to resume the new thread, which was never actually
1575 * suspended, and try to decrement the child's thread suspend count to -1.
1576 * We can catch this in the resume-all code.
1577 *
1578 * Bouncing back and forth between threads like this adds a small amount
1579 * of scheduler overhead to thread startup.
1580 *
1581 * One alternative to having the child wait for the parent would be
1582 * to have the child inherit the parents' suspension count. This
1583 * would work for a GC, since we can safely assume that the parent
1584 * thread didn't cause it, but we must only do so if the parent suspension
1585 * was caused by a suspend-all. If the parent was being asked to
1586 * suspend singly by the debugger, the child should not inherit the value.
1587 *
1588 * We could also have a global "new thread suspend count" that gets
1589 * picked up by new threads before changing state to THREAD_RUNNING.
1590 * This would be protected by the thread list lock and set by a
1591 * suspend-all.
1592 */
1593 dvmLockThreadList(self);
1594 assert(self->status == THREAD_RUNNING);
1595 self->status = THREAD_VMWAIT;
1596 while (newThread->status != THREAD_STARTING)
1597 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1598
1599 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1600 newThread->next = gDvm.threadList->next;
1601 if (newThread->next != NULL)
1602 newThread->next->prev = newThread;
1603 newThread->prev = gDvm.threadList;
1604 gDvm.threadList->next = newThread;
1605
1606 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1607 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1608
1609 dvmUnlockThreadList();
1610
1611 /* change status back to RUNNING, self-suspending if necessary */
1612 dvmChangeStatus(self, THREAD_RUNNING);
1613
1614 /*
1615 * Tell the new thread to start.
1616 *
1617 * We must hold the thread list lock before messing with another thread.
1618 * In the general case we would also need to verify that newThread was
1619 * still in the thread list, but in our case the thread has not started
1620 * executing user code and therefore has not had a chance to exit.
1621 *
1622 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1623 * comes with a suspend-pending check.
1624 */
1625 dvmLockThreadList(self);
1626
1627 assert(newThread->status == THREAD_STARTING);
1628 newThread->status = THREAD_VMWAIT;
1629 pthread_cond_broadcast(&gDvm.threadStartCond);
1630
1631 dvmUnlockThreadList();
1632
1633 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1634 return true;
1635
1636fail:
1637 freeThread(newThread);
1638 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1639 return false;
1640}
1641
1642/*
1643 * pthread entry function for threads started from interpreted code.
1644 */
1645static void* interpThreadStart(void* arg)
1646{
1647 Thread* self = (Thread*) arg;
1648
1649 char *threadName = dvmGetThreadName(self);
1650 setThreadName(threadName);
1651 free(threadName);
1652
1653 /*
1654 * Finish initializing the Thread struct.
1655 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001656 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001657 prepareThread(self);
1658
1659 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1660
1661 /*
1662 * Change our status and wake our parent, who will add us to the
1663 * thread list and advance our state to VMWAIT.
1664 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001665 self->status = THREAD_STARTING;
1666 pthread_cond_broadcast(&gDvm.threadStartCond);
1667
1668 /*
1669 * Wait until the parent says we can go. Assuming there wasn't a
1670 * suspend pending, this will happen immediately. When it completes,
1671 * we're full-fledged citizens of the VM.
1672 *
1673 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1674 * because the pthread_cond_wait below needs to reacquire a lock that
1675 * suspend-all is also interested in. If we get unlucky, the parent could
1676 * change us to THREAD_RUNNING, then a GC could start before we get
1677 * signaled, and suspend-all will grab the thread list lock and then
1678 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1679 * trying to get the lock.
1680 */
1681 while (self->status != THREAD_VMWAIT)
1682 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1683
1684 dvmUnlockThreadList();
1685
1686 /*
1687 * Add a JNI context.
1688 */
1689 self->jniEnv = dvmCreateJNIEnv(self);
1690
1691 /*
1692 * Change our state so the GC will wait for us from now on. If a GC is
1693 * in progress this call will suspend us.
1694 */
1695 dvmChangeStatus(self, THREAD_RUNNING);
1696
1697 /*
1698 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001699 * us to suspend ourselves (and others). The thread state may change
1700 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001701 */
1702 if (gDvm.debuggerConnected)
1703 dvmDbgPostThreadStart(self);
1704
1705 /*
1706 * Set the system thread priority according to the Thread object's
1707 * priority level. We don't usually need to do this, because both the
1708 * Thread object and system thread priorities inherit from parents. The
1709 * tricky case is when somebody creates a Thread object, calls
1710 * setPriority(), and then starts the thread. We could manage this with
1711 * a "needs priority update" flag to avoid the redundant call.
1712 */
Andy McFadden4879df92009-08-07 14:49:40 -07001713 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001714 gDvm.offJavaLangThread_priority);
1715 dvmChangeThreadPriority(self, priority);
1716
1717 /*
1718 * Execute the "run" method.
1719 *
1720 * At this point our stack is empty, so somebody who comes looking for
1721 * stack traces right now won't have much to look at. This is normal.
1722 */
1723 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1724 JValue unused;
1725
1726 LOGV("threadid=%d: calling run()\n", self->threadId);
1727 assert(strcmp(run->name, "run") == 0);
1728 dvmCallMethod(self, run, self->threadObj, &unused);
1729 LOGV("threadid=%d: exiting\n", self->threadId);
1730
1731 /*
1732 * Remove the thread from various lists, report its death, and free
1733 * its resources.
1734 */
1735 dvmDetachCurrentThread();
1736
1737 return NULL;
1738}
1739
1740/*
1741 * The current thread is exiting with an uncaught exception. The
1742 * Java programming language allows the application to provide a
1743 * thread-exit-uncaught-exception handler for the VM, for a specific
1744 * Thread, and for all threads in a ThreadGroup.
1745 *
1746 * Version 1.5 added the per-thread handler. We need to call
1747 * "uncaughtException" in the handler object, which is either the
1748 * ThreadGroup object or the Thread-specific handler.
1749 */
1750static void threadExitUncaughtException(Thread* self, Object* group)
1751{
1752 Object* exception;
1753 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001754 Method* uncaughtHandler = NULL;
1755 InstField* threadHandler;
1756
1757 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1758 self->threadId, group);
1759 assert(group != NULL);
1760
1761 /*
1762 * Get a pointer to the exception, then clear out the one in the
1763 * thread. We don't want to have it set when executing interpreted code.
1764 */
1765 exception = dvmGetException(self);
1766 dvmAddTrackedAlloc(exception, self);
1767 dvmClearException(self);
1768
1769 /*
1770 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1771 * else use "group" (which is an instance of UncaughtExceptionHandler).
1772 */
1773 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1774 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1775 if (threadHandler == NULL) {
1776 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1777 goto bail;
1778 }
1779 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1780 if (handlerObj == NULL)
1781 handlerObj = group;
1782
1783 /*
1784 * Find the "uncaughtHandler" field in this object.
1785 */
1786 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1787 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1788
1789 if (uncaughtHandler != NULL) {
1790 //LOGI("+++ calling %s.uncaughtException\n",
1791 // handlerObj->clazz->descriptor);
1792 JValue unused;
1793 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1794 self->threadObj, exception);
1795 } else {
1796 /* restore it and dump a stack trace */
1797 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1798 handlerObj->clazz->descriptor);
1799 dvmSetException(self, exception);
1800 dvmLogExceptionStackTrace();
1801 }
1802
1803bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001804 /* Remove this thread's suspendCount from global suspendCount sum */
1805 lockThreadSuspendCount();
1806 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1807 unlockThreadSuspendCount();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001808 dvmReleaseTrackedAlloc(exception, self);
1809}
1810
1811
1812/*
1813 * Create an internal VM thread, for things like JDWP and finalizers.
1814 *
1815 * The easiest way to do this is create a new thread and then use the
1816 * JNI AttachCurrentThread implementation.
1817 *
1818 * This does not return until after the new thread has begun executing.
1819 */
1820bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1821 InternalThreadStart func, void* funcArg)
1822{
1823 InternalStartArgs* pArgs;
1824 Object* systemGroup;
1825 pthread_attr_t threadAttr;
1826 volatile Thread* newThread = NULL;
1827 volatile int createStatus = 0;
1828
1829 systemGroup = dvmGetSystemThreadGroup();
1830 if (systemGroup == NULL)
1831 return false;
1832
1833 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1834 pArgs->func = func;
1835 pArgs->funcArg = funcArg;
1836 pArgs->name = strdup(name); // storage will be owned by new thread
1837 pArgs->group = systemGroup;
1838 pArgs->isDaemon = true;
1839 pArgs->pThread = &newThread;
1840 pArgs->pCreateStatus = &createStatus;
1841
1842 pthread_attr_init(&threadAttr);
1843 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1844
1845 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1846 pArgs) != 0)
1847 {
1848 LOGE("internal thread creation failed\n");
1849 free(pArgs->name);
1850 free(pArgs);
1851 return false;
1852 }
1853
1854 /*
1855 * Wait for the child to start. This gives us an opportunity to make
1856 * sure that the thread started correctly, and allows our caller to
1857 * assume that the thread has started running.
1858 *
1859 * Because we aren't holding a lock across the thread creation, it's
1860 * possible that the child will already have completed its
1861 * initialization. Because the child only adjusts "createStatus" while
1862 * holding the thread list lock, the initial condition on the "while"
1863 * loop will correctly avoid the wait if this occurs.
1864 *
1865 * It's also possible that we'll have to wait for the thread to finish
1866 * being created, and as part of allocating a Thread object it might
1867 * need to initiate a GC. We switch to VMWAIT while we pause.
1868 */
1869 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001870 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001871 dvmLockThreadList(self);
1872 while (createStatus == 0)
1873 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1874
1875 if (newThread == NULL) {
1876 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1877 assert(createStatus < 0);
1878 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1879 dvmUnlockThreadList();
1880 dvmChangeStatus(self, oldStatus);
1881 return false;
1882 }
1883
1884 /* thread could be in any state now (except early init states) */
1885 //assert(newThread->status == THREAD_RUNNING);
1886
1887 dvmUnlockThreadList();
1888 dvmChangeStatus(self, oldStatus);
1889
1890 return true;
1891}
1892
1893/*
1894 * pthread entry function for internally-created threads.
1895 *
1896 * We are expected to free "arg" and its contents. If we're a daemon
1897 * thread, and we get cancelled abruptly when the VM shuts down, the
1898 * storage won't be freed. If this becomes a concern we can make a copy
1899 * on the stack.
1900 */
1901static void* internalThreadStart(void* arg)
1902{
1903 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1904 JavaVMAttachArgs jniArgs;
1905
1906 jniArgs.version = JNI_VERSION_1_2;
1907 jniArgs.name = pArgs->name;
1908 jniArgs.group = pArgs->group;
1909
1910 setThreadName(pArgs->name);
1911
1912 /* use local jniArgs as stack top */
1913 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1914 /*
1915 * Tell the parent of our success.
1916 *
1917 * threadListLock is the mutex for threadStartCond.
1918 */
1919 dvmLockThreadList(dvmThreadSelf());
1920 *pArgs->pCreateStatus = 1;
1921 *pArgs->pThread = dvmThreadSelf();
1922 pthread_cond_broadcast(&gDvm.threadStartCond);
1923 dvmUnlockThreadList();
1924
1925 LOG_THREAD("threadid=%d: internal '%s'\n",
1926 dvmThreadSelf()->threadId, pArgs->name);
1927
1928 /* execute */
1929 (*pArgs->func)(pArgs->funcArg);
1930
1931 /* detach ourselves */
1932 dvmDetachCurrentThread();
1933 } else {
1934 /*
1935 * Tell the parent of our failure. We don't have a Thread struct,
1936 * so we can't be suspended, so we don't need to enter a critical
1937 * section.
1938 */
1939 dvmLockThreadList(dvmThreadSelf());
1940 *pArgs->pCreateStatus = -1;
1941 assert(*pArgs->pThread == NULL);
1942 pthread_cond_broadcast(&gDvm.threadStartCond);
1943 dvmUnlockThreadList();
1944
1945 assert(*pArgs->pThread == NULL);
1946 }
1947
1948 free(pArgs->name);
1949 free(pArgs);
1950 return NULL;
1951}
1952
1953/*
1954 * Attach the current thread to the VM.
1955 *
1956 * Used for internally-created threads and JNI's AttachCurrentThread.
1957 */
1958bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1959{
1960 Thread* self = NULL;
1961 Object* threadObj = NULL;
1962 Object* vmThreadObj = NULL;
1963 StringObject* threadNameStr = NULL;
1964 Method* init;
1965 bool ok, ret;
1966
Andy McFaddene3346d82010-06-02 15:37:21 -07001967 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001968 self = allocThread(gDvm.stackSize);
1969 if (self == NULL)
1970 goto fail;
1971 setThreadSelf(self);
1972
1973 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001974 * Finish our thread prep. We need to do this before adding ourselves
1975 * to the thread list or invoking any interpreted code. prepareThread()
1976 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001977 */
1978 dvmLockThreadList(self);
1979 ok = prepareThread(self);
1980 dvmUnlockThreadList();
1981 if (!ok)
1982 goto fail;
1983
1984 self->jniEnv = dvmCreateJNIEnv(self);
1985 if (self->jniEnv == NULL)
1986 goto fail;
1987
1988 /*
1989 * Create a "fake" JNI frame at the top of the main thread interp stack.
1990 * It isn't really necessary for the internal threads, but it gives
1991 * the debugger something to show. It is essential for the JNI-attached
1992 * threads.
1993 */
1994 if (!createFakeRunFrame(self))
1995 goto fail;
1996
1997 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001998 * The native side of the thread is ready; add it to the list. Once
1999 * 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 -08002000 */
2001 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
2002
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002003 dvmLockThreadList(self);
2004
2005 self->next = gDvm.threadList->next;
2006 if (self->next != NULL)
2007 self->next->prev = self;
2008 self->prev = gDvm.threadList;
2009 gDvm.threadList->next = self;
2010 if (!isDaemon)
2011 gDvm.nonDaemonThreadCount++;
2012
2013 dvmUnlockThreadList();
2014
2015 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002016 * Switch state from initializing to running.
2017 *
2018 * It's possible that a GC began right before we added ourselves
2019 * to the thread list, and is still going. That means our thread
2020 * suspend count won't reflect the fact that we should be suspended.
2021 * To deal with this, we transition to VMWAIT, pulse the heap lock,
2022 * and then advance to RUNNING. That will ensure that we stall until
2023 * the GC completes.
2024 *
2025 * Once we're in RUNNING, we're like any other thread in the VM (except
2026 * for the lack of an initialized threadObj). We're then free to
2027 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002028 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002029 assert(self->status == THREAD_INITIALIZING);
2030 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002031 dvmLockMutex(&gDvm.gcHeapLock);
2032 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002033 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002034
2035 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002036 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002037 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002038 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2039 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2040 if (threadObj == NULL || vmThreadObj == NULL)
2041 goto fail_unlink;
2042
2043 /*
2044 * This makes threadObj visible to the GC. We still have it in the
2045 * tracked allocation table, so it can't move around on us.
2046 */
2047 self->threadObj = threadObj;
2048 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2049
2050 /*
2051 * Create a string for the thread name.
2052 */
2053 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002054 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002055 if (threadNameStr == NULL) {
2056 assert(dvmCheckException(dvmThreadSelf()));
2057 goto fail_unlink;
2058 }
2059 }
2060
2061 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2062 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2063 if (init == NULL) {
2064 assert(dvmCheckException(self));
2065 goto fail_unlink;
2066 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002067
2068 /*
2069 * Now we're ready to run some interpreted code.
2070 *
2071 * We need to construct the Thread object and set the VMThread field.
2072 * Setting VMThread tells interpreted code that we're alive.
2073 *
2074 * Call the (group, name, priority, daemon) constructor on the Thread.
2075 * This sets the thread's name and adds it to the specified group, and
2076 * provides values for priority and daemon (which are normally inherited
2077 * from the current thread).
2078 */
2079 JValue unused;
2080 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2081 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2082 if (dvmCheckException(self)) {
2083 LOGE("exception thrown while constructing attached thread object\n");
2084 goto fail_unlink;
2085 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002086
2087 /*
2088 * Set the VMThread field, which tells interpreted code that we're alive.
2089 *
2090 * The risk of a thread start collision here is very low; somebody
2091 * would have to be deliberately polling the ThreadGroup list and
2092 * trying to start threads against anything it sees, which would
2093 * generally cause problems for all thread creation. However, for
2094 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002095 *
2096 * TODO: this still has a race, it's just smaller. Not sure this is
2097 * worth putting effort into fixing. Need to hold a lock while
2098 * fiddling with the field, or maybe initialize the Thread object in a
2099 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002100 */
2101 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002102 LOGW("WOW: thread start hijack\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002103 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2104 "thread has already been started");
2105 /* We don't want to free anything associated with the thread
2106 * because someone is obviously interested in it. Just let
2107 * it go and hope it will clean itself up when its finished.
2108 * This case should never happen anyway.
2109 *
2110 * Since we're letting it live, we need to finish setting it up.
2111 * We just have to let the caller know that the intended operation
2112 * has failed.
2113 *
2114 * [ This seems strange -- stepping on the vmThread object that's
2115 * already present seems like a bad idea. TODO: figure this out. ]
2116 */
2117 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002118 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002119 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002120 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002121 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2122
Andy McFaddene3346d82010-06-02 15:37:21 -07002123 /* we can now safely un-pin these */
2124 dvmReleaseTrackedAlloc(threadObj, self);
2125 dvmReleaseTrackedAlloc(vmThreadObj, self);
2126 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002127
2128 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2129 self->threadId, pArgs->name);
2130
2131 /* tell the debugger & DDM */
2132 if (gDvm.debuggerConnected)
2133 dvmDbgPostThreadStart(self);
2134
2135 return ret;
2136
2137fail_unlink:
2138 dvmLockThreadList(self);
2139 unlinkThread(self);
2140 if (!isDaemon)
2141 gDvm.nonDaemonThreadCount--;
2142 dvmUnlockThreadList();
2143 /* fall through to "fail" */
2144fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002145 dvmReleaseTrackedAlloc(threadObj, self);
2146 dvmReleaseTrackedAlloc(vmThreadObj, self);
2147 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002148 if (self != NULL) {
2149 if (self->jniEnv != NULL) {
2150 dvmDestroyJNIEnv(self->jniEnv);
2151 self->jniEnv = NULL;
2152 }
2153 freeThread(self);
2154 }
2155 setThreadSelf(NULL);
2156 return false;
2157}
2158
2159/*
2160 * Detach the thread from the various data structures, notify other threads
2161 * that are waiting to "join" it, and free up all heap-allocated storage.
2162 *
2163 * Used for all threads.
2164 *
2165 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2166 * requires us to enforce this for the DetachCurrentThread call, probably
2167 * because it also says that DetachCurrentThread causes all monitors
2168 * associated with the thread to be released. (Because the stack is empty,
2169 * we only have to worry about explicit JNI calls to MonitorEnter.)
2170 *
2171 * THOUGHT:
2172 * We might want to avoid freeing our internal Thread structure until the
2173 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2174 * get to once the thread shuts down, but there is a small possibility of
2175 * an operation starting in another thread before this thread halts, and
2176 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2177 * We don't want something like Thread.isInterrupted() crawling through
2178 * freed storage. Can do with a Thread finalizer, or by creating a
2179 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2180 * state into that.
2181 */
2182void dvmDetachCurrentThread(void)
2183{
2184 Thread* self = dvmThreadSelf();
2185 Object* vmThread;
2186 Object* group;
2187
2188 /*
2189 * Make sure we're not detaching a thread that's still running. (This
2190 * could happen with an explicit JNI detach call.)
2191 *
2192 * A thread created by interpreted code will finish with a depth of
2193 * zero, while a JNI-attached thread will have the synthetic "stack
2194 * starter" native method at the top.
2195 */
2196 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2197 if (curDepth != 0) {
2198 bool topIsNative = false;
2199
2200 if (curDepth == 1) {
2201 /* not expecting a lingering break frame; just look at curFrame */
Carl Shapirofc75f3e2010-12-07 11:43:38 -08002202 assert(!dvmIsBreakFrame((u4*)self->curFrame));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002203 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2204 if (dvmIsNativeMethod(ssa->method))
2205 topIsNative = true;
2206 }
2207
2208 if (!topIsNative) {
2209 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2210 curDepth);
2211 dvmDumpThread(self, false);
2212 dvmAbort();
2213 }
2214 }
2215
2216 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2217 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2218
2219 /*
2220 * Release any held monitors. Since there are no interpreted stack
2221 * frames, the only thing left are the monitors held by JNI MonitorEnter
2222 * calls.
2223 */
2224 dvmReleaseJniMonitors(self);
2225
2226 /*
2227 * Do some thread-exit uncaught exception processing if necessary.
2228 */
2229 if (dvmCheckException(self))
2230 threadExitUncaughtException(self, group);
2231
2232 /*
2233 * Remove the thread from the thread group.
2234 */
2235 if (group != NULL) {
2236 Method* removeThread =
2237 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2238 JValue unused;
2239 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2240 }
2241
2242 /*
2243 * Clear the vmThread reference in the Thread object. Interpreted code
2244 * will now see that this Thread is not running. As this may be the
2245 * only reference to the VMThread object that the VM knows about, we
2246 * have to create an internal reference to it first.
2247 */
2248 vmThread = dvmGetFieldObject(self->threadObj,
2249 gDvm.offJavaLangThread_vmThread);
2250 dvmAddTrackedAlloc(vmThread, self);
2251 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2252
2253 /* clear out our struct Thread pointer, since it's going away */
2254 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2255
2256 /*
2257 * Tell the debugger & DDM. This may cause the current thread or all
2258 * threads to suspend.
2259 *
2260 * The JDWP spec is somewhat vague about when this happens, other than
2261 * that it's issued by the dying thread, which may still appear in
2262 * an "all threads" listing.
2263 */
2264 if (gDvm.debuggerConnected)
2265 dvmDbgPostThreadDeath(self);
2266
2267 /*
2268 * Thread.join() is implemented as an Object.wait() on the VMThread
2269 * object. Signal anyone who is waiting.
2270 */
2271 dvmLockObject(self, vmThread);
2272 dvmObjectNotifyAll(self, vmThread);
2273 dvmUnlockObject(self, vmThread);
2274
2275 dvmReleaseTrackedAlloc(vmThread, self);
2276 vmThread = NULL;
2277
2278 /*
2279 * We're done manipulating objects, so it's okay if the GC runs in
2280 * parallel with us from here out. It's important to do this if
2281 * profiling is enabled, since we can wait indefinitely.
2282 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002283 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002284
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002285 /*
2286 * If we're doing method trace profiling, we don't want threads to exit,
2287 * because if they do we'll end up reusing thread IDs. This complicates
2288 * analysis and makes it impossible to have reasonable output in the
2289 * "threads" section of the "key" file.
2290 *
2291 * We need to do this after Thread.join() completes, or other threads
2292 * could get wedged. Since self->threadObj is still valid, the Thread
2293 * object will not get GCed even though we're no longer in the ThreadGroup
2294 * list (which is important since the profiling thread needs to get
2295 * the thread's name).
2296 */
2297 MethodTraceState* traceState = &gDvm.methodTrace;
2298
2299 dvmLockMutex(&traceState->startStopLock);
2300 if (traceState->traceEnabled) {
2301 LOGI("threadid=%d: waiting for method trace to finish\n",
2302 self->threadId);
2303 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002304 dvmWaitCond(&traceState->threadExitCond,
2305 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002306 }
2307 }
2308 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002309
2310 dvmLockThreadList(self);
2311
2312 /*
2313 * Lose the JNI context.
2314 */
2315 dvmDestroyJNIEnv(self->jniEnv);
2316 self->jniEnv = NULL;
2317
2318 self->status = THREAD_ZOMBIE;
2319
2320 /*
2321 * Remove ourselves from the internal thread list.
2322 */
2323 unlinkThread(self);
2324
2325 /*
2326 * If we're the last one standing, signal anybody waiting in
2327 * DestroyJavaVM that it's okay to exit.
2328 */
2329 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2330 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2331
2332 if (gDvm.nonDaemonThreadCount == 0) {
2333 int cc;
2334
2335 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2336 //dvmDumpAllThreads(false);
2337 // cond var guarded by threadListLock, which we already hold
2338 cc = pthread_cond_signal(&gDvm.vmExitCond);
2339 assert(cc == 0);
2340 }
2341 }
2342
2343 LOGV("threadid=%d: bye!\n", self->threadId);
2344 releaseThreadId(self);
2345 dvmUnlockThreadList();
2346
2347 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002348
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002349 freeThread(self);
2350}
2351
2352
2353/*
2354 * Suspend a single thread. Do not use to suspend yourself.
2355 *
2356 * This is used primarily for debugger/DDMS activity. Does not return
2357 * until the thread has suspended or is in a "safe" state (e.g. executing
2358 * native code outside the VM).
2359 *
2360 * The thread list lock should be held before calling here -- it's not
2361 * entirely safe to hang on to a Thread* from another thread otherwise.
2362 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2363 */
2364void dvmSuspendThread(Thread* thread)
2365{
2366 assert(thread != NULL);
2367 assert(thread != dvmThreadSelf());
2368 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2369
2370 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002371 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002372 thread->dbgSuspendCount++;
2373
2374 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2375 thread->threadId, thread->suspendCount);
2376 unlockThreadSuspendCount();
2377
2378 waitForThreadSuspend(dvmThreadSelf(), thread);
2379}
2380
2381/*
2382 * Reduce the suspend count of a thread. If it hits zero, tell it to
2383 * resume.
2384 *
2385 * Used primarily for debugger/DDMS activity. The thread in question
2386 * might have been suspended singly or as part of a suspend-all operation.
2387 *
2388 * The thread list lock should be held before calling here -- it's not
2389 * entirely safe to hang on to a Thread* from another thread otherwise.
2390 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2391 */
2392void dvmResumeThread(Thread* thread)
2393{
2394 assert(thread != NULL);
2395 assert(thread != dvmThreadSelf());
2396 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2397
2398 lockThreadSuspendCount();
2399 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002400 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002401 thread->dbgSuspendCount--;
2402 } else {
2403 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2404 thread->threadId);
2405 }
2406
2407 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2408 thread->threadId, thread->suspendCount);
2409
2410 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002411 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002412 }
2413
2414 unlockThreadSuspendCount();
2415}
2416
2417/*
2418 * Suspend yourself, as a result of debugger activity.
2419 */
2420void dvmSuspendSelf(bool jdwpActivity)
2421{
2422 Thread* self = dvmThreadSelf();
2423
Andy McFadden6dce9962010-08-23 16:45:24 -07002424 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002425 assert(gDvm.jdwpState != NULL);
2426 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2427 assert(false);
2428 return;
2429 }
2430
2431 /*
2432 * Collisions with other suspends aren't really interesting. We want
2433 * to ensure that we're the only one fiddling with the suspend count
2434 * though.
2435 */
2436 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002437 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002438 self->dbgSuspendCount++;
2439
2440 /*
2441 * Suspend ourselves.
2442 */
2443 assert(self->suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002444 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002445 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2446
2447 /*
2448 * Tell JDWP that we've completed suspension. The JDWP thread can't
2449 * tell us to resume before we're fully asleep because we hold the
2450 * suspend count lock.
2451 *
2452 * If we got here via waitForDebugger(), don't do this part.
2453 */
2454 if (jdwpActivity) {
2455 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2456 // self->threadId, (int) self->handle);
2457 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2458 }
2459
2460 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002461 dvmWaitCond(&gDvm.threadSuspendCountCond,
2462 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002463 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002464 /*
2465 * The condition was signaled but we're still suspended. This
2466 * can happen if the debugger lets go while a SIGQUIT thread
2467 * dump event is pending (assuming SignalCatcher was resumed for
2468 * just long enough to try to grab the thread-suspend lock).
2469 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002470 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
2471 self->threadId, self->suspendCount, self->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002472 }
2473 }
2474 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002475 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002476 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2477 self->threadId, self->status);
2478
2479 unlockThreadSuspendCount();
2480}
2481
2482
2483#ifdef HAVE_GLIBC
2484# define NUM_FRAMES 20
2485# include <execinfo.h>
2486/*
2487 * glibc-only stack dump function. Requires link with "--export-dynamic".
2488 *
2489 * TODO: move this into libs/cutils and make it work for all platforms.
2490 */
2491static void printBackTrace(void)
2492{
2493 void* array[NUM_FRAMES];
2494 size_t size;
2495 char** strings;
2496 size_t i;
2497
2498 size = backtrace(array, NUM_FRAMES);
2499 strings = backtrace_symbols(array, size);
2500
2501 LOGW("Obtained %zd stack frames.\n", size);
2502
2503 for (i = 0; i < size; i++)
2504 LOGW("%s\n", strings[i]);
2505
2506 free(strings);
2507}
2508#else
2509static void printBackTrace(void) {}
2510#endif
2511
2512/*
2513 * Dump the state of the current thread and that of another thread that
2514 * we think is wedged.
2515 */
2516static void dumpWedgedThread(Thread* thread)
2517{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002518 dvmDumpThread(dvmThreadSelf(), false);
2519 printBackTrace();
2520
2521 // dumping a running thread is risky, but could be useful
2522 dvmDumpThread(thread, true);
2523
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002524 // stop now and get a core dump
2525 //abort();
2526}
2527
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002528/*
2529 * If the thread is running at below-normal priority, temporarily elevate
2530 * it to "normal".
2531 *
2532 * Returns zero if no changes were made. Otherwise, returns bit flags
2533 * indicating what was changed, storing the previous values in the
2534 * provided locations.
2535 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002536int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002537 SchedPolicy* pSavedThreadPolicy)
2538{
2539 errno = 0;
2540 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2541 if (errno != 0) {
2542 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2543 thread->threadId, thread->systemTid);
2544 return 0;
2545 }
2546 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2547 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2548 thread->threadId, thread->systemTid);
2549 return 0;
2550 }
2551
2552 int changeFlags = 0;
2553
2554 /*
2555 * Change the priority if we're in the background group.
2556 */
2557 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2558 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2559 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2560 } else {
2561 changeFlags |= kChangedPolicy;
2562 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2563 thread->systemTid, *pSavedThreadPolicy);
2564 }
2565 }
2566
2567 /*
2568 * getpriority() returns the "nice" value, so larger numbers indicate
2569 * lower priority, with 0 being normal.
2570 */
2571 if (*pSavedThreadPrio > 0) {
2572 const int kHigher = 0;
2573 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2574 LOGW("Couldn't raise priority on tid %d to %d\n",
2575 thread->systemTid, kHigher);
2576 } else {
2577 changeFlags |= kChangedPriority;
2578 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2579 thread->systemTid, *pSavedThreadPrio, kHigher);
2580 }
2581 }
2582
2583 return changeFlags;
2584}
2585
2586/*
2587 * Reset the priority values for the thread in question.
2588 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002589void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002590 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2591{
2592 if ((changeFlags & kChangedPolicy) != 0) {
2593 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2594 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2595 thread->systemTid, savedThreadPolicy);
2596 } else {
2597 LOGD("Restored policy of %d to %d\n",
2598 thread->systemTid, savedThreadPolicy);
2599 }
2600 }
2601
2602 if ((changeFlags & kChangedPriority) != 0) {
2603 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2604 {
2605 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2606 thread->systemTid, savedThreadPrio);
2607 } else {
2608 LOGD("Restored priority on %d to %d\n",
2609 thread->systemTid, savedThreadPrio);
2610 }
2611 }
2612}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002613
2614/*
2615 * Wait for another thread to see the pending suspension and stop running.
2616 * It can either suspend itself or go into a non-running state such as
2617 * VMWAIT or NATIVE in which it cannot interact with the GC.
2618 *
2619 * If we're running at a higher priority, sched_yield() may not do anything,
2620 * so we need to sleep for "long enough" to guarantee that the other
2621 * thread has a chance to finish what it's doing. Sleeping for too short
2622 * a period (e.g. less than the resolution of the sleep clock) might cause
2623 * the scheduler to return immediately, so we want to start with a
2624 * "reasonable" value and expand.
2625 *
2626 * This does not return until the other thread has stopped running.
2627 * Eventually we time out and the VM aborts.
2628 *
2629 * This does not try to detect the situation where two threads are
2630 * waiting for each other to suspend. In normal use this is part of a
2631 * suspend-all, which implies that the suspend-all lock is held, or as
2632 * part of a debugger action in which the JDWP thread is always the one
2633 * doing the suspending. (We may need to re-evaluate this now that
2634 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2635 *
2636 * TODO: track basic stats about time required to suspend VM.
2637 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002638#define FIRST_SLEEP (250*1000) /* 0.25s */
2639#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002640static void waitForThreadSuspend(Thread* self, Thread* thread)
2641{
2642 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002643 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002644 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002645 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002646 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002647 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002648
2649 int sleepIter = 0;
2650 int retryCount = 0;
2651 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002652 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002653
Andy McFadden6dce9962010-08-23 16:45:24 -07002654 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002655 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002656 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002657 if (firstStartWhen == 0) // first iteration of first attempt
2658 firstStartWhen = startWhen;
2659
2660 /*
2661 * After waiting for a bit, check to see if the target thread is
2662 * running at a reduced priority. If so, bump it up temporarily
2663 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002664 */
2665 if (retryCount == 2) {
2666 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002667 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002668 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002669 }
2670 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002671
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002672#if defined (WITH_JIT)
2673 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002674 * If we're still waiting after the first timeout, unchain all
2675 * translations iff:
2676 * 1) There are new chains formed since the last unchain
2677 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002678 */
Ben Cheng6999d842010-01-26 16:46:15 -08002679 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2680 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002681 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002682 dvmJitUnchainAll();
2683 }
2684#endif
2685
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002686 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002687 * Sleep briefly. The iterative sleep call returns false if we've
2688 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002689 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002690 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002691 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002692 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002693 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002694 thread->threadId, priChangeFlags);
2695 if (retryCount > 1) {
2696 /* stack trace logging is slow; skip on first iter */
2697 dumpWedgedThread(thread);
2698 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002699 complained = true;
2700 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002701
2702 // keep going; could be slow due to valgrind
2703 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002704 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002705
2706 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002707 LOGE("Fatal spin-on-suspend, dumping threads\n");
2708 dvmDumpAllThreads(false);
2709
2710 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002711 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2712 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002713
2714 /* try to get a debuggerd dump from the spinning thread */
2715 dvmNukeThread(thread);
2716 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002717 dvmAbort();
2718 }
2719 }
2720 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002721
2722 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002723 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2724 self->threadId,
2725 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002726 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2727 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002728 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002729 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002730 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002731 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002732}
2733
2734/*
2735 * Suspend all threads except the current one. This is used by the GC,
2736 * the debugger, and by any thread that hits a "suspend all threads"
2737 * debugger event (e.g. breakpoint or exception).
2738 *
2739 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2740 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2741 * create objects and even execute arbitrary code. The "why" argument
2742 * allows the caller to say why the suspension is taking place.
2743 *
2744 * This can be called when a global suspend has already happened, due to
2745 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2746 * doesn't work.
2747 *
2748 * DO NOT grab any locks before calling here. We grab & release the thread
2749 * lock and suspend lock here (and we're not using recursive threads), and
2750 * we might have to self-suspend if somebody else beats us here.
2751 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002752 * We know the current thread is in the thread list, because we attach the
2753 * thread before doing anything that could cause VM suspension (like object
2754 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002755 */
2756void dvmSuspendAllThreads(SuspendCause why)
2757{
2758 Thread* self = dvmThreadSelf();
2759 Thread* thread;
2760
2761 assert(why != 0);
2762
2763 /*
2764 * Start by grabbing the thread suspend lock. If we can't get it, most
2765 * likely somebody else is in the process of performing a suspend or
2766 * resume, so lockThreadSuspend() will cause us to self-suspend.
2767 *
2768 * We keep the lock until all other threads are suspended.
2769 */
2770 lockThreadSuspend("susp-all", why);
2771
2772 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2773
2774 /*
2775 * This is possible if the current thread was in VMWAIT mode when a
2776 * suspend-all happened, and then decided to do its own suspend-all.
2777 * This can happen when a couple of threads have simultaneous events
2778 * of interest to the debugger.
2779 */
2780 //assert(self->suspendCount == 0);
2781
2782 /*
2783 * Increment everybody's suspend count (except our own).
2784 */
2785 dvmLockThreadList(self);
2786
2787 lockThreadSuspendCount();
2788 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2789 if (thread == self)
2790 continue;
2791
2792 /* debugger events don't suspend JDWP thread */
2793 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2794 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2795 continue;
2796
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002797 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002798 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2799 thread->dbgSuspendCount++;
2800 }
2801 unlockThreadSuspendCount();
2802
2803 /*
2804 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2805 * indicate the code is either running natively or sleeping quietly.
2806 * Any attempt to transition back to THREAD_RUNNING will cause a check
2807 * for suspension, so it should be impossible for anything to execute
2808 * interpreted code or modify objects (assuming native code plays nicely).
2809 *
2810 * It's also okay if the thread transitions to a non-RUNNING state.
2811 *
2812 * Note we released the threadSuspendCountLock before getting here,
2813 * so if another thread is fiddling with its suspend count (perhaps
2814 * self-suspending for the debugger) it won't block while we're waiting
2815 * in here.
2816 */
2817 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2818 if (thread == self)
2819 continue;
2820
2821 /* debugger events don't suspend JDWP thread */
2822 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2823 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2824 continue;
2825
2826 /* wait for the other thread to see the pending suspend */
2827 waitForThreadSuspend(self, thread);
2828
Andy McFadden6dce9962010-08-23 16:45:24 -07002829 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002830 self->threadId,
2831 thread->threadId, thread->status, thread->suspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07002832 thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002833 }
2834
2835 dvmUnlockThreadList();
2836 unlockThreadSuspend();
2837
2838 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2839}
2840
2841/*
2842 * Resume all threads that are currently suspended.
2843 *
2844 * The "why" must match with the previous suspend.
2845 */
2846void dvmResumeAllThreads(SuspendCause why)
2847{
2848 Thread* self = dvmThreadSelf();
2849 Thread* thread;
2850 int cc;
2851
2852 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2853 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2854
2855 /*
2856 * Decrement the suspend counts for all threads. No need for atomic
2857 * writes, since nobody should be moving until we decrement the count.
2858 * We do need to hold the thread list because of JNI attaches.
2859 */
2860 dvmLockThreadList(self);
2861 lockThreadSuspendCount();
2862 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2863 if (thread == self)
2864 continue;
2865
2866 /* debugger events don't suspend JDWP thread */
2867 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2868 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002869 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002870 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002871 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002872
2873 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002874 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002875 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2876 thread->dbgSuspendCount--;
2877 } else {
2878 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2879 thread->threadId);
2880 }
2881 }
2882 unlockThreadSuspendCount();
2883 dvmUnlockThreadList();
2884
2885 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002886 * In some ways it makes sense to continue to hold the thread-suspend
2887 * lock while we issue the wakeup broadcast. It allows us to complete
2888 * one operation before moving on to the next, which simplifies the
2889 * thread activity debug traces.
2890 *
2891 * This approach caused us some difficulty under Linux, because the
2892 * condition variable broadcast not only made the threads runnable,
2893 * but actually caused them to execute, and it was a while before
2894 * the thread performing the wakeup had an opportunity to release the
2895 * thread-suspend lock.
2896 *
2897 * This is a problem because, when a thread tries to acquire that
2898 * lock, it times out after 3 seconds. If at some point the thread
2899 * is told to suspend, the clock resets; but since the VM is still
2900 * theoretically mid-resume, there's no suspend pending. If, for
2901 * example, the GC was waking threads up while the SIGQUIT handler
2902 * was trying to acquire the lock, we would occasionally time out on
2903 * a busy system and SignalCatcher would abort.
2904 *
2905 * We now perform the unlock before the wakeup broadcast. The next
2906 * suspend can't actually start until the broadcast completes and
2907 * returns, because we're holding the thread-suspend-count lock, but the
2908 * suspending thread is now able to make progress and we avoid the abort.
2909 *
2910 * (Technically there is a narrow window between when we release
2911 * the thread-suspend lock and grab the thread-suspend-count lock.
2912 * This could cause us to send a broadcast to threads with nonzero
2913 * suspend counts, but this is expected and they'll all just fall
2914 * right back to sleep. It's probably safe to grab the suspend-count
2915 * lock before releasing thread-suspend, since we're still following
2916 * the correct order of acquisition, but it feels weird.)
2917 */
2918
2919 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2920 unlockThreadSuspend();
2921
2922 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002923 * Broadcast a notification to all suspended threads, some or all of
2924 * which may choose to wake up. No need to wait for them.
2925 */
2926 lockThreadSuspendCount();
2927 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2928 assert(cc == 0);
2929 unlockThreadSuspendCount();
2930
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002931 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2932}
2933
2934/*
2935 * Undo any debugger suspensions. This is called when the debugger
2936 * disconnects.
2937 */
2938void dvmUndoDebuggerSuspensions(void)
2939{
2940 Thread* self = dvmThreadSelf();
2941 Thread* thread;
2942 int cc;
2943
2944 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2945 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2946
2947 /*
2948 * Decrement the suspend counts for all threads. No need for atomic
2949 * writes, since nobody should be moving until we decrement the count.
2950 * We do need to hold the thread list because of JNI attaches.
2951 */
2952 dvmLockThreadList(self);
2953 lockThreadSuspendCount();
2954 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2955 if (thread == self)
2956 continue;
2957
2958 /* debugger events don't suspend JDWP thread */
2959 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2960 assert(thread->dbgSuspendCount == 0);
2961 continue;
2962 }
2963
2964 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002965 dvmAddToThreadSuspendCount(&thread->suspendCount,
2966 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002967 thread->dbgSuspendCount = 0;
2968 }
2969 unlockThreadSuspendCount();
2970 dvmUnlockThreadList();
2971
2972 /*
2973 * Broadcast a notification to all suspended threads, some or all of
2974 * which may choose to wake up. No need to wait for them.
2975 */
2976 lockThreadSuspendCount();
2977 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2978 assert(cc == 0);
2979 unlockThreadSuspendCount();
2980
2981 unlockThreadSuspend();
2982
2983 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2984}
2985
2986/*
2987 * Determine if a thread is suspended.
2988 *
2989 * As with all operations on foreign threads, the caller should hold
2990 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002991 *
2992 * If the thread is suspending or waking, these fields could be changing
2993 * out from under us (or the thread could change state right after we
2994 * examine it), making this generally unreliable. This is chiefly
2995 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002996 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002997bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002998{
2999 /*
3000 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07003001 * (1) Running happily. status is RUNNING, suspendCount is zero.
3002 * Return "false".
3003 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
3004 * Return "false".
3005 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003006 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07003007 * (4) Waking up. suspendCount is zero, status is SUSPENDED
3008 * Return "false" (since it could change out from under us, unless
3009 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003010 */
3011
Andy McFadden6dce9962010-08-23 16:45:24 -07003012 return (thread->suspendCount != 0 && thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003013}
3014
3015/*
3016 * Wait until another thread self-suspends. This is specifically for
3017 * synchronization between the JDWP thread and a thread that has decided
3018 * to suspend itself after sending an event to the debugger.
3019 *
3020 * Threads that encounter "suspend all" events work as well -- the thread
3021 * in question suspends everybody else and then itself.
3022 *
3023 * We can't hold a thread lock here or in the caller, because we could
3024 * get here just before the to-be-waited-for-thread issues a "suspend all".
3025 * There's an opportunity for badness if the thread we're waiting for exits
3026 * and gets cleaned up, but since the thread in question is processing a
3027 * debugger event, that's not really a possibility. (To avoid deadlock,
3028 * it's important that we not be in THREAD_RUNNING while we wait.)
3029 */
3030void dvmWaitForSuspend(Thread* thread)
3031{
3032 Thread* self = dvmThreadSelf();
3033
3034 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3035 self->threadId, thread->threadId);
3036
3037 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3038 assert(thread != self);
3039 assert(self->status != THREAD_RUNNING);
3040
3041 waitForThreadSuspend(self, thread);
3042
3043 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3044 self->threadId, thread->threadId);
3045}
3046
3047/*
3048 * Check to see if we need to suspend ourselves. If so, go to sleep on
3049 * a condition variable.
3050 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003051 * Returns "true" if we suspended ourselves.
3052 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003053static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003054{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003055 assert(self != NULL);
3056 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003057
Andy McFadden6dce9962010-08-23 16:45:24 -07003058 /*
3059 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
3060 * access to self->suspendCount.
3061 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003062 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3063
Andy McFadden6dce9962010-08-23 16:45:24 -07003064 bool needSuspend = (self->suspendCount != 0);
3065 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07003066 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07003067 ThreadStatus oldStatus = self->status; /* should be RUNNING */
3068 self->status = THREAD_SUSPENDED;
3069
Andy McFadden3469a7e2010-08-04 16:09:10 -07003070 while (self->suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003071 /*
3072 * Wait for wakeup signal, releasing lock. The act of releasing
3073 * and re-acquiring the lock provides the memory barriers we
3074 * need for correct behavior on SMP.
3075 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07003076 dvmWaitCond(&gDvm.threadSuspendCountCond,
3077 &gDvm.threadSuspendCountLock);
3078 }
3079 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07003080 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07003081 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3082 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003083 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003084
3085 unlockThreadSuspendCount();
3086
Andy McFadden6dce9962010-08-23 16:45:24 -07003087 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003088}
3089
3090/*
Andy McFadden6dce9962010-08-23 16:45:24 -07003091 * Check to see if a suspend is pending. If so, suspend the current
3092 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003093 */
3094bool dvmCheckSuspendPending(Thread* self)
3095{
Andy McFadden6dce9962010-08-23 16:45:24 -07003096 assert(self != NULL);
3097 if (self->suspendCount == 0) {
3098 return false;
3099 } else {
3100 return fullSuspendCheck(self);
3101 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003102}
3103
3104/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003105 * Update our status.
3106 *
3107 * The "self" argument, which may be NULL, is accepted as an optimization.
3108 *
3109 * Returns the old status.
3110 */
3111ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3112{
3113 ThreadStatus oldStatus;
3114
3115 if (self == NULL)
3116 self = dvmThreadSelf();
3117
3118 LOGVV("threadid=%d: (status %d -> %d)\n",
3119 self->threadId, self->status, newStatus);
3120
3121 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07003122 if (oldStatus == newStatus)
3123 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003124
3125 if (newStatus == THREAD_RUNNING) {
3126 /*
3127 * Change our status to THREAD_RUNNING. The transition requires
3128 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003129 * us to be "asleep" in all other states, and another thread could
3130 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003131 *
Andy McFadden6dce9962010-08-23 16:45:24 -07003132 * The order of operations is very significant here. One way to
3133 * do this wrong is:
3134 *
3135 * GCing thread Our thread (in NATIVE)
3136 * ------------ ----------------------
3137 * check suspend count (== 0)
3138 * dvmSuspendAllThreads()
3139 * grab suspend-count lock
3140 * increment all suspend counts
3141 * release suspend-count lock
3142 * check thread state (== NATIVE)
3143 * all are suspended, begin GC
3144 * set state to RUNNING
3145 * (continue executing)
3146 *
3147 * We can correct this by grabbing the suspend-count lock and
3148 * performing both of our operations (check suspend count, set
3149 * state) while holding it, now we need to grab a mutex on every
3150 * transition to RUNNING.
3151 *
3152 * What we do instead is change the order of operations so that
3153 * the transition to RUNNING happens first. If we then detect
3154 * that the suspend count is nonzero, we switch to SUSPENDED.
3155 *
3156 * Appropriate compiler and memory barriers are required to ensure
3157 * that the operations are observed in the expected order.
3158 *
3159 * This does create a small window of opportunity where a GC in
3160 * progress could observe what appears to be a running thread (if
3161 * it happens to look between when we set to RUNNING and when we
3162 * switch to SUSPENDED). At worst this only affects assertions
3163 * and thread logging. (We could work around it with some sort
3164 * of intermediate "pre-running" state that is generally treated
3165 * as equivalent to running, but that doesn't seem worthwhile.)
3166 *
3167 * We can also solve this by combining the "status" and "suspend
3168 * count" fields into a single 32-bit value. This trades the
3169 * store/load barrier on transition to RUNNING for an atomic RMW
3170 * op on all transitions and all suspend count updates (also, all
3171 * accesses to status or the thread count require bit-fiddling).
3172 * It also eliminates the brief transition through RUNNING when
3173 * the thread is supposed to be suspended. This is possibly faster
3174 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003175 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003176 android_atomic_acquire_store(newStatus, &self->status);
3177 if (self->suspendCount != 0) {
3178 fullSuspendCheck(self);
3179 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003180 } else {
3181 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003182 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003183 *
3184 * We use a releasing store to ensure that, if we were RUNNING,
3185 * any updates we previously made to objects on the managed heap
3186 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003187 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003188 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003189 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003190 }
3191
3192 return oldStatus;
3193}
3194
3195/*
3196 * Get a statically defined thread group from a field in the ThreadGroup
3197 * Class object. Expected arguments are "mMain" and "mSystem".
3198 */
3199static Object* getStaticThreadGroup(const char* fieldName)
3200{
3201 StaticField* groupField;
3202 Object* groupObj;
3203
3204 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3205 fieldName, "Ljava/lang/ThreadGroup;");
3206 if (groupField == NULL) {
3207 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3208 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3209 return NULL;
3210 }
3211 groupObj = dvmGetStaticFieldObject(groupField);
3212 if (groupObj == NULL) {
3213 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3214 dvmThrowException("Ljava/lang/InternalError;", NULL);
3215 return NULL;
3216 }
3217
3218 return groupObj;
3219}
3220Object* dvmGetSystemThreadGroup(void)
3221{
3222 return getStaticThreadGroup("mSystem");
3223}
3224Object* dvmGetMainThreadGroup(void)
3225{
3226 return getStaticThreadGroup("mMain");
3227}
3228
3229/*
3230 * Given a VMThread object, return the associated Thread*.
3231 *
3232 * NOTE: if the thread detaches, the struct Thread will disappear, and
3233 * we will be touching invalid data. For safety, lock the thread list
3234 * before calling this.
3235 */
3236Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3237{
3238 int vmData;
3239
3240 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003241
3242 if (false) {
3243 Thread* thread = gDvm.threadList;
3244 while (thread != NULL) {
3245 if ((Thread*)vmData == thread)
3246 break;
3247
3248 thread = thread->next;
3249 }
3250
3251 if (thread == NULL) {
3252 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3253 vmThreadObj, (Thread*)vmData);
3254 vmData = 0;
3255 }
3256 }
3257
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003258 return (Thread*) vmData;
3259}
3260
Andy McFadden2b94b302010-03-09 16:38:36 -08003261/*
3262 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003263 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003264 *
3265 * Returns NULL if the thread was not found.
3266 */
3267Thread* dvmGetThreadByHandle(pthread_t handle)
3268{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003269 Thread* thread;
3270 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003271 if (thread->handle == handle)
3272 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003273 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003274 return thread;
3275}
Andy McFadden2b94b302010-03-09 16:38:36 -08003276
Andy McFadden0a24ef92010-03-12 13:39:59 -08003277/*
3278 * Given a threadId, return the associated Thread*.
3279 * Caller must hold the thread list lock.
3280 *
3281 * Returns NULL if the thread was not found.
3282 */
3283Thread* dvmGetThreadByThreadId(u4 threadId)
3284{
3285 Thread* thread;
3286 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3287 if (thread->threadId == threadId)
3288 break;
3289 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003290 return thread;
3291}
3292
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003293
3294/*
3295 * Conversion map for "nice" values.
3296 *
3297 * We use Android thread priority constants to be consistent with the rest
3298 * of the system. In some cases adjacent entries may overlap.
3299 */
3300static const int kNiceValues[10] = {
3301 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3302 ANDROID_PRIORITY_BACKGROUND + 6,
3303 ANDROID_PRIORITY_BACKGROUND + 3,
3304 ANDROID_PRIORITY_BACKGROUND,
3305 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3306 ANDROID_PRIORITY_NORMAL - 2,
3307 ANDROID_PRIORITY_NORMAL - 4,
3308 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3309 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3310 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3311};
3312
3313/*
3314 * Change the priority of a system thread to match that of the Thread object.
3315 *
3316 * We map a priority value from 1-10 to Linux "nice" values, where lower
3317 * numbers indicate higher priority.
3318 */
3319void dvmChangeThreadPriority(Thread* thread, int newPriority)
3320{
3321 pid_t pid = thread->systemTid;
3322 int newNice;
3323
3324 if (newPriority < 1 || newPriority > 10) {
3325 LOGW("bad priority %d\n", newPriority);
3326 newPriority = 5;
3327 }
3328 newNice = kNiceValues[newPriority-1];
3329
Andy McFaddend62c0b52009-08-04 15:02:12 -07003330 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003331 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003332 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003333 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003334 }
3335
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003336 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3337 char* str = dvmGetThreadName(thread);
3338 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3339 pid, str, newPriority, newNice, strerror(errno));
3340 free(str);
3341 } else {
3342 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3343 pid, newPriority, newNice);
3344 }
3345}
3346
3347/*
3348 * Get the thread priority for the current thread by querying the system.
3349 * This is useful when attaching a thread through JNI.
3350 *
3351 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3352 */
3353static int getThreadPriorityFromSystem(void)
3354{
3355 int i, sysprio, jprio;
3356
3357 errno = 0;
3358 sysprio = getpriority(PRIO_PROCESS, 0);
3359 if (sysprio == -1 && errno != 0) {
3360 LOGW("getpriority() failed: %s\n", strerror(errno));
3361 return THREAD_NORM_PRIORITY;
3362 }
3363
3364 jprio = THREAD_MIN_PRIORITY;
3365 for (i = 0; i < NELEM(kNiceValues); i++) {
3366 if (sysprio >= kNiceValues[i])
3367 break;
3368 jprio++;
3369 }
3370 if (jprio > THREAD_MAX_PRIORITY)
3371 jprio = THREAD_MAX_PRIORITY;
3372
3373 return jprio;
3374}
3375
3376
3377/*
3378 * Return true if the thread is on gDvm.threadList.
3379 * Caller should not hold gDvm.threadListLock.
3380 */
3381bool dvmIsOnThreadList(const Thread* thread)
3382{
3383 bool ret = false;
3384
3385 dvmLockThreadList(NULL);
3386 if (thread == gDvm.threadList) {
3387 ret = true;
3388 } else {
3389 ret = thread->prev != NULL || thread->next != NULL;
3390 }
3391 dvmUnlockThreadList();
3392
3393 return ret;
3394}
3395
3396/*
3397 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3398 * output target.
3399 */
3400void dvmDumpThread(Thread* thread, bool isRunning)
3401{
3402 DebugOutputTarget target;
3403
3404 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3405 dvmDumpThreadEx(&target, thread, isRunning);
3406}
3407
3408/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003409 * Try to get the scheduler group.
3410 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003411 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003412 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003413 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003414 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003415 * We return the part on the "cpu" line after the '/', which will be an
3416 * empty string for the default cgroup. If the string is longer than
3417 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003418 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003419 * On error, -1 is returned, and an error description will be stored in
3420 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003421 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003422static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003423{
3424#ifdef HAVE_ANDROID_OS
3425 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003426 char lineBuf[256];
3427 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003428
Andy McFadden7f64ede2010-03-03 15:37:10 -08003429 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003430 if ((fp = fopen(pathBuf, "r")) == NULL) {
3431 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003432 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003433 }
3434
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003435 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3436 char* subsys;
3437 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003438 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003439
Andy McFadden7f64ede2010-03-03 15:37:10 -08003440 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003441 subsys = strchr(lineBuf, ':');
3442 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003443 goto out_bad_data;
3444 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003445
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003446 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003447 /* Not the subsys we're looking for */
3448 continue;
3449 }
3450
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003451 grp = strchr(subsys, '/');
3452 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003453 goto out_bad_data;
3454 }
3455 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003456
Andy McFadden7f64ede2010-03-03 15:37:10 -08003457 len = strlen(grp);
3458 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3459
3460 if (bufLen <= len) {
3461 len = bufLen - 1;
3462 }
3463 strncpy(buf, grp, len);
3464 buf[len] = '\0';
3465 fclose(fp);
3466 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003467 }
3468
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003469 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003470 fclose(fp);
3471 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003472
3473out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003474 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003475 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003476 fclose(fp);
3477 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003478
Andy McFaddend62c0b52009-08-04 15:02:12 -07003479#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003480 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003481 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003482#endif
3483}
3484
3485/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003486 * Convert ThreadStatus to a string.
3487 */
3488const char* dvmGetThreadStatusStr(ThreadStatus status)
3489{
3490 switch (status) {
3491 case THREAD_ZOMBIE: return "ZOMBIE";
3492 case THREAD_RUNNING: return "RUNNABLE";
3493 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3494 case THREAD_MONITOR: return "MONITOR";
3495 case THREAD_WAIT: return "WAIT";
3496 case THREAD_INITIALIZING: return "INITIALIZING";
3497 case THREAD_STARTING: return "STARTING";
3498 case THREAD_NATIVE: return "NATIVE";
3499 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003500 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003501 default: return "UNKNOWN";
3502 }
3503}
3504
3505/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003506 * Print information about the specified thread.
3507 *
3508 * Works best when the thread in question is "self" or has been suspended.
3509 * When dumping a separate thread that's still running, set "isRunning" to
3510 * use a more cautious thread dump function.
3511 */
3512void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3513 bool isRunning)
3514{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003515 Object* threadObj;
3516 Object* groupObj;
3517 StringObject* nameStr;
3518 char* threadName = NULL;
3519 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003520 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003521 bool isDaemon;
3522 int priority; // java.lang.Thread priority
3523 int policy; // pthread policy
3524 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003525 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003526
Andy McFaddene3346d82010-06-02 15:37:21 -07003527 /*
3528 * Get the java.lang.Thread object. This function gets called from
3529 * some weird debug contexts, so it's possible that there's a GC in
3530 * progress on some other thread. To decrease the chances of the
3531 * thread object being moved out from under us, we add the reference
3532 * to the tracked allocation list, which pins it in place.
3533 *
3534 * If threadObj is NULL, the thread is still in the process of being
3535 * attached to the VM, and there's really nothing interesting to
3536 * say about it yet.
3537 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003538 threadObj = thread->threadObj;
3539 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003540 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003541 return;
3542 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003543 dvmAddTrackedAlloc(threadObj, NULL);
3544
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003545 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3546 gDvm.offJavaLangThread_name);
3547 threadName = dvmCreateCstrFromString(nameStr);
3548
3549 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3550 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3551
3552 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3553 LOGW("Warning: pthread_getschedparam failed\n");
3554 policy = -1;
3555 sp.sched_priority = -1;
3556 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003557 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003558 sizeof(schedulerGroupBuf)) == 0 &&
3559 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003560 strcpy(schedulerGroupBuf, "default");
3561 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003562
3563 /* a null value for group is not expected, but deal with it anyway */
3564 groupObj = (Object*) dvmGetFieldObject(threadObj,
3565 gDvm.offJavaLangThread_group);
3566 if (groupObj != NULL) {
3567 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3568 "name", "Ljava/lang/String;");
3569 if (offset < 0) {
3570 LOGW("Unable to find 'name' field in ThreadGroup\n");
3571 } else {
3572 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3573 groupName = dvmCreateCstrFromString(nameStr);
3574 }
3575 }
3576 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003577 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003578
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003579 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003580 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003581 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003582 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3583#if defined(WITH_JIT)
3584 thread->inJitCodeCache ? " JIT" : ""
3585#else
3586 ""
3587#endif
3588 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003589 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003590 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003591 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07003592 thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003593 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003594 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003595 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003596 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003597
Andy McFadden0a3f6982010-08-31 13:50:08 -07003598 /* get some bits from /proc/self/stat */
3599 ProcStatData procStatData;
3600 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3601 /* failed, use zeroed values */
3602 memset(&procStatData, 0, sizeof(procStatData));
3603 }
3604
3605 /* grab the scheduler stats for this thread */
3606 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3607 thread->systemTid);
3608 int schedstatFd = open(schedstatBuf, O_RDONLY);
3609 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003610 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003611 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003612 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3613 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003614 if (bytes >= 1) {
3615 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003616 }
3617 }
3618
Andy McFadden0a3f6982010-08-31 13:50:08 -07003619 /* show what we got */
3620 dvmPrintDebugMessage(target,
3621 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3622 schedstatBuf, procStatData.utime, procStatData.stime,
3623 procStatData.processor);
3624
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003625 if (isRunning)
3626 dvmDumpRunningThreadStack(target, thread);
3627 else
3628 dvmDumpThreadStack(target, thread);
3629
Andy McFaddene3346d82010-06-02 15:37:21 -07003630 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003631 free(threadName);
3632 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003633}
3634
3635/*
3636 * Get the name of a thread.
3637 *
3638 * For correctness, the caller should hold the thread list lock to ensure
3639 * that the thread doesn't go away mid-call.
3640 *
3641 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3642 */
3643char* dvmGetThreadName(Thread* thread)
3644{
3645 StringObject* nameObj;
3646
3647 if (thread->threadObj == NULL) {
3648 LOGW("threadObj is NULL, name not available\n");
3649 return strdup("-unknown-");
3650 }
3651
3652 nameObj = (StringObject*)
3653 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3654 return dvmCreateCstrFromString(nameObj);
3655}
3656
3657/*
3658 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3659 * an output target.
3660 */
3661void dvmDumpAllThreads(bool grabLock)
3662{
3663 DebugOutputTarget target;
3664
3665 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3666 dvmDumpAllThreadsEx(&target, grabLock);
3667}
3668
3669/*
3670 * Print information about all known threads. Assumes they have been
3671 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3672 *
3673 * If "grabLock" is true, we grab the thread lock list. This is important
3674 * to do unless the caller already holds the lock.
3675 */
3676void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3677{
3678 Thread* thread;
3679
3680 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3681
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003682#ifdef HAVE_ANDROID_OS
3683 dvmPrintDebugMessage(target,
3684 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3685 gDvm.threadListLock.value,
3686 gDvm._threadSuspendLock.value,
3687 gDvm.threadSuspendCountLock.value,
3688 gDvm.gcHeapLock.value,
3689 gDvm.heapWorkerLock.value,
3690 gDvm.heapWorkerListLock.value);
3691#endif
3692
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003693 if (grabLock)
3694 dvmLockThreadList(dvmThreadSelf());
3695
3696 thread = gDvm.threadList;
3697 while (thread != NULL) {
3698 dvmDumpThreadEx(target, thread, false);
3699
3700 /* verify link */
3701 assert(thread->next == NULL || thread->next->prev == thread);
3702
3703 thread = thread->next;
3704 }
3705
3706 if (grabLock)
3707 dvmUnlockThreadList();
3708}
3709
Andy McFadden384ef6b2010-03-15 17:24:55 -07003710/*
3711 * Nuke the target thread from orbit.
3712 *
3713 * The idea is to send a "crash" signal to the target thread so that
3714 * debuggerd will take notice and dump an appropriate stack trace.
3715 * Because of the way debuggerd works, we have to throw the same signal
3716 * at it twice.
3717 *
3718 * This does not necessarily cause the entire process to stop, but once a
3719 * thread has been nuked the rest of the system is likely to be unstable.
3720 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003721 * performed, but it's advisable (and expected) to call dvmAbort soon.
3722 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003723 */
3724void dvmNukeThread(Thread* thread)
3725{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003726 int killResult;
3727
Andy McFaddena388a162010-03-18 16:27:14 -07003728 /* suppress the heapworker watchdog to assist anyone using a debugger */
3729 gDvm.nativeDebuggerActive = true;
3730
Andy McFadden384ef6b2010-03-15 17:24:55 -07003731 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003732 * Send the signals, separated by a brief interval to allow debuggerd
3733 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3734 * can be used instead of SIGSEGV to avoid making it look like the
3735 * code actually crashed at the current point of execution.
3736 *
3737 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3738 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3739 * you don't get the second stack trace; possibly something in the
3740 * kernel decides that a signal has already been sent and it's time
3741 * to just kill the process. The position in the current thread is
3742 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003743 *
Andy McFaddena388a162010-03-18 16:27:14 -07003744 * The target thread can continue to execute between the two signals.
3745 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003746 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003747 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3748 " cause debuggerd dump\n",
3749 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003750 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3751 if (killResult != 0) {
3752 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3753 }
Andy McFaddena388a162010-03-18 16:27:14 -07003754 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003755 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3756 if (killResult != 0) {
3757 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3758 }
Andy McFadden7122d862010-03-19 15:18:57 -07003759 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003760 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003761
3762 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3763 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003764 LOGD("Continuing\n");
3765}