blob: 94d049c9455d0969dba2c7baf78a88942c5fa21b [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
buzbeea7d59bb2011-02-24 09:38:17 -0800974#ifndef DVM_NO_ASM_INTERP
975 thread->mainHandlerTable = dvmAsmInstructionStart;
976 thread->altHandlerTable = dvmAsmAltInstructionStart;
977 thread->curHandlerTable = thread->mainHandlerTable;
978#endif
979
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800980 /* give the thread code a chance to set things up */
981 dvmInitInterpStack(thread, interpStackSize);
982
buzbee9f601a92011-02-11 17:48:20 -0800983 /* One-time setup for interpreter/JIT state */
984 dvmInitInterpreterState(thread);
985
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800986 return thread;
987}
988
989/*
990 * Get a meaningful thread ID. At present this only has meaning under Linux,
991 * where getpid() and gettid() sometimes agree and sometimes don't depending
992 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
993 */
994pid_t dvmGetSysThreadId(void)
995{
996#ifdef HAVE_GETTID
997 return gettid();
998#else
999 return getpid();
1000#endif
1001}
1002
1003/*
1004 * Finish initialization of a Thread struct.
1005 *
1006 * This must be called while executing in the new thread, but before the
1007 * thread is added to the thread list.
1008 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001009 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001010 * assignThreadId()).
1011 */
1012static bool prepareThread(Thread* thread)
1013{
1014 assignThreadId(thread);
1015 thread->handle = pthread_self();
1016 thread->systemTid = dvmGetSysThreadId();
1017
1018 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1019 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001020 /*
1021 * If we were called by dvmAttachCurrentThread, the self value is
1022 * already correctly established as "thread".
1023 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001024 setThreadSelf(thread);
1025
1026 LOGV("threadid=%d: interp stack at %p\n",
1027 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1028
1029 /*
1030 * Initialize invokeReq.
1031 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001032 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001033 pthread_cond_init(&thread->invokeReq.cv, NULL);
1034
1035 /*
1036 * Initialize our reference tracking tables.
1037 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001038 * Most threads won't use jniMonitorRefTable, so we clear out the
1039 * structure but don't call the init function (which allocs storage).
1040 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001041#ifdef USE_INDIRECT_REF
1042 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1043 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1044 return false;
1045#else
1046 /*
1047 * The JNI local ref table *must* be fixed-size because we keep pointers
1048 * into the table in our stack frames.
1049 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001050 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1051 kJniLocalRefMax, kJniLocalRefMax))
1052 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001053#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001054 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1055 kInternalRefDefault, kInternalRefMax))
1056 return false;
1057
1058 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1059
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001060 pthread_cond_init(&thread->waitCond, NULL);
1061 dvmInitMutex(&thread->waitMutex);
1062
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001063 return true;
1064}
1065
1066/*
1067 * Remove a thread from the internal list.
1068 * Clear out the links to make it obvious that the thread is
1069 * no longer on the list. Caller must hold gDvm.threadListLock.
1070 */
1071static void unlinkThread(Thread* thread)
1072{
1073 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1074 if (thread == gDvm.threadList) {
1075 assert(thread->prev == NULL);
1076 gDvm.threadList = thread->next;
1077 } else {
1078 assert(thread->prev != NULL);
1079 thread->prev->next = thread->next;
1080 }
1081 if (thread->next != NULL)
1082 thread->next->prev = thread->prev;
1083 thread->prev = thread->next = NULL;
1084}
1085
1086/*
1087 * Free a Thread struct, and all the stuff allocated within.
1088 */
1089static void freeThread(Thread* thread)
1090{
1091 if (thread == NULL)
1092 return;
1093
1094 /* thread->threadId is zero at this point */
1095 LOGVV("threadid=%d: freeing\n", thread->threadId);
1096
1097 if (thread->interpStackStart != NULL) {
1098 u1* interpStackBottom;
1099
1100 interpStackBottom = thread->interpStackStart;
1101 interpStackBottom -= thread->interpStackSize;
1102#ifdef MALLOC_INTERP_STACK
1103 free(interpStackBottom);
1104#else
1105 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1106 LOGW("munmap(thread stack) failed\n");
1107#endif
1108 }
1109
Andy McFaddend5ab7262009-08-25 07:19:34 -07001110#ifdef USE_INDIRECT_REF
1111 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1112#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001113 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001114#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001115 dvmClearReferenceTable(&thread->internalLocalRefTable);
1116 if (&thread->jniMonitorRefTable.table != NULL)
1117 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1118
Jeff Hao97319a82009-08-12 16:57:15 -07001119#if defined(WITH_SELF_VERIFICATION)
1120 dvmSelfVerificationShadowSpaceFree(thread);
1121#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001122 free(thread);
1123}
1124
1125/*
1126 * Like pthread_self(), but on a Thread*.
1127 */
1128Thread* dvmThreadSelf(void)
1129{
1130 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1131}
1132
1133/*
1134 * Explore our sense of self. Stuffs the thread pointer into TLS.
1135 */
1136static void setThreadSelf(Thread* thread)
1137{
1138 int cc;
1139
1140 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1141 if (cc != 0) {
1142 /*
1143 * Sometimes this fails under Bionic with EINVAL during shutdown.
1144 * This can happen if the timing is just right, e.g. a thread
1145 * fails to attach during shutdown, but the "fail" path calls
1146 * here to ensure we clean up after ourselves.
1147 */
1148 if (thread != NULL) {
1149 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1150 dvmAbort(); /* the world is fundamentally hosed */
1151 }
1152 }
1153}
1154
1155/*
1156 * This is associated with the pthreadKeySelf key. It's called by the
1157 * pthread library when a thread is exiting and the "self" pointer in TLS
1158 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001159 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001160 *
1161 * This is mainly of use to ensure that we don't leak resources if, for
1162 * example, a thread attaches itself to us with AttachCurrentThread and
1163 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001164 *
1165 * We could do the detach here instead of aborting, but this will lead to
1166 * portability problems. Other implementations do not do this check and
1167 * will simply be unaware that the thread has exited, leading to resource
1168 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1169 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001170 *
1171 * Because some implementations may want to use the pthread destructor
1172 * to initiate the detach, and the ordering of destructors is not defined,
1173 * 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 -08001174 */
1175static void threadExitCheck(void* arg)
1176{
Andy McFadden909ce242009-12-10 16:38:30 -08001177 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001178
Andy McFadden909ce242009-12-10 16:38:30 -08001179 Thread* self = (Thread*) arg;
1180 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001181
Andy McFadden909ce242009-12-10 16:38:30 -08001182 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1183 self->threadId, arg, self->threadExitCheckCount);
1184
1185 if (self->status == THREAD_ZOMBIE) {
1186 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1187 self->threadId);
1188 return;
1189 }
1190
1191 if (self->threadExitCheckCount < kMaxCount) {
1192 /*
1193 * Spin a couple of times to let other destructors fire.
1194 */
1195 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1196 self->threadId, self->threadExitCheckCount);
1197 self->threadExitCheckCount++;
1198 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1199 if (cc != 0) {
1200 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1201 self->threadId);
1202 dvmAbort();
1203 }
1204 } else {
1205 LOGE("threadid=%d: native thread exited without detaching\n",
1206 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001207 dvmAbort();
1208 }
1209}
1210
1211
1212/*
1213 * Assign the threadId. This needs to be a small integer so that our
1214 * "thin" locks fit in a small number of bits.
1215 *
1216 * We reserve zero for use as an invalid ID.
1217 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001218 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001219 */
1220static void assignThreadId(Thread* thread)
1221{
Carl Shapiro59a93122010-01-26 17:12:51 -08001222 /*
1223 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001224 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1225 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001226 */
1227 int num = dvmAllocBit(gDvm.threadIdMap);
1228 if (num < 0) {
1229 LOGE("Ran out of thread IDs\n");
1230 dvmAbort(); // TODO: make this a non-fatal error result
1231 }
1232
Carl Shapiro59a93122010-01-26 17:12:51 -08001233 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001234
1235 assert(thread->threadId != 0);
1236 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1237}
1238
1239/*
1240 * Give back the thread ID.
1241 */
1242static void releaseThreadId(Thread* thread)
1243{
1244 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001245 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001246 thread->threadId = 0;
1247}
1248
1249
1250/*
1251 * Add a stack frame that makes it look like the native code in the main
1252 * thread was originally invoked from interpreted code. This gives us a
1253 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1254 * VM begins by executing "main" in a class, so in a way this brings us
1255 * closer to the spec.
1256 */
1257static bool createFakeEntryFrame(Thread* thread)
1258{
1259 assert(thread->threadId == kMainThreadId); // main thread only
1260
1261 /* find the method on first use */
1262 if (gDvm.methFakeNativeEntry == NULL) {
1263 ClassObject* nativeStart;
1264 Method* mainMeth;
1265
1266 nativeStart = dvmFindSystemClassNoInit(
1267 "Ldalvik/system/NativeStart;");
1268 if (nativeStart == NULL) {
1269 LOGE("Unable to find dalvik.system.NativeStart class\n");
1270 return false;
1271 }
1272
1273 /*
1274 * Because we are creating a frame that represents application code, we
1275 * want to stuff the application class loader into the method's class
1276 * loader field, even though we're using the system class loader to
1277 * load it. This makes life easier over in JNI FindClass (though it
1278 * could bite us in other ways).
1279 *
1280 * Unfortunately this is occurring too early in the initialization,
1281 * of necessity coming before JNI is initialized, and we're not quite
1282 * ready to set up the application class loader.
1283 *
1284 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1285 * and check it in FindClass. The method is private so nobody else
1286 * can call it.
1287 */
1288 //nativeStart->classLoader = dvmGetSystemClassLoader();
1289
1290 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1291 "main", "([Ljava/lang/String;)V");
1292 if (mainMeth == NULL) {
1293 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1294 return false;
1295 }
1296
1297 gDvm.methFakeNativeEntry = mainMeth;
1298 }
1299
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001300 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1301 return false;
1302
1303 /*
1304 * Null out the "String[] args" argument.
1305 */
1306 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1307 u4* framePtr = (u4*) thread->curFrame;
1308 framePtr[0] = 0;
1309
1310 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001311}
1312
1313
1314/*
1315 * Add a stack frame that makes it look like the native thread has been
1316 * executing interpreted code. This gives us a place to hang JNI local
1317 * references.
1318 */
1319static bool createFakeRunFrame(Thread* thread)
1320{
1321 ClassObject* nativeStart;
1322 Method* runMeth;
1323
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001324 /*
1325 * TODO: cache this result so we don't have to dig for it every time
1326 * somebody attaches a thread to the VM. Also consider changing this
1327 * to a static method so we don't have a null "this" pointer in the
1328 * "ins" on the stack. (Does it really need to look like a Runnable?)
1329 */
1330 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001331 if (nativeStart == NULL) {
1332 LOGE("Unable to find dalvik.system.NativeStart class\n");
1333 return false;
1334 }
1335
1336 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1337 if (runMeth == NULL) {
1338 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1339 return false;
1340 }
1341
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001342 if (!dvmPushJNIFrame(thread, runMeth))
1343 return false;
1344
1345 /*
1346 * Provide a NULL 'this' argument. The method we've put at the top of
1347 * the stack looks like a virtual call to run() in a Runnable class.
1348 * (If we declared the method static, it wouldn't take any arguments
1349 * and we wouldn't have to do this.)
1350 */
1351 assert(runMeth->registersSize == 1);
1352 u4* framePtr = (u4*) thread->curFrame;
1353 framePtr[0] = 0;
1354
1355 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001356}
1357
1358/*
1359 * Helper function to set the name of the current thread
1360 */
1361static void setThreadName(const char *threadName)
1362{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001363 int hasAt = 0;
1364 int hasDot = 0;
1365 const char *s = threadName;
1366 while (*s) {
1367 if (*s == '.') hasDot = 1;
1368 else if (*s == '@') hasAt = 1;
1369 s++;
1370 }
1371 int len = s - threadName;
1372 if (len < 15 || hasAt || !hasDot) {
1373 s = threadName;
1374 } else {
1375 s = threadName + len - 15;
1376 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001377#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001378 /* pthread_setname_np fails rather than truncating long strings */
1379 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1380 strncpy(buf, s, sizeof(buf)-1);
1381 buf[sizeof(buf)-1] = '\0';
1382 int err = pthread_setname_np(pthread_self(), buf);
1383 if (err != 0) {
1384 LOGW("Unable to set the name of current thread to '%s': %s\n",
1385 buf, strerror(err));
1386 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001387#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001388 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001389#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001390 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001391#endif
1392}
1393
1394/*
1395 * Create a thread as a result of java.lang.Thread.start().
1396 *
1397 * We do have to worry about some concurrency problems, e.g. programs
1398 * that try to call Thread.start() on the same object from multiple threads.
1399 * (This will fail for all but one, but we have to make sure that it succeeds
1400 * for exactly one.)
1401 *
1402 * Some of the complexity here arises from our desire to mimic the
1403 * Thread vs. VMThread class decomposition we inherited. We've been given
1404 * a Thread, and now we need to create a VMThread and then populate both
1405 * objects. We also need to create one of our internal Thread objects.
1406 *
1407 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001408 *
1409 * The "threadObj" reference must be pinned by the caller to prevent the GC
1410 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001411 */
1412bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1413{
1414 pthread_attr_t threadAttr;
1415 pthread_t threadHandle;
1416 Thread* self;
1417 Thread* newThread = NULL;
1418 Object* vmThreadObj = NULL;
1419 int stackSize;
1420
1421 assert(threadObj != NULL);
1422
1423 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001424 // Allow the sampling profiler thread. We shut it down before forking.
1425 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1426 gDvm.offJavaLangThread_name);
1427 char* threadName = dvmCreateCstrFromString(nameStr);
1428 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
Bob Lee9dc72a32009-09-04 18:28:16 -07001429 if (!profilerThread) {
Brian Carlstrom33dab962010-12-01 13:46:50 -08001430 dvmThrowExceptionFmt("Ljava/lang/IllegalStateException;",
1431 "No new threads in -Xzygote mode. "
1432 "Found thread named '%s'", threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001433
Brian Carlstrom33dab962010-12-01 13:46:50 -08001434 free(threadName);
Bob Lee9dc72a32009-09-04 18:28:16 -07001435 goto fail;
1436 }
Brian Carlstrom33dab962010-12-01 13:46:50 -08001437 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001438 }
1439
1440 self = dvmThreadSelf();
1441 if (reqStackSize == 0)
1442 stackSize = gDvm.stackSize;
1443 else if (reqStackSize < kMinStackSize)
1444 stackSize = kMinStackSize;
1445 else if (reqStackSize > kMaxStackSize)
1446 stackSize = kMaxStackSize;
1447 else
1448 stackSize = reqStackSize;
1449
1450 pthread_attr_init(&threadAttr);
1451 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1452
1453 /*
1454 * To minimize the time spent in the critical section, we allocate the
1455 * vmThread object here.
1456 */
1457 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1458 if (vmThreadObj == NULL)
1459 goto fail;
1460
1461 newThread = allocThread(stackSize);
1462 if (newThread == NULL)
1463 goto fail;
1464 newThread->threadObj = threadObj;
1465
1466 assert(newThread->status == THREAD_INITIALIZING);
1467
1468 /*
1469 * We need to lock out other threads while we test and set the
1470 * "vmThread" field in java.lang.Thread, because we use that to determine
1471 * if this thread has been started before. We use the thread list lock
1472 * because it's handy and we're going to need to grab it again soon
1473 * anyway.
1474 */
1475 dvmLockThreadList(self);
1476
1477 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1478 dvmUnlockThreadList();
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001479 dvmThrowIllegalThreadStateException(
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001480 "thread has already been started");
1481 goto fail;
1482 }
1483
1484 /*
1485 * There are actually three data structures: Thread (object), VMThread
1486 * (object), and Thread (C struct). All of them point to at least one
1487 * other.
1488 *
1489 * As soon as "VMThread.vmData" is assigned, other threads can start
1490 * making calls into us (e.g. setPriority).
1491 */
1492 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1493 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1494
1495 /*
1496 * Thread creation might take a while, so release the lock.
1497 */
1498 dvmUnlockThreadList();
1499
Carl Shapiro5617ad32010-07-02 10:50:57 -07001500 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1501 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001502 newThread);
1503 oldStatus = dvmChangeStatus(self, oldStatus);
1504
1505 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001506 /*
1507 * Failure generally indicates that we have exceeded system
1508 * resource limits. VirtualMachineError is probably too severe,
1509 * so use OutOfMemoryError.
1510 */
1511 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1512
1513 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1514
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001515 dvmThrowOutOfMemoryError("thread creation failed");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001516 goto fail;
1517 }
1518
1519 /*
1520 * We need to wait for the thread to start. Otherwise, depending on
1521 * the whims of the OS scheduler, we could return and the code in our
1522 * thread could try to do operations on the new thread before it had
1523 * finished starting.
1524 *
1525 * The new thread will lock the thread list, change its state to
1526 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1527 * on gDvm.threadStartCond (which uses the thread list lock). This
1528 * thread (the parent) will either see that the thread is already ready
1529 * after we grab the thread list lock, or will be awakened from the
1530 * condition variable on the broadcast.
1531 *
1532 * We don't want to stall the rest of the VM while the new thread
1533 * starts, which can happen if the GC wakes up at the wrong moment.
1534 * So, we change our own status to VMWAIT, and self-suspend if
1535 * necessary after we finish adding the new thread.
1536 *
1537 *
1538 * We have to deal with an odd race with the GC/debugger suspension
1539 * mechanism when creating a new thread. The information about whether
1540 * or not a thread should be suspended is contained entirely within
1541 * the Thread struct; this is usually cleaner to deal with than having
1542 * one or more globally-visible suspension flags. The trouble is that
1543 * we could create the thread while the VM is trying to suspend all
1544 * threads. The suspend-count won't be nonzero for the new thread,
1545 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1546 *
1547 * The easiest way to deal with this is to prevent the new thread from
1548 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001549 * following (correct) sequence of events for a "badly timed" GC
1550 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001551 *
1552 * - call pthread_create()
1553 * - lock thread list
1554 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1555 * - sleep on condition var (mutex = thread list lock) until child starts
1556 * + GC triggered by another thread
1557 * + thread list locked; suspend counts updated; thread list unlocked
1558 * + loop waiting for all runnable threads to suspend
1559 * + success, start GC
1560 * o child thread wakes, signals condition var to wake parent
1561 * o child waits for parent ack on condition variable
1562 * - we wake up, locking thread list
1563 * - add child to thread list
1564 * - unlock thread list
1565 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1566 * + GC finishes; all threads in thread list are resumed
1567 * - lock thread list
1568 * - set child to THREAD_VMWAIT, and signal it to start
1569 * - unlock thread list
1570 * o child resumes
1571 * o child changes state to THREAD_RUNNING
1572 *
1573 * The above shows the GC starting up during thread creation, but if
1574 * it starts anywhere after VMThread.create() is called it will
1575 * produce the same series of events.
1576 *
1577 * Once the child is in the thread list, it will be suspended and
1578 * resumed like any other thread. In the above scenario the resume-all
1579 * code will try to resume the new thread, which was never actually
1580 * suspended, and try to decrement the child's thread suspend count to -1.
1581 * We can catch this in the resume-all code.
1582 *
1583 * Bouncing back and forth between threads like this adds a small amount
1584 * of scheduler overhead to thread startup.
1585 *
1586 * One alternative to having the child wait for the parent would be
1587 * to have the child inherit the parents' suspension count. This
1588 * would work for a GC, since we can safely assume that the parent
1589 * thread didn't cause it, but we must only do so if the parent suspension
1590 * was caused by a suspend-all. If the parent was being asked to
1591 * suspend singly by the debugger, the child should not inherit the value.
1592 *
1593 * We could also have a global "new thread suspend count" that gets
1594 * picked up by new threads before changing state to THREAD_RUNNING.
1595 * This would be protected by the thread list lock and set by a
1596 * suspend-all.
1597 */
1598 dvmLockThreadList(self);
1599 assert(self->status == THREAD_RUNNING);
1600 self->status = THREAD_VMWAIT;
1601 while (newThread->status != THREAD_STARTING)
1602 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1603
1604 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1605 newThread->next = gDvm.threadList->next;
1606 if (newThread->next != NULL)
1607 newThread->next->prev = newThread;
1608 newThread->prev = gDvm.threadList;
1609 gDvm.threadList->next = newThread;
1610
1611 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1612 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1613
1614 dvmUnlockThreadList();
1615
1616 /* change status back to RUNNING, self-suspending if necessary */
1617 dvmChangeStatus(self, THREAD_RUNNING);
1618
1619 /*
1620 * Tell the new thread to start.
1621 *
1622 * We must hold the thread list lock before messing with another thread.
1623 * In the general case we would also need to verify that newThread was
1624 * still in the thread list, but in our case the thread has not started
1625 * executing user code and therefore has not had a chance to exit.
1626 *
1627 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1628 * comes with a suspend-pending check.
1629 */
1630 dvmLockThreadList(self);
1631
1632 assert(newThread->status == THREAD_STARTING);
1633 newThread->status = THREAD_VMWAIT;
1634 pthread_cond_broadcast(&gDvm.threadStartCond);
1635
1636 dvmUnlockThreadList();
1637
1638 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1639 return true;
1640
1641fail:
1642 freeThread(newThread);
1643 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1644 return false;
1645}
1646
1647/*
1648 * pthread entry function for threads started from interpreted code.
1649 */
1650static void* interpThreadStart(void* arg)
1651{
1652 Thread* self = (Thread*) arg;
1653
1654 char *threadName = dvmGetThreadName(self);
1655 setThreadName(threadName);
1656 free(threadName);
1657
1658 /*
1659 * Finish initializing the Thread struct.
1660 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001661 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001662 prepareThread(self);
1663
1664 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1665
1666 /*
1667 * Change our status and wake our parent, who will add us to the
1668 * thread list and advance our state to VMWAIT.
1669 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001670 self->status = THREAD_STARTING;
1671 pthread_cond_broadcast(&gDvm.threadStartCond);
1672
1673 /*
1674 * Wait until the parent says we can go. Assuming there wasn't a
1675 * suspend pending, this will happen immediately. When it completes,
1676 * we're full-fledged citizens of the VM.
1677 *
1678 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1679 * because the pthread_cond_wait below needs to reacquire a lock that
1680 * suspend-all is also interested in. If we get unlucky, the parent could
1681 * change us to THREAD_RUNNING, then a GC could start before we get
1682 * signaled, and suspend-all will grab the thread list lock and then
1683 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1684 * trying to get the lock.
1685 */
1686 while (self->status != THREAD_VMWAIT)
1687 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1688
1689 dvmUnlockThreadList();
1690
1691 /*
1692 * Add a JNI context.
1693 */
1694 self->jniEnv = dvmCreateJNIEnv(self);
1695
1696 /*
1697 * Change our state so the GC will wait for us from now on. If a GC is
1698 * in progress this call will suspend us.
1699 */
1700 dvmChangeStatus(self, THREAD_RUNNING);
1701
1702 /*
1703 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001704 * us to suspend ourselves (and others). The thread state may change
1705 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001706 */
1707 if (gDvm.debuggerConnected)
1708 dvmDbgPostThreadStart(self);
1709
1710 /*
1711 * Set the system thread priority according to the Thread object's
1712 * priority level. We don't usually need to do this, because both the
1713 * Thread object and system thread priorities inherit from parents. The
1714 * tricky case is when somebody creates a Thread object, calls
1715 * setPriority(), and then starts the thread. We could manage this with
1716 * a "needs priority update" flag to avoid the redundant call.
1717 */
Andy McFadden4879df92009-08-07 14:49:40 -07001718 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001719 gDvm.offJavaLangThread_priority);
1720 dvmChangeThreadPriority(self, priority);
1721
1722 /*
1723 * Execute the "run" method.
1724 *
1725 * At this point our stack is empty, so somebody who comes looking for
1726 * stack traces right now won't have much to look at. This is normal.
1727 */
1728 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1729 JValue unused;
1730
1731 LOGV("threadid=%d: calling run()\n", self->threadId);
1732 assert(strcmp(run->name, "run") == 0);
1733 dvmCallMethod(self, run, self->threadObj, &unused);
1734 LOGV("threadid=%d: exiting\n", self->threadId);
1735
1736 /*
1737 * Remove the thread from various lists, report its death, and free
1738 * its resources.
1739 */
1740 dvmDetachCurrentThread();
1741
1742 return NULL;
1743}
1744
1745/*
1746 * The current thread is exiting with an uncaught exception. The
1747 * Java programming language allows the application to provide a
1748 * thread-exit-uncaught-exception handler for the VM, for a specific
1749 * Thread, and for all threads in a ThreadGroup.
1750 *
1751 * Version 1.5 added the per-thread handler. We need to call
1752 * "uncaughtException" in the handler object, which is either the
1753 * ThreadGroup object or the Thread-specific handler.
1754 */
1755static void threadExitUncaughtException(Thread* self, Object* group)
1756{
1757 Object* exception;
1758 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001759 Method* uncaughtHandler = NULL;
1760 InstField* threadHandler;
1761
1762 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1763 self->threadId, group);
1764 assert(group != NULL);
1765
1766 /*
1767 * Get a pointer to the exception, then clear out the one in the
1768 * thread. We don't want to have it set when executing interpreted code.
1769 */
1770 exception = dvmGetException(self);
1771 dvmAddTrackedAlloc(exception, self);
1772 dvmClearException(self);
1773
1774 /*
1775 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1776 * else use "group" (which is an instance of UncaughtExceptionHandler).
1777 */
1778 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1779 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1780 if (threadHandler == NULL) {
1781 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1782 goto bail;
1783 }
1784 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1785 if (handlerObj == NULL)
1786 handlerObj = group;
1787
1788 /*
1789 * Find the "uncaughtHandler" field in this object.
1790 */
1791 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1792 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1793
1794 if (uncaughtHandler != NULL) {
1795 //LOGI("+++ calling %s.uncaughtException\n",
1796 // handlerObj->clazz->descriptor);
1797 JValue unused;
1798 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1799 self->threadObj, exception);
1800 } else {
1801 /* restore it and dump a stack trace */
1802 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1803 handlerObj->clazz->descriptor);
1804 dvmSetException(self, exception);
1805 dvmLogExceptionStackTrace();
1806 }
1807
1808bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001809 /* Remove this thread's suspendCount from global suspendCount sum */
1810 lockThreadSuspendCount();
1811 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1812 unlockThreadSuspendCount();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001813 dvmReleaseTrackedAlloc(exception, self);
1814}
1815
1816
1817/*
1818 * Create an internal VM thread, for things like JDWP and finalizers.
1819 *
1820 * The easiest way to do this is create a new thread and then use the
1821 * JNI AttachCurrentThread implementation.
1822 *
1823 * This does not return until after the new thread has begun executing.
1824 */
1825bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1826 InternalThreadStart func, void* funcArg)
1827{
1828 InternalStartArgs* pArgs;
1829 Object* systemGroup;
1830 pthread_attr_t threadAttr;
1831 volatile Thread* newThread = NULL;
1832 volatile int createStatus = 0;
1833
1834 systemGroup = dvmGetSystemThreadGroup();
1835 if (systemGroup == NULL)
1836 return false;
1837
1838 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1839 pArgs->func = func;
1840 pArgs->funcArg = funcArg;
1841 pArgs->name = strdup(name); // storage will be owned by new thread
1842 pArgs->group = systemGroup;
1843 pArgs->isDaemon = true;
1844 pArgs->pThread = &newThread;
1845 pArgs->pCreateStatus = &createStatus;
1846
1847 pthread_attr_init(&threadAttr);
1848 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1849
1850 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1851 pArgs) != 0)
1852 {
1853 LOGE("internal thread creation failed\n");
1854 free(pArgs->name);
1855 free(pArgs);
1856 return false;
1857 }
1858
1859 /*
1860 * Wait for the child to start. This gives us an opportunity to make
1861 * sure that the thread started correctly, and allows our caller to
1862 * assume that the thread has started running.
1863 *
1864 * Because we aren't holding a lock across the thread creation, it's
1865 * possible that the child will already have completed its
1866 * initialization. Because the child only adjusts "createStatus" while
1867 * holding the thread list lock, the initial condition on the "while"
1868 * loop will correctly avoid the wait if this occurs.
1869 *
1870 * It's also possible that we'll have to wait for the thread to finish
1871 * being created, and as part of allocating a Thread object it might
1872 * need to initiate a GC. We switch to VMWAIT while we pause.
1873 */
1874 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001875 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001876 dvmLockThreadList(self);
1877 while (createStatus == 0)
1878 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1879
1880 if (newThread == NULL) {
1881 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1882 assert(createStatus < 0);
1883 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1884 dvmUnlockThreadList();
1885 dvmChangeStatus(self, oldStatus);
1886 return false;
1887 }
1888
1889 /* thread could be in any state now (except early init states) */
1890 //assert(newThread->status == THREAD_RUNNING);
1891
1892 dvmUnlockThreadList();
1893 dvmChangeStatus(self, oldStatus);
1894
1895 return true;
1896}
1897
1898/*
1899 * pthread entry function for internally-created threads.
1900 *
1901 * We are expected to free "arg" and its contents. If we're a daemon
1902 * thread, and we get cancelled abruptly when the VM shuts down, the
1903 * storage won't be freed. If this becomes a concern we can make a copy
1904 * on the stack.
1905 */
1906static void* internalThreadStart(void* arg)
1907{
1908 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1909 JavaVMAttachArgs jniArgs;
1910
1911 jniArgs.version = JNI_VERSION_1_2;
1912 jniArgs.name = pArgs->name;
1913 jniArgs.group = pArgs->group;
1914
1915 setThreadName(pArgs->name);
1916
1917 /* use local jniArgs as stack top */
1918 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1919 /*
1920 * Tell the parent of our success.
1921 *
1922 * threadListLock is the mutex for threadStartCond.
1923 */
1924 dvmLockThreadList(dvmThreadSelf());
1925 *pArgs->pCreateStatus = 1;
1926 *pArgs->pThread = dvmThreadSelf();
1927 pthread_cond_broadcast(&gDvm.threadStartCond);
1928 dvmUnlockThreadList();
1929
1930 LOG_THREAD("threadid=%d: internal '%s'\n",
1931 dvmThreadSelf()->threadId, pArgs->name);
1932
1933 /* execute */
1934 (*pArgs->func)(pArgs->funcArg);
1935
1936 /* detach ourselves */
1937 dvmDetachCurrentThread();
1938 } else {
1939 /*
1940 * Tell the parent of our failure. We don't have a Thread struct,
1941 * so we can't be suspended, so we don't need to enter a critical
1942 * section.
1943 */
1944 dvmLockThreadList(dvmThreadSelf());
1945 *pArgs->pCreateStatus = -1;
1946 assert(*pArgs->pThread == NULL);
1947 pthread_cond_broadcast(&gDvm.threadStartCond);
1948 dvmUnlockThreadList();
1949
1950 assert(*pArgs->pThread == NULL);
1951 }
1952
1953 free(pArgs->name);
1954 free(pArgs);
1955 return NULL;
1956}
1957
1958/*
1959 * Attach the current thread to the VM.
1960 *
1961 * Used for internally-created threads and JNI's AttachCurrentThread.
1962 */
1963bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1964{
1965 Thread* self = NULL;
1966 Object* threadObj = NULL;
1967 Object* vmThreadObj = NULL;
1968 StringObject* threadNameStr = NULL;
1969 Method* init;
1970 bool ok, ret;
1971
Andy McFaddene3346d82010-06-02 15:37:21 -07001972 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001973 self = allocThread(gDvm.stackSize);
1974 if (self == NULL)
1975 goto fail;
1976 setThreadSelf(self);
1977
1978 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001979 * Finish our thread prep. We need to do this before adding ourselves
1980 * to the thread list or invoking any interpreted code. prepareThread()
1981 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001982 */
1983 dvmLockThreadList(self);
1984 ok = prepareThread(self);
1985 dvmUnlockThreadList();
1986 if (!ok)
1987 goto fail;
1988
1989 self->jniEnv = dvmCreateJNIEnv(self);
1990 if (self->jniEnv == NULL)
1991 goto fail;
1992
1993 /*
1994 * Create a "fake" JNI frame at the top of the main thread interp stack.
1995 * It isn't really necessary for the internal threads, but it gives
1996 * the debugger something to show. It is essential for the JNI-attached
1997 * threads.
1998 */
1999 if (!createFakeRunFrame(self))
2000 goto fail;
2001
2002 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002003 * The native side of the thread is ready; add it to the list. Once
2004 * 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 -08002005 */
2006 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
2007
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002008 dvmLockThreadList(self);
2009
2010 self->next = gDvm.threadList->next;
2011 if (self->next != NULL)
2012 self->next->prev = self;
2013 self->prev = gDvm.threadList;
2014 gDvm.threadList->next = self;
2015 if (!isDaemon)
2016 gDvm.nonDaemonThreadCount++;
2017
2018 dvmUnlockThreadList();
2019
2020 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002021 * Switch state from initializing to running.
2022 *
2023 * It's possible that a GC began right before we added ourselves
2024 * to the thread list, and is still going. That means our thread
2025 * suspend count won't reflect the fact that we should be suspended.
2026 * To deal with this, we transition to VMWAIT, pulse the heap lock,
2027 * and then advance to RUNNING. That will ensure that we stall until
2028 * the GC completes.
2029 *
2030 * Once we're in RUNNING, we're like any other thread in the VM (except
2031 * for the lack of an initialized threadObj). We're then free to
2032 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002033 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002034 assert(self->status == THREAD_INITIALIZING);
2035 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002036 dvmLockMutex(&gDvm.gcHeapLock);
2037 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002038 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002039
2040 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002041 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002042 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002043 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2044 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2045 if (threadObj == NULL || vmThreadObj == NULL)
2046 goto fail_unlink;
2047
2048 /*
2049 * This makes threadObj visible to the GC. We still have it in the
2050 * tracked allocation table, so it can't move around on us.
2051 */
2052 self->threadObj = threadObj;
2053 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2054
2055 /*
2056 * Create a string for the thread name.
2057 */
2058 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002059 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002060 if (threadNameStr == NULL) {
2061 assert(dvmCheckException(dvmThreadSelf()));
2062 goto fail_unlink;
2063 }
2064 }
2065
2066 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2067 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2068 if (init == NULL) {
2069 assert(dvmCheckException(self));
2070 goto fail_unlink;
2071 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002072
2073 /*
2074 * Now we're ready to run some interpreted code.
2075 *
2076 * We need to construct the Thread object and set the VMThread field.
2077 * Setting VMThread tells interpreted code that we're alive.
2078 *
2079 * Call the (group, name, priority, daemon) constructor on the Thread.
2080 * This sets the thread's name and adds it to the specified group, and
2081 * provides values for priority and daemon (which are normally inherited
2082 * from the current thread).
2083 */
2084 JValue unused;
2085 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2086 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2087 if (dvmCheckException(self)) {
2088 LOGE("exception thrown while constructing attached thread object\n");
2089 goto fail_unlink;
2090 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002091
2092 /*
2093 * Set the VMThread field, which tells interpreted code that we're alive.
2094 *
2095 * The risk of a thread start collision here is very low; somebody
2096 * would have to be deliberately polling the ThreadGroup list and
2097 * trying to start threads against anything it sees, which would
2098 * generally cause problems for all thread creation. However, for
2099 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002100 *
2101 * TODO: this still has a race, it's just smaller. Not sure this is
2102 * worth putting effort into fixing. Need to hold a lock while
2103 * fiddling with the field, or maybe initialize the Thread object in a
2104 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002105 */
2106 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002107 LOGW("WOW: thread start hijack\n");
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08002108 dvmThrowIllegalThreadStateException(
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002109 "thread has already been started");
2110 /* We don't want to free anything associated with the thread
2111 * because someone is obviously interested in it. Just let
2112 * it go and hope it will clean itself up when its finished.
2113 * This case should never happen anyway.
2114 *
2115 * Since we're letting it live, we need to finish setting it up.
2116 * We just have to let the caller know that the intended operation
2117 * has failed.
2118 *
2119 * [ This seems strange -- stepping on the vmThread object that's
2120 * already present seems like a bad idea. TODO: figure this out. ]
2121 */
2122 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002123 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002124 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002125 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002126 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2127
Andy McFaddene3346d82010-06-02 15:37:21 -07002128 /* we can now safely un-pin these */
2129 dvmReleaseTrackedAlloc(threadObj, self);
2130 dvmReleaseTrackedAlloc(vmThreadObj, self);
2131 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002132
2133 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2134 self->threadId, pArgs->name);
2135
2136 /* tell the debugger & DDM */
2137 if (gDvm.debuggerConnected)
2138 dvmDbgPostThreadStart(self);
2139
2140 return ret;
2141
2142fail_unlink:
2143 dvmLockThreadList(self);
2144 unlinkThread(self);
2145 if (!isDaemon)
2146 gDvm.nonDaemonThreadCount--;
2147 dvmUnlockThreadList();
2148 /* fall through to "fail" */
2149fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002150 dvmReleaseTrackedAlloc(threadObj, self);
2151 dvmReleaseTrackedAlloc(vmThreadObj, self);
2152 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002153 if (self != NULL) {
2154 if (self->jniEnv != NULL) {
2155 dvmDestroyJNIEnv(self->jniEnv);
2156 self->jniEnv = NULL;
2157 }
2158 freeThread(self);
2159 }
2160 setThreadSelf(NULL);
2161 return false;
2162}
2163
2164/*
2165 * Detach the thread from the various data structures, notify other threads
2166 * that are waiting to "join" it, and free up all heap-allocated storage.
2167 *
2168 * Used for all threads.
2169 *
2170 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2171 * requires us to enforce this for the DetachCurrentThread call, probably
2172 * because it also says that DetachCurrentThread causes all monitors
2173 * associated with the thread to be released. (Because the stack is empty,
2174 * we only have to worry about explicit JNI calls to MonitorEnter.)
2175 *
2176 * THOUGHT:
2177 * We might want to avoid freeing our internal Thread structure until the
2178 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2179 * get to once the thread shuts down, but there is a small possibility of
2180 * an operation starting in another thread before this thread halts, and
2181 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2182 * We don't want something like Thread.isInterrupted() crawling through
2183 * freed storage. Can do with a Thread finalizer, or by creating a
2184 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2185 * state into that.
2186 */
2187void dvmDetachCurrentThread(void)
2188{
2189 Thread* self = dvmThreadSelf();
2190 Object* vmThread;
2191 Object* group;
2192
2193 /*
2194 * Make sure we're not detaching a thread that's still running. (This
2195 * could happen with an explicit JNI detach call.)
2196 *
2197 * A thread created by interpreted code will finish with a depth of
2198 * zero, while a JNI-attached thread will have the synthetic "stack
2199 * starter" native method at the top.
2200 */
2201 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2202 if (curDepth != 0) {
2203 bool topIsNative = false;
2204
2205 if (curDepth == 1) {
2206 /* not expecting a lingering break frame; just look at curFrame */
Carl Shapirofc75f3e2010-12-07 11:43:38 -08002207 assert(!dvmIsBreakFrame((u4*)self->curFrame));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002208 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2209 if (dvmIsNativeMethod(ssa->method))
2210 topIsNative = true;
2211 }
2212
2213 if (!topIsNative) {
2214 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2215 curDepth);
2216 dvmDumpThread(self, false);
2217 dvmAbort();
2218 }
2219 }
2220
2221 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2222 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2223
2224 /*
2225 * Release any held monitors. Since there are no interpreted stack
2226 * frames, the only thing left are the monitors held by JNI MonitorEnter
2227 * calls.
2228 */
2229 dvmReleaseJniMonitors(self);
2230
2231 /*
2232 * Do some thread-exit uncaught exception processing if necessary.
2233 */
2234 if (dvmCheckException(self))
2235 threadExitUncaughtException(self, group);
2236
2237 /*
2238 * Remove the thread from the thread group.
2239 */
2240 if (group != NULL) {
2241 Method* removeThread =
2242 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2243 JValue unused;
2244 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2245 }
2246
2247 /*
2248 * Clear the vmThread reference in the Thread object. Interpreted code
2249 * will now see that this Thread is not running. As this may be the
2250 * only reference to the VMThread object that the VM knows about, we
2251 * have to create an internal reference to it first.
2252 */
2253 vmThread = dvmGetFieldObject(self->threadObj,
2254 gDvm.offJavaLangThread_vmThread);
2255 dvmAddTrackedAlloc(vmThread, self);
2256 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2257
2258 /* clear out our struct Thread pointer, since it's going away */
2259 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2260
2261 /*
2262 * Tell the debugger & DDM. This may cause the current thread or all
2263 * threads to suspend.
2264 *
2265 * The JDWP spec is somewhat vague about when this happens, other than
2266 * that it's issued by the dying thread, which may still appear in
2267 * an "all threads" listing.
2268 */
2269 if (gDvm.debuggerConnected)
2270 dvmDbgPostThreadDeath(self);
2271
2272 /*
2273 * Thread.join() is implemented as an Object.wait() on the VMThread
2274 * object. Signal anyone who is waiting.
2275 */
2276 dvmLockObject(self, vmThread);
2277 dvmObjectNotifyAll(self, vmThread);
2278 dvmUnlockObject(self, vmThread);
2279
2280 dvmReleaseTrackedAlloc(vmThread, self);
2281 vmThread = NULL;
2282
2283 /*
2284 * We're done manipulating objects, so it's okay if the GC runs in
2285 * parallel with us from here out. It's important to do this if
2286 * profiling is enabled, since we can wait indefinitely.
2287 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002288 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002289
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002290 /*
2291 * If we're doing method trace profiling, we don't want threads to exit,
2292 * because if they do we'll end up reusing thread IDs. This complicates
2293 * analysis and makes it impossible to have reasonable output in the
2294 * "threads" section of the "key" file.
2295 *
2296 * We need to do this after Thread.join() completes, or other threads
2297 * could get wedged. Since self->threadObj is still valid, the Thread
2298 * object will not get GCed even though we're no longer in the ThreadGroup
2299 * list (which is important since the profiling thread needs to get
2300 * the thread's name).
2301 */
2302 MethodTraceState* traceState = &gDvm.methodTrace;
2303
2304 dvmLockMutex(&traceState->startStopLock);
2305 if (traceState->traceEnabled) {
2306 LOGI("threadid=%d: waiting for method trace to finish\n",
2307 self->threadId);
2308 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002309 dvmWaitCond(&traceState->threadExitCond,
2310 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002311 }
2312 }
2313 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002314
2315 dvmLockThreadList(self);
2316
2317 /*
2318 * Lose the JNI context.
2319 */
2320 dvmDestroyJNIEnv(self->jniEnv);
2321 self->jniEnv = NULL;
2322
2323 self->status = THREAD_ZOMBIE;
2324
2325 /*
2326 * Remove ourselves from the internal thread list.
2327 */
2328 unlinkThread(self);
2329
2330 /*
2331 * If we're the last one standing, signal anybody waiting in
2332 * DestroyJavaVM that it's okay to exit.
2333 */
2334 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2335 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2336
2337 if (gDvm.nonDaemonThreadCount == 0) {
2338 int cc;
2339
2340 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2341 //dvmDumpAllThreads(false);
2342 // cond var guarded by threadListLock, which we already hold
2343 cc = pthread_cond_signal(&gDvm.vmExitCond);
2344 assert(cc == 0);
2345 }
2346 }
2347
2348 LOGV("threadid=%d: bye!\n", self->threadId);
2349 releaseThreadId(self);
2350 dvmUnlockThreadList();
2351
2352 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002353
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002354 freeThread(self);
2355}
2356
2357
2358/*
2359 * Suspend a single thread. Do not use to suspend yourself.
2360 *
2361 * This is used primarily for debugger/DDMS activity. Does not return
2362 * until the thread has suspended or is in a "safe" state (e.g. executing
2363 * native code outside the VM).
2364 *
2365 * The thread list lock should be held before calling here -- it's not
2366 * entirely safe to hang on to a Thread* from another thread otherwise.
2367 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2368 */
2369void dvmSuspendThread(Thread* thread)
2370{
2371 assert(thread != NULL);
2372 assert(thread != dvmThreadSelf());
2373 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2374
2375 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002376 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002377 thread->dbgSuspendCount++;
2378
2379 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2380 thread->threadId, thread->suspendCount);
2381 unlockThreadSuspendCount();
2382
2383 waitForThreadSuspend(dvmThreadSelf(), thread);
2384}
2385
2386/*
2387 * Reduce the suspend count of a thread. If it hits zero, tell it to
2388 * resume.
2389 *
2390 * Used primarily for debugger/DDMS activity. The thread in question
2391 * might have been suspended singly or as part of a suspend-all operation.
2392 *
2393 * The thread list lock should be held before calling here -- it's not
2394 * entirely safe to hang on to a Thread* from another thread otherwise.
2395 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2396 */
2397void dvmResumeThread(Thread* thread)
2398{
2399 assert(thread != NULL);
2400 assert(thread != dvmThreadSelf());
2401 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2402
2403 lockThreadSuspendCount();
2404 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002405 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002406 thread->dbgSuspendCount--;
2407 } else {
2408 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2409 thread->threadId);
2410 }
2411
2412 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2413 thread->threadId, thread->suspendCount);
2414
2415 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002416 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002417 }
2418
2419 unlockThreadSuspendCount();
2420}
2421
2422/*
2423 * Suspend yourself, as a result of debugger activity.
2424 */
2425void dvmSuspendSelf(bool jdwpActivity)
2426{
2427 Thread* self = dvmThreadSelf();
2428
Andy McFadden6dce9962010-08-23 16:45:24 -07002429 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002430 assert(gDvm.jdwpState != NULL);
2431 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2432 assert(false);
2433 return;
2434 }
2435
2436 /*
2437 * Collisions with other suspends aren't really interesting. We want
2438 * to ensure that we're the only one fiddling with the suspend count
2439 * though.
2440 */
2441 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002442 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002443 self->dbgSuspendCount++;
2444
2445 /*
2446 * Suspend ourselves.
2447 */
2448 assert(self->suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002449 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002450 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2451
2452 /*
2453 * Tell JDWP that we've completed suspension. The JDWP thread can't
2454 * tell us to resume before we're fully asleep because we hold the
2455 * suspend count lock.
2456 *
2457 * If we got here via waitForDebugger(), don't do this part.
2458 */
2459 if (jdwpActivity) {
2460 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2461 // self->threadId, (int) self->handle);
2462 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2463 }
2464
2465 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002466 dvmWaitCond(&gDvm.threadSuspendCountCond,
2467 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002468 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002469 /*
2470 * The condition was signaled but we're still suspended. This
2471 * can happen if the debugger lets go while a SIGQUIT thread
2472 * dump event is pending (assuming SignalCatcher was resumed for
2473 * just long enough to try to grab the thread-suspend lock).
2474 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002475 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
2476 self->threadId, self->suspendCount, self->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002477 }
2478 }
2479 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002480 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002481 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2482 self->threadId, self->status);
2483
2484 unlockThreadSuspendCount();
2485}
2486
2487
2488#ifdef HAVE_GLIBC
2489# define NUM_FRAMES 20
2490# include <execinfo.h>
2491/*
2492 * glibc-only stack dump function. Requires link with "--export-dynamic".
2493 *
2494 * TODO: move this into libs/cutils and make it work for all platforms.
2495 */
2496static void printBackTrace(void)
2497{
2498 void* array[NUM_FRAMES];
2499 size_t size;
2500 char** strings;
2501 size_t i;
2502
2503 size = backtrace(array, NUM_FRAMES);
2504 strings = backtrace_symbols(array, size);
2505
2506 LOGW("Obtained %zd stack frames.\n", size);
2507
2508 for (i = 0; i < size; i++)
2509 LOGW("%s\n", strings[i]);
2510
2511 free(strings);
2512}
2513#else
2514static void printBackTrace(void) {}
2515#endif
2516
2517/*
2518 * Dump the state of the current thread and that of another thread that
2519 * we think is wedged.
2520 */
2521static void dumpWedgedThread(Thread* thread)
2522{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002523 dvmDumpThread(dvmThreadSelf(), false);
2524 printBackTrace();
2525
2526 // dumping a running thread is risky, but could be useful
2527 dvmDumpThread(thread, true);
2528
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002529 // stop now and get a core dump
2530 //abort();
2531}
2532
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002533/*
2534 * If the thread is running at below-normal priority, temporarily elevate
2535 * it to "normal".
2536 *
2537 * Returns zero if no changes were made. Otherwise, returns bit flags
2538 * indicating what was changed, storing the previous values in the
2539 * provided locations.
2540 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002541int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002542 SchedPolicy* pSavedThreadPolicy)
2543{
2544 errno = 0;
2545 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2546 if (errno != 0) {
2547 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2548 thread->threadId, thread->systemTid);
2549 return 0;
2550 }
2551 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2552 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2553 thread->threadId, thread->systemTid);
2554 return 0;
2555 }
2556
2557 int changeFlags = 0;
2558
2559 /*
2560 * Change the priority if we're in the background group.
2561 */
2562 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2563 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2564 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2565 } else {
2566 changeFlags |= kChangedPolicy;
2567 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2568 thread->systemTid, *pSavedThreadPolicy);
2569 }
2570 }
2571
2572 /*
2573 * getpriority() returns the "nice" value, so larger numbers indicate
2574 * lower priority, with 0 being normal.
2575 */
2576 if (*pSavedThreadPrio > 0) {
2577 const int kHigher = 0;
2578 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2579 LOGW("Couldn't raise priority on tid %d to %d\n",
2580 thread->systemTid, kHigher);
2581 } else {
2582 changeFlags |= kChangedPriority;
2583 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2584 thread->systemTid, *pSavedThreadPrio, kHigher);
2585 }
2586 }
2587
2588 return changeFlags;
2589}
2590
2591/*
2592 * Reset the priority values for the thread in question.
2593 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002594void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002595 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2596{
2597 if ((changeFlags & kChangedPolicy) != 0) {
2598 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2599 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2600 thread->systemTid, savedThreadPolicy);
2601 } else {
2602 LOGD("Restored policy of %d to %d\n",
2603 thread->systemTid, savedThreadPolicy);
2604 }
2605 }
2606
2607 if ((changeFlags & kChangedPriority) != 0) {
2608 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2609 {
2610 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2611 thread->systemTid, savedThreadPrio);
2612 } else {
2613 LOGD("Restored priority on %d to %d\n",
2614 thread->systemTid, savedThreadPrio);
2615 }
2616 }
2617}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002618
2619/*
2620 * Wait for another thread to see the pending suspension and stop running.
2621 * It can either suspend itself or go into a non-running state such as
2622 * VMWAIT or NATIVE in which it cannot interact with the GC.
2623 *
2624 * If we're running at a higher priority, sched_yield() may not do anything,
2625 * so we need to sleep for "long enough" to guarantee that the other
2626 * thread has a chance to finish what it's doing. Sleeping for too short
2627 * a period (e.g. less than the resolution of the sleep clock) might cause
2628 * the scheduler to return immediately, so we want to start with a
2629 * "reasonable" value and expand.
2630 *
2631 * This does not return until the other thread has stopped running.
2632 * Eventually we time out and the VM aborts.
2633 *
2634 * This does not try to detect the situation where two threads are
2635 * waiting for each other to suspend. In normal use this is part of a
2636 * suspend-all, which implies that the suspend-all lock is held, or as
2637 * part of a debugger action in which the JDWP thread is always the one
2638 * doing the suspending. (We may need to re-evaluate this now that
2639 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2640 *
2641 * TODO: track basic stats about time required to suspend VM.
2642 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002643#define FIRST_SLEEP (250*1000) /* 0.25s */
2644#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002645static void waitForThreadSuspend(Thread* self, Thread* thread)
2646{
2647 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002648 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002649 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002650 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002651 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002652 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002653
2654 int sleepIter = 0;
2655 int retryCount = 0;
2656 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002657 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002658
Andy McFadden6dce9962010-08-23 16:45:24 -07002659 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002660 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002661 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002662 if (firstStartWhen == 0) // first iteration of first attempt
2663 firstStartWhen = startWhen;
2664
2665 /*
2666 * After waiting for a bit, check to see if the target thread is
2667 * running at a reduced priority. If so, bump it up temporarily
2668 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002669 */
2670 if (retryCount == 2) {
2671 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002672 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002673 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002674 }
2675 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002676
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002677#if defined (WITH_JIT)
2678 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002679 * If we're still waiting after the first timeout, unchain all
2680 * translations iff:
2681 * 1) There are new chains formed since the last unchain
2682 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002683 */
Ben Cheng6999d842010-01-26 16:46:15 -08002684 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2685 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002686 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002687 dvmJitUnchainAll();
2688 }
2689#endif
2690
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002691 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002692 * Sleep briefly. The iterative sleep call returns false if we've
2693 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002694 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002695 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002696 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002697 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002698 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002699 thread->threadId, priChangeFlags);
2700 if (retryCount > 1) {
2701 /* stack trace logging is slow; skip on first iter */
2702 dumpWedgedThread(thread);
2703 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002704 complained = true;
2705 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002706
2707 // keep going; could be slow due to valgrind
2708 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002709 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002710
2711 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002712 LOGE("Fatal spin-on-suspend, dumping threads\n");
2713 dvmDumpAllThreads(false);
2714
2715 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002716 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2717 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002718
2719 /* try to get a debuggerd dump from the spinning thread */
2720 dvmNukeThread(thread);
2721 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002722 dvmAbort();
2723 }
2724 }
2725 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002726
2727 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002728 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2729 self->threadId,
2730 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002731 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2732 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002733 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002734 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002735 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002736 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002737}
2738
2739/*
2740 * Suspend all threads except the current one. This is used by the GC,
2741 * the debugger, and by any thread that hits a "suspend all threads"
2742 * debugger event (e.g. breakpoint or exception).
2743 *
2744 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2745 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2746 * create objects and even execute arbitrary code. The "why" argument
2747 * allows the caller to say why the suspension is taking place.
2748 *
2749 * This can be called when a global suspend has already happened, due to
2750 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2751 * doesn't work.
2752 *
2753 * DO NOT grab any locks before calling here. We grab & release the thread
2754 * lock and suspend lock here (and we're not using recursive threads), and
2755 * we might have to self-suspend if somebody else beats us here.
2756 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002757 * We know the current thread is in the thread list, because we attach the
2758 * thread before doing anything that could cause VM suspension (like object
2759 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002760 */
2761void dvmSuspendAllThreads(SuspendCause why)
2762{
2763 Thread* self = dvmThreadSelf();
2764 Thread* thread;
2765
2766 assert(why != 0);
2767
2768 /*
2769 * Start by grabbing the thread suspend lock. If we can't get it, most
2770 * likely somebody else is in the process of performing a suspend or
2771 * resume, so lockThreadSuspend() will cause us to self-suspend.
2772 *
2773 * We keep the lock until all other threads are suspended.
2774 */
2775 lockThreadSuspend("susp-all", why);
2776
2777 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2778
2779 /*
2780 * This is possible if the current thread was in VMWAIT mode when a
2781 * suspend-all happened, and then decided to do its own suspend-all.
2782 * This can happen when a couple of threads have simultaneous events
2783 * of interest to the debugger.
2784 */
2785 //assert(self->suspendCount == 0);
2786
2787 /*
2788 * Increment everybody's suspend count (except our own).
2789 */
2790 dvmLockThreadList(self);
2791
2792 lockThreadSuspendCount();
2793 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2794 if (thread == self)
2795 continue;
2796
2797 /* debugger events don't suspend JDWP thread */
2798 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2799 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2800 continue;
2801
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002802 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002803 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2804 thread->dbgSuspendCount++;
2805 }
2806 unlockThreadSuspendCount();
2807
2808 /*
2809 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2810 * indicate the code is either running natively or sleeping quietly.
2811 * Any attempt to transition back to THREAD_RUNNING will cause a check
2812 * for suspension, so it should be impossible for anything to execute
2813 * interpreted code or modify objects (assuming native code plays nicely).
2814 *
2815 * It's also okay if the thread transitions to a non-RUNNING state.
2816 *
2817 * Note we released the threadSuspendCountLock before getting here,
2818 * so if another thread is fiddling with its suspend count (perhaps
2819 * self-suspending for the debugger) it won't block while we're waiting
2820 * in here.
2821 */
2822 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2823 if (thread == self)
2824 continue;
2825
2826 /* debugger events don't suspend JDWP thread */
2827 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2828 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2829 continue;
2830
2831 /* wait for the other thread to see the pending suspend */
2832 waitForThreadSuspend(self, thread);
2833
Andy McFadden6dce9962010-08-23 16:45:24 -07002834 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002835 self->threadId,
2836 thread->threadId, thread->status, thread->suspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07002837 thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002838 }
2839
2840 dvmUnlockThreadList();
2841 unlockThreadSuspend();
2842
2843 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2844}
2845
2846/*
2847 * Resume all threads that are currently suspended.
2848 *
2849 * The "why" must match with the previous suspend.
2850 */
2851void dvmResumeAllThreads(SuspendCause why)
2852{
2853 Thread* self = dvmThreadSelf();
2854 Thread* thread;
2855 int cc;
2856
2857 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2858 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2859
2860 /*
2861 * Decrement the suspend counts for all threads. No need for atomic
2862 * writes, since nobody should be moving until we decrement the count.
2863 * We do need to hold the thread list because of JNI attaches.
2864 */
2865 dvmLockThreadList(self);
2866 lockThreadSuspendCount();
2867 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2868 if (thread == self)
2869 continue;
2870
2871 /* debugger events don't suspend JDWP thread */
2872 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2873 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002874 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002875 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002876 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002877
2878 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002879 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002880 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2881 thread->dbgSuspendCount--;
2882 } else {
2883 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2884 thread->threadId);
2885 }
2886 }
2887 unlockThreadSuspendCount();
2888 dvmUnlockThreadList();
2889
2890 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002891 * In some ways it makes sense to continue to hold the thread-suspend
2892 * lock while we issue the wakeup broadcast. It allows us to complete
2893 * one operation before moving on to the next, which simplifies the
2894 * thread activity debug traces.
2895 *
2896 * This approach caused us some difficulty under Linux, because the
2897 * condition variable broadcast not only made the threads runnable,
2898 * but actually caused them to execute, and it was a while before
2899 * the thread performing the wakeup had an opportunity to release the
2900 * thread-suspend lock.
2901 *
2902 * This is a problem because, when a thread tries to acquire that
2903 * lock, it times out after 3 seconds. If at some point the thread
2904 * is told to suspend, the clock resets; but since the VM is still
2905 * theoretically mid-resume, there's no suspend pending. If, for
2906 * example, the GC was waking threads up while the SIGQUIT handler
2907 * was trying to acquire the lock, we would occasionally time out on
2908 * a busy system and SignalCatcher would abort.
2909 *
2910 * We now perform the unlock before the wakeup broadcast. The next
2911 * suspend can't actually start until the broadcast completes and
2912 * returns, because we're holding the thread-suspend-count lock, but the
2913 * suspending thread is now able to make progress and we avoid the abort.
2914 *
2915 * (Technically there is a narrow window between when we release
2916 * the thread-suspend lock and grab the thread-suspend-count lock.
2917 * This could cause us to send a broadcast to threads with nonzero
2918 * suspend counts, but this is expected and they'll all just fall
2919 * right back to sleep. It's probably safe to grab the suspend-count
2920 * lock before releasing thread-suspend, since we're still following
2921 * the correct order of acquisition, but it feels weird.)
2922 */
2923
2924 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2925 unlockThreadSuspend();
2926
2927 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002928 * Broadcast a notification to all suspended threads, some or all of
2929 * which may choose to wake up. No need to wait for them.
2930 */
2931 lockThreadSuspendCount();
2932 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2933 assert(cc == 0);
2934 unlockThreadSuspendCount();
2935
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002936 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2937}
2938
2939/*
2940 * Undo any debugger suspensions. This is called when the debugger
2941 * disconnects.
2942 */
2943void dvmUndoDebuggerSuspensions(void)
2944{
2945 Thread* self = dvmThreadSelf();
2946 Thread* thread;
2947 int cc;
2948
2949 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2950 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2951
2952 /*
2953 * Decrement the suspend counts for all threads. No need for atomic
2954 * writes, since nobody should be moving until we decrement the count.
2955 * We do need to hold the thread list because of JNI attaches.
2956 */
2957 dvmLockThreadList(self);
2958 lockThreadSuspendCount();
2959 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2960 if (thread == self)
2961 continue;
2962
2963 /* debugger events don't suspend JDWP thread */
2964 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2965 assert(thread->dbgSuspendCount == 0);
2966 continue;
2967 }
2968
2969 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002970 dvmAddToThreadSuspendCount(&thread->suspendCount,
2971 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002972 thread->dbgSuspendCount = 0;
2973 }
2974 unlockThreadSuspendCount();
2975 dvmUnlockThreadList();
2976
2977 /*
2978 * Broadcast a notification to all suspended threads, some or all of
2979 * which may choose to wake up. No need to wait for them.
2980 */
2981 lockThreadSuspendCount();
2982 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2983 assert(cc == 0);
2984 unlockThreadSuspendCount();
2985
2986 unlockThreadSuspend();
2987
2988 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2989}
2990
2991/*
2992 * Determine if a thread is suspended.
2993 *
2994 * As with all operations on foreign threads, the caller should hold
2995 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002996 *
2997 * If the thread is suspending or waking, these fields could be changing
2998 * out from under us (or the thread could change state right after we
2999 * examine it), making this generally unreliable. This is chiefly
3000 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003001 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07003002bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003003{
3004 /*
3005 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07003006 * (1) Running happily. status is RUNNING, suspendCount is zero.
3007 * Return "false".
3008 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
3009 * Return "false".
3010 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003011 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07003012 * (4) Waking up. suspendCount is zero, status is SUSPENDED
3013 * Return "false" (since it could change out from under us, unless
3014 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003015 */
3016
Andy McFadden6dce9962010-08-23 16:45:24 -07003017 return (thread->suspendCount != 0 && thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003018}
3019
3020/*
3021 * Wait until another thread self-suspends. This is specifically for
3022 * synchronization between the JDWP thread and a thread that has decided
3023 * to suspend itself after sending an event to the debugger.
3024 *
3025 * Threads that encounter "suspend all" events work as well -- the thread
3026 * in question suspends everybody else and then itself.
3027 *
3028 * We can't hold a thread lock here or in the caller, because we could
3029 * get here just before the to-be-waited-for-thread issues a "suspend all".
3030 * There's an opportunity for badness if the thread we're waiting for exits
3031 * and gets cleaned up, but since the thread in question is processing a
3032 * debugger event, that's not really a possibility. (To avoid deadlock,
3033 * it's important that we not be in THREAD_RUNNING while we wait.)
3034 */
3035void dvmWaitForSuspend(Thread* thread)
3036{
3037 Thread* self = dvmThreadSelf();
3038
3039 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3040 self->threadId, thread->threadId);
3041
3042 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3043 assert(thread != self);
3044 assert(self->status != THREAD_RUNNING);
3045
3046 waitForThreadSuspend(self, thread);
3047
3048 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3049 self->threadId, thread->threadId);
3050}
3051
3052/*
3053 * Check to see if we need to suspend ourselves. If so, go to sleep on
3054 * a condition variable.
3055 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003056 * Returns "true" if we suspended ourselves.
3057 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003058static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003059{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003060 assert(self != NULL);
3061 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003062
Andy McFadden6dce9962010-08-23 16:45:24 -07003063 /*
3064 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
3065 * access to self->suspendCount.
3066 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003067 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3068
Andy McFadden6dce9962010-08-23 16:45:24 -07003069 bool needSuspend = (self->suspendCount != 0);
3070 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07003071 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07003072 ThreadStatus oldStatus = self->status; /* should be RUNNING */
3073 self->status = THREAD_SUSPENDED;
3074
Andy McFadden3469a7e2010-08-04 16:09:10 -07003075 while (self->suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003076 /*
3077 * Wait for wakeup signal, releasing lock. The act of releasing
3078 * and re-acquiring the lock provides the memory barriers we
3079 * need for correct behavior on SMP.
3080 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07003081 dvmWaitCond(&gDvm.threadSuspendCountCond,
3082 &gDvm.threadSuspendCountLock);
3083 }
3084 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07003085 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07003086 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3087 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003088 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003089
3090 unlockThreadSuspendCount();
3091
Andy McFadden6dce9962010-08-23 16:45:24 -07003092 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003093}
3094
3095/*
Andy McFadden6dce9962010-08-23 16:45:24 -07003096 * Check to see if a suspend is pending. If so, suspend the current
3097 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003098 */
3099bool dvmCheckSuspendPending(Thread* self)
3100{
Andy McFadden6dce9962010-08-23 16:45:24 -07003101 assert(self != NULL);
3102 if (self->suspendCount == 0) {
3103 return false;
3104 } else {
3105 return fullSuspendCheck(self);
3106 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003107}
3108
3109/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003110 * Update our status.
3111 *
3112 * The "self" argument, which may be NULL, is accepted as an optimization.
3113 *
3114 * Returns the old status.
3115 */
3116ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3117{
3118 ThreadStatus oldStatus;
3119
3120 if (self == NULL)
3121 self = dvmThreadSelf();
3122
3123 LOGVV("threadid=%d: (status %d -> %d)\n",
3124 self->threadId, self->status, newStatus);
3125
3126 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07003127 if (oldStatus == newStatus)
3128 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003129
3130 if (newStatus == THREAD_RUNNING) {
3131 /*
3132 * Change our status to THREAD_RUNNING. The transition requires
3133 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003134 * us to be "asleep" in all other states, and another thread could
3135 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003136 *
Andy McFadden6dce9962010-08-23 16:45:24 -07003137 * The order of operations is very significant here. One way to
3138 * do this wrong is:
3139 *
3140 * GCing thread Our thread (in NATIVE)
3141 * ------------ ----------------------
3142 * check suspend count (== 0)
3143 * dvmSuspendAllThreads()
3144 * grab suspend-count lock
3145 * increment all suspend counts
3146 * release suspend-count lock
3147 * check thread state (== NATIVE)
3148 * all are suspended, begin GC
3149 * set state to RUNNING
3150 * (continue executing)
3151 *
3152 * We can correct this by grabbing the suspend-count lock and
3153 * performing both of our operations (check suspend count, set
3154 * state) while holding it, now we need to grab a mutex on every
3155 * transition to RUNNING.
3156 *
3157 * What we do instead is change the order of operations so that
3158 * the transition to RUNNING happens first. If we then detect
3159 * that the suspend count is nonzero, we switch to SUSPENDED.
3160 *
3161 * Appropriate compiler and memory barriers are required to ensure
3162 * that the operations are observed in the expected order.
3163 *
3164 * This does create a small window of opportunity where a GC in
3165 * progress could observe what appears to be a running thread (if
3166 * it happens to look between when we set to RUNNING and when we
3167 * switch to SUSPENDED). At worst this only affects assertions
3168 * and thread logging. (We could work around it with some sort
3169 * of intermediate "pre-running" state that is generally treated
3170 * as equivalent to running, but that doesn't seem worthwhile.)
3171 *
3172 * We can also solve this by combining the "status" and "suspend
3173 * count" fields into a single 32-bit value. This trades the
3174 * store/load barrier on transition to RUNNING for an atomic RMW
3175 * op on all transitions and all suspend count updates (also, all
3176 * accesses to status or the thread count require bit-fiddling).
3177 * It also eliminates the brief transition through RUNNING when
3178 * the thread is supposed to be suspended. This is possibly faster
3179 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003180 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003181 android_atomic_acquire_store(newStatus, &self->status);
3182 if (self->suspendCount != 0) {
3183 fullSuspendCheck(self);
3184 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003185 } else {
3186 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003187 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003188 *
3189 * We use a releasing store to ensure that, if we were RUNNING,
3190 * any updates we previously made to objects on the managed heap
3191 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003192 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003193 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003194 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003195 }
3196
3197 return oldStatus;
3198}
3199
3200/*
3201 * Get a statically defined thread group from a field in the ThreadGroup
3202 * Class object. Expected arguments are "mMain" and "mSystem".
3203 */
3204static Object* getStaticThreadGroup(const char* fieldName)
3205{
3206 StaticField* groupField;
3207 Object* groupObj;
3208
3209 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3210 fieldName, "Ljava/lang/ThreadGroup;");
3211 if (groupField == NULL) {
3212 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
Dan Bornstein70b00ab2011-02-23 14:11:27 -08003213 dvmThrowInternalError("bad definition for ThreadGroup");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003214 return NULL;
3215 }
3216 groupObj = dvmGetStaticFieldObject(groupField);
3217 if (groupObj == NULL) {
3218 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08003219 dvmThrowInternalError(NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003220 return NULL;
3221 }
3222
3223 return groupObj;
3224}
3225Object* dvmGetSystemThreadGroup(void)
3226{
3227 return getStaticThreadGroup("mSystem");
3228}
3229Object* dvmGetMainThreadGroup(void)
3230{
3231 return getStaticThreadGroup("mMain");
3232}
3233
3234/*
3235 * Given a VMThread object, return the associated Thread*.
3236 *
3237 * NOTE: if the thread detaches, the struct Thread will disappear, and
3238 * we will be touching invalid data. For safety, lock the thread list
3239 * before calling this.
3240 */
3241Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3242{
3243 int vmData;
3244
3245 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003246
3247 if (false) {
3248 Thread* thread = gDvm.threadList;
3249 while (thread != NULL) {
3250 if ((Thread*)vmData == thread)
3251 break;
3252
3253 thread = thread->next;
3254 }
3255
3256 if (thread == NULL) {
3257 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3258 vmThreadObj, (Thread*)vmData);
3259 vmData = 0;
3260 }
3261 }
3262
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003263 return (Thread*) vmData;
3264}
3265
Andy McFadden2b94b302010-03-09 16:38:36 -08003266/*
3267 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003268 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003269 *
3270 * Returns NULL if the thread was not found.
3271 */
3272Thread* dvmGetThreadByHandle(pthread_t handle)
3273{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003274 Thread* thread;
3275 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003276 if (thread->handle == handle)
3277 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003278 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003279 return thread;
3280}
Andy McFadden2b94b302010-03-09 16:38:36 -08003281
Andy McFadden0a24ef92010-03-12 13:39:59 -08003282/*
3283 * Given a threadId, return the associated Thread*.
3284 * Caller must hold the thread list lock.
3285 *
3286 * Returns NULL if the thread was not found.
3287 */
3288Thread* dvmGetThreadByThreadId(u4 threadId)
3289{
3290 Thread* thread;
3291 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3292 if (thread->threadId == threadId)
3293 break;
3294 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003295 return thread;
3296}
3297
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003298
3299/*
3300 * Conversion map for "nice" values.
3301 *
3302 * We use Android thread priority constants to be consistent with the rest
3303 * of the system. In some cases adjacent entries may overlap.
3304 */
3305static const int kNiceValues[10] = {
3306 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3307 ANDROID_PRIORITY_BACKGROUND + 6,
3308 ANDROID_PRIORITY_BACKGROUND + 3,
3309 ANDROID_PRIORITY_BACKGROUND,
3310 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3311 ANDROID_PRIORITY_NORMAL - 2,
3312 ANDROID_PRIORITY_NORMAL - 4,
3313 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3314 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3315 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3316};
3317
3318/*
3319 * Change the priority of a system thread to match that of the Thread object.
3320 *
3321 * We map a priority value from 1-10 to Linux "nice" values, where lower
3322 * numbers indicate higher priority.
3323 */
3324void dvmChangeThreadPriority(Thread* thread, int newPriority)
3325{
3326 pid_t pid = thread->systemTid;
3327 int newNice;
3328
3329 if (newPriority < 1 || newPriority > 10) {
3330 LOGW("bad priority %d\n", newPriority);
3331 newPriority = 5;
3332 }
3333 newNice = kNiceValues[newPriority-1];
3334
Andy McFaddend62c0b52009-08-04 15:02:12 -07003335 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003336 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003337 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003338 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003339 }
3340
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003341 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3342 char* str = dvmGetThreadName(thread);
3343 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3344 pid, str, newPriority, newNice, strerror(errno));
3345 free(str);
3346 } else {
3347 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3348 pid, newPriority, newNice);
3349 }
3350}
3351
3352/*
3353 * Get the thread priority for the current thread by querying the system.
3354 * This is useful when attaching a thread through JNI.
3355 *
3356 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3357 */
3358static int getThreadPriorityFromSystem(void)
3359{
3360 int i, sysprio, jprio;
3361
3362 errno = 0;
3363 sysprio = getpriority(PRIO_PROCESS, 0);
3364 if (sysprio == -1 && errno != 0) {
3365 LOGW("getpriority() failed: %s\n", strerror(errno));
3366 return THREAD_NORM_PRIORITY;
3367 }
3368
3369 jprio = THREAD_MIN_PRIORITY;
3370 for (i = 0; i < NELEM(kNiceValues); i++) {
3371 if (sysprio >= kNiceValues[i])
3372 break;
3373 jprio++;
3374 }
3375 if (jprio > THREAD_MAX_PRIORITY)
3376 jprio = THREAD_MAX_PRIORITY;
3377
3378 return jprio;
3379}
3380
3381
3382/*
3383 * Return true if the thread is on gDvm.threadList.
3384 * Caller should not hold gDvm.threadListLock.
3385 */
3386bool dvmIsOnThreadList(const Thread* thread)
3387{
3388 bool ret = false;
3389
3390 dvmLockThreadList(NULL);
3391 if (thread == gDvm.threadList) {
3392 ret = true;
3393 } else {
3394 ret = thread->prev != NULL || thread->next != NULL;
3395 }
3396 dvmUnlockThreadList();
3397
3398 return ret;
3399}
3400
3401/*
3402 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3403 * output target.
3404 */
3405void dvmDumpThread(Thread* thread, bool isRunning)
3406{
3407 DebugOutputTarget target;
3408
3409 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3410 dvmDumpThreadEx(&target, thread, isRunning);
3411}
3412
3413/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003414 * Try to get the scheduler group.
3415 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003416 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003417 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003418 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003419 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003420 * We return the part on the "cpu" line after the '/', which will be an
3421 * empty string for the default cgroup. If the string is longer than
3422 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003423 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003424 * On error, -1 is returned, and an error description will be stored in
3425 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003426 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003427static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003428{
3429#ifdef HAVE_ANDROID_OS
3430 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003431 char lineBuf[256];
3432 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003433
Andy McFadden7f64ede2010-03-03 15:37:10 -08003434 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003435 if ((fp = fopen(pathBuf, "r")) == NULL) {
3436 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003437 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003438 }
3439
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003440 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3441 char* subsys;
3442 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003443 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003444
Andy McFadden7f64ede2010-03-03 15:37:10 -08003445 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003446 subsys = strchr(lineBuf, ':');
3447 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003448 goto out_bad_data;
3449 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003450
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003451 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003452 /* Not the subsys we're looking for */
3453 continue;
3454 }
3455
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003456 grp = strchr(subsys, '/');
3457 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003458 goto out_bad_data;
3459 }
3460 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003461
Andy McFadden7f64ede2010-03-03 15:37:10 -08003462 len = strlen(grp);
3463 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3464
3465 if (bufLen <= len) {
3466 len = bufLen - 1;
3467 }
3468 strncpy(buf, grp, len);
3469 buf[len] = '\0';
3470 fclose(fp);
3471 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003472 }
3473
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003474 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003475 fclose(fp);
3476 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003477
3478out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003479 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003480 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003481 fclose(fp);
3482 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003483
Andy McFaddend62c0b52009-08-04 15:02:12 -07003484#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003485 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003486 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003487#endif
3488}
3489
3490/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003491 * Convert ThreadStatus to a string.
3492 */
3493const char* dvmGetThreadStatusStr(ThreadStatus status)
3494{
3495 switch (status) {
3496 case THREAD_ZOMBIE: return "ZOMBIE";
3497 case THREAD_RUNNING: return "RUNNABLE";
3498 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3499 case THREAD_MONITOR: return "MONITOR";
3500 case THREAD_WAIT: return "WAIT";
3501 case THREAD_INITIALIZING: return "INITIALIZING";
3502 case THREAD_STARTING: return "STARTING";
3503 case THREAD_NATIVE: return "NATIVE";
3504 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003505 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003506 default: return "UNKNOWN";
3507 }
3508}
3509
3510/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003511 * Print information about the specified thread.
3512 *
3513 * Works best when the thread in question is "self" or has been suspended.
3514 * When dumping a separate thread that's still running, set "isRunning" to
3515 * use a more cautious thread dump function.
3516 */
3517void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3518 bool isRunning)
3519{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003520 Object* threadObj;
3521 Object* groupObj;
3522 StringObject* nameStr;
3523 char* threadName = NULL;
3524 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003525 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003526 bool isDaemon;
3527 int priority; // java.lang.Thread priority
3528 int policy; // pthread policy
3529 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003530 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003531
Andy McFaddene3346d82010-06-02 15:37:21 -07003532 /*
3533 * Get the java.lang.Thread object. This function gets called from
3534 * some weird debug contexts, so it's possible that there's a GC in
3535 * progress on some other thread. To decrease the chances of the
3536 * thread object being moved out from under us, we add the reference
3537 * to the tracked allocation list, which pins it in place.
3538 *
3539 * If threadObj is NULL, the thread is still in the process of being
3540 * attached to the VM, and there's really nothing interesting to
3541 * say about it yet.
3542 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003543 threadObj = thread->threadObj;
3544 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003545 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003546 return;
3547 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003548 dvmAddTrackedAlloc(threadObj, NULL);
3549
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003550 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3551 gDvm.offJavaLangThread_name);
3552 threadName = dvmCreateCstrFromString(nameStr);
3553
3554 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3555 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3556
3557 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3558 LOGW("Warning: pthread_getschedparam failed\n");
3559 policy = -1;
3560 sp.sched_priority = -1;
3561 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003562 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003563 sizeof(schedulerGroupBuf)) == 0 &&
3564 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003565 strcpy(schedulerGroupBuf, "default");
3566 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003567
3568 /* a null value for group is not expected, but deal with it anyway */
3569 groupObj = (Object*) dvmGetFieldObject(threadObj,
3570 gDvm.offJavaLangThread_group);
3571 if (groupObj != NULL) {
3572 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3573 "name", "Ljava/lang/String;");
3574 if (offset < 0) {
3575 LOGW("Unable to find 'name' field in ThreadGroup\n");
3576 } else {
3577 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3578 groupName = dvmCreateCstrFromString(nameStr);
3579 }
3580 }
3581 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003582 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003583
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003584 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003585 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003586 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003587 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3588#if defined(WITH_JIT)
3589 thread->inJitCodeCache ? " JIT" : ""
3590#else
3591 ""
3592#endif
3593 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003594 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003595 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003596 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07003597 thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003598 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003599 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003600 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003601 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003602
Andy McFadden0a3f6982010-08-31 13:50:08 -07003603 /* get some bits from /proc/self/stat */
3604 ProcStatData procStatData;
3605 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3606 /* failed, use zeroed values */
3607 memset(&procStatData, 0, sizeof(procStatData));
3608 }
3609
3610 /* grab the scheduler stats for this thread */
3611 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3612 thread->systemTid);
3613 int schedstatFd = open(schedstatBuf, O_RDONLY);
3614 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003615 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003616 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003617 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3618 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003619 if (bytes >= 1) {
3620 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003621 }
3622 }
3623
Andy McFadden0a3f6982010-08-31 13:50:08 -07003624 /* show what we got */
3625 dvmPrintDebugMessage(target,
3626 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3627 schedstatBuf, procStatData.utime, procStatData.stime,
3628 procStatData.processor);
3629
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003630 if (isRunning)
3631 dvmDumpRunningThreadStack(target, thread);
3632 else
3633 dvmDumpThreadStack(target, thread);
3634
Andy McFaddene3346d82010-06-02 15:37:21 -07003635 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003636 free(threadName);
3637 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003638}
3639
3640/*
3641 * Get the name of a thread.
3642 *
3643 * For correctness, the caller should hold the thread list lock to ensure
3644 * that the thread doesn't go away mid-call.
3645 *
3646 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3647 */
3648char* dvmGetThreadName(Thread* thread)
3649{
3650 StringObject* nameObj;
3651
3652 if (thread->threadObj == NULL) {
3653 LOGW("threadObj is NULL, name not available\n");
3654 return strdup("-unknown-");
3655 }
3656
3657 nameObj = (StringObject*)
3658 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3659 return dvmCreateCstrFromString(nameObj);
3660}
3661
3662/*
3663 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3664 * an output target.
3665 */
3666void dvmDumpAllThreads(bool grabLock)
3667{
3668 DebugOutputTarget target;
3669
3670 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3671 dvmDumpAllThreadsEx(&target, grabLock);
3672}
3673
3674/*
3675 * Print information about all known threads. Assumes they have been
3676 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3677 *
3678 * If "grabLock" is true, we grab the thread lock list. This is important
3679 * to do unless the caller already holds the lock.
3680 */
3681void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3682{
3683 Thread* thread;
3684
3685 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3686
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003687#ifdef HAVE_ANDROID_OS
3688 dvmPrintDebugMessage(target,
3689 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3690 gDvm.threadListLock.value,
3691 gDvm._threadSuspendLock.value,
3692 gDvm.threadSuspendCountLock.value,
3693 gDvm.gcHeapLock.value,
3694 gDvm.heapWorkerLock.value,
3695 gDvm.heapWorkerListLock.value);
3696#endif
3697
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003698 if (grabLock)
3699 dvmLockThreadList(dvmThreadSelf());
3700
3701 thread = gDvm.threadList;
3702 while (thread != NULL) {
3703 dvmDumpThreadEx(target, thread, false);
3704
3705 /* verify link */
3706 assert(thread->next == NULL || thread->next->prev == thread);
3707
3708 thread = thread->next;
3709 }
3710
3711 if (grabLock)
3712 dvmUnlockThreadList();
3713}
3714
Andy McFadden384ef6b2010-03-15 17:24:55 -07003715/*
3716 * Nuke the target thread from orbit.
3717 *
3718 * The idea is to send a "crash" signal to the target thread so that
3719 * debuggerd will take notice and dump an appropriate stack trace.
3720 * Because of the way debuggerd works, we have to throw the same signal
3721 * at it twice.
3722 *
3723 * This does not necessarily cause the entire process to stop, but once a
3724 * thread has been nuked the rest of the system is likely to be unstable.
3725 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003726 * performed, but it's advisable (and expected) to call dvmAbort soon.
3727 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003728 */
3729void dvmNukeThread(Thread* thread)
3730{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003731 int killResult;
3732
Andy McFaddena388a162010-03-18 16:27:14 -07003733 /* suppress the heapworker watchdog to assist anyone using a debugger */
3734 gDvm.nativeDebuggerActive = true;
3735
Andy McFadden384ef6b2010-03-15 17:24:55 -07003736 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003737 * Send the signals, separated by a brief interval to allow debuggerd
3738 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3739 * can be used instead of SIGSEGV to avoid making it look like the
3740 * code actually crashed at the current point of execution.
3741 *
3742 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3743 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3744 * you don't get the second stack trace; possibly something in the
3745 * kernel decides that a signal has already been sent and it's time
3746 * to just kill the process. The position in the current thread is
3747 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003748 *
Andy McFaddena388a162010-03-18 16:27:14 -07003749 * The target thread can continue to execute between the two signals.
3750 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003751 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003752 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3753 " cause debuggerd dump\n",
3754 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003755 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3756 if (killResult != 0) {
3757 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3758 }
Andy McFaddena388a162010-03-18 16:27:14 -07003759 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003760 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3761 if (killResult != 0) {
3762 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3763 }
Andy McFadden7122d862010-03-19 15:18:57 -07003764 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003765 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003766
3767 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3768 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003769 LOGD("Continuing\n");
3770}