blob: 4db32fcc94d018abe4ba4430aaace4fc543803ed [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/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800246 * Initialize thread list and main thread's environment. We need to set
247 * up some basic stuff so that dvmThreadSelf() will work when we start
248 * loading classes (e.g. to check for exceptions).
249 */
250bool dvmThreadStartup(void)
251{
252 Thread* thread;
253
254 /* allocate a TLS slot */
255 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
256 LOGE("ERROR: pthread_key_create failed\n");
257 return false;
258 }
259
260 /* test our pthread lib */
261 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
262 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
263
264 /* prep thread-related locks and conditions */
265 dvmInitMutex(&gDvm.threadListLock);
266 pthread_cond_init(&gDvm.threadStartCond, NULL);
267 //dvmInitMutex(&gDvm.vmExitLock);
268 pthread_cond_init(&gDvm.vmExitCond, NULL);
269 dvmInitMutex(&gDvm._threadSuspendLock);
270 dvmInitMutex(&gDvm.threadSuspendCountLock);
271 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800272
273 /*
274 * Dedicated monitor for Thread.sleep().
275 * TODO: change this to an Object* so we don't have to expose this
276 * call, and we interact better with JDWP monitor calls. Requires
277 * deferring the object creation to much later (e.g. final "main"
278 * thread prep) or until first use.
279 */
280 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
281
282 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
283
284 thread = allocThread(gDvm.stackSize);
285 if (thread == NULL)
286 return false;
287
288 /* switch mode for when we run initializers */
289 thread->status = THREAD_RUNNING;
290
291 /*
292 * We need to assign the threadId early so we can lock/notify
293 * object monitors. We'll set the "threadObj" field later.
294 */
295 prepareThread(thread);
296 gDvm.threadList = thread;
297
298#ifdef COUNT_PRECISE_METHODS
299 gDvm.preciseMethods = dvmPointerSetAlloc(200);
300#endif
301
302 return true;
303}
304
305/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800306 * All threads should be stopped by now. Clean up some thread globals.
307 */
308void dvmThreadShutdown(void)
309{
310 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700311 /*
312 * If we walk through the thread list and try to free the
313 * lingering thread structures (which should only be for daemon
314 * threads), the daemon threads may crash if they execute before
315 * the process dies. Let them leak.
316 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800317 freeThread(gDvm.threadList);
318 gDvm.threadList = NULL;
319 }
320
321 dvmFreeBitVector(gDvm.threadIdMap);
322
323 dvmFreeMonitorList();
324
325 pthread_key_delete(gDvm.pthreadKeySelf);
326}
327
328
329/*
330 * Grab the suspend count global lock.
331 */
332static inline void lockThreadSuspendCount(void)
333{
334 /*
335 * Don't try to change to VMWAIT here. When we change back to RUNNING
336 * we have to check for a pending suspend, which results in grabbing
337 * this lock recursively. Doesn't work with "fast" pthread mutexes.
338 *
339 * This lock is always held for very brief periods, so as long as
340 * mutex ordering is respected we shouldn't stall.
341 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700342 dvmLockMutex(&gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800343}
344
345/*
346 * Release the suspend count global lock.
347 */
348static inline void unlockThreadSuspendCount(void)
349{
350 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
351}
352
353/*
354 * Grab the thread list global lock.
355 *
356 * This is held while "suspend all" is trying to make everybody stop. If
357 * the shutdown is in progress, and somebody tries to grab the lock, they'll
358 * have to wait for the GC to finish. Therefore it's important that the
359 * thread not be in RUNNING mode.
360 *
361 * We don't have to check to see if we should be suspended once we have
362 * the lock. Nobody can suspend all threads without holding the thread list
363 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700364 *
Andy McFadden3469a7e2010-08-04 16:09:10 -0700365 * This function deliberately avoids the use of dvmChangeStatus(),
366 * which could grab threadSuspendCountLock. To avoid deadlock, threads
367 * are required to grab the thread list lock before the thread suspend
368 * count lock. (See comment in DvmGlobals.)
369 *
Andy McFadden44860362009-08-06 17:56:14 -0700370 * TODO: consider checking for suspend after acquiring the lock, and
371 * backing off if set. As stated above, it can't happen during normal
372 * execution, but it *can* happen during shutdown when daemon threads
373 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800374 */
375void dvmLockThreadList(Thread* self)
376{
377 ThreadStatus oldStatus;
378
379 if (self == NULL) /* try to get it from TLS */
380 self = dvmThreadSelf();
381
382 if (self != NULL) {
383 oldStatus = self->status;
384 self->status = THREAD_VMWAIT;
385 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700386 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800387 //LOGW("NULL self in dvmLockThreadList\n");
388 oldStatus = -1; // shut up gcc
389 }
390
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700391 dvmLockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800392
393 if (self != NULL)
394 self->status = oldStatus;
395}
396
397/*
Andy McFaddend19988d2010-10-22 13:32:12 -0700398 * Try to lock the thread list.
399 *
400 * Returns "true" if we locked it. This is a "fast" mutex, so if the
401 * current thread holds the lock this will fail.
402 */
403bool dvmTryLockThreadList(void)
404{
405 return (dvmTryLockMutex(&gDvm.threadListLock) == 0);
406}
407
408/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800409 * Release the thread list global lock.
410 */
411void dvmUnlockThreadList(void)
412{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700413 dvmUnlockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800414}
415
The Android Open Source Project99409882009-03-18 22:20:24 -0700416/*
417 * Convert SuspendCause to a string.
418 */
419static const char* getSuspendCauseStr(SuspendCause why)
420{
421 switch (why) {
422 case SUSPEND_NOT: return "NOT?";
423 case SUSPEND_FOR_GC: return "gc";
424 case SUSPEND_FOR_DEBUG: return "debug";
425 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
426 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700427 case SUSPEND_FOR_VERIFY: return "verify";
Carl Shapiro07018e22010-10-26 21:07:41 -0700428 case SUSPEND_FOR_HPROF: return "hprof";
Ben Chenga8e64a72009-10-20 13:01:36 -0700429#if defined(WITH_JIT)
430 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
431 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800432 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800433 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700434#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700435 default: return "UNKNOWN";
436 }
437}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800438
439/*
440 * Grab the "thread suspend" lock. This is required to prevent the
441 * GC and the debugger from simultaneously suspending all threads.
442 *
443 * If we fail to get the lock, somebody else is trying to suspend all
444 * threads -- including us. If we go to sleep on the lock we'll deadlock
445 * the VM. Loop until we get it or somebody puts us to sleep.
446 */
447static void lockThreadSuspend(const char* who, SuspendCause why)
448{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800449 const int kSpinSleepTime = 3*1000*1000; /* 3s */
450 u8 startWhen = 0; // init req'd to placate gcc
451 int sleepIter = 0;
452 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700453
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800454 do {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700455 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800456 if (cc != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700457 Thread* self = dvmThreadSelf();
458
459 if (!dvmCheckSuspendPending(self)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800460 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700461 * Could be that a resume-all is in progress, and something
462 * grabbed the CPU when the wakeup was broadcast. The thread
463 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700464 * thread suspend lock. (We release before the broadcast,
465 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700466 *
467 * Could be we hit the window as a suspend was started,
468 * and the lock has been grabbed but the suspend counts
469 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700470 *
471 * Could be an unusual JNI thread-attach thing.
472 *
473 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800474 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700475 *
476 * Could be two app threads both want to patch predicted
477 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800478 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700479 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
480 " it's held, no suspend pending\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700481 self->threadId, who, getSuspendCauseStr(why));
The Android Open Source Project99409882009-03-18 22:20:24 -0700482 } else {
483 /* we suspended; reset timeout */
484 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800485 }
486
487 /* give the lock-holder a chance to do some work */
488 if (sleepIter == 0)
489 startWhen = dvmGetRelativeTimeUsec();
490 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700491 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800492 " bailing\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700493 self->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700494 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800495 dvmDumpAllThreads(false);
496 dvmAbort();
497 }
498 }
499 } while (cc != 0);
500 assert(cc == 0);
501}
502
503/*
504 * Release the "thread suspend" lock.
505 */
506static inline void unlockThreadSuspend(void)
507{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700508 dvmUnlockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800509}
510
511
512/*
513 * Kill any daemon threads that still exist. All of ours should be
514 * stopped, so these should be Thread objects or JNI-attached threads
515 * started by the application. Actively-running threads are likely
516 * to crash the process if they continue to execute while the VM
517 * shuts down, so we really need to kill or suspend them. (If we want
518 * the VM to restart within this process, we need to kill them, but that
519 * leaves open the possibility of orphaned resources.)
520 *
521 * Waiting for the thread to suspend may be unwise at this point, but
522 * if one of these is wedged in a critical section then we probably
523 * would've locked up on the last GC attempt.
524 *
525 * It's possible for this function to get called after a failed
526 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700527 *
528 * This will be called from whatever thread calls DestroyJavaVM, usually
529 * but not necessarily the main thread. It's likely, but not guaranteed,
530 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800531 */
532void dvmSlayDaemons(void)
533{
Andy McFadden44860362009-08-06 17:56:14 -0700534 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800535 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700536 int threadId = 0;
537 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800538
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800539 dvmLockThreadList(self);
540
Andy McFadden44860362009-08-06 17:56:14 -0700541 if (self != NULL)
542 threadId = self->threadId;
543
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800544 target = gDvm.threadList;
545 while (target != NULL) {
546 if (target == self) {
547 target = target->next;
548 continue;
549 }
550
551 if (!dvmGetFieldBoolean(target->threadObj,
552 gDvm.offJavaLangThread_daemon))
553 {
Andy McFadden44860362009-08-06 17:56:14 -0700554 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800555 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700556 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800557 }
558
Andy McFadden44860362009-08-06 17:56:14 -0700559 char* threadName = dvmGetThreadName(target);
560 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
561 threadId, target->threadId, threadName);
562 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800563
Andy McFadden44860362009-08-06 17:56:14 -0700564 /* mark as suspended */
565 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -0800566 dvmAddToSuspendCounts(target, 1, 0);
Andy McFadden44860362009-08-06 17:56:14 -0700567 unlockThreadSuspendCount();
568 doWait = true;
569
570 target = target->next;
571 }
572
573 //dvmDumpAllThreads(false);
574
575 /*
576 * Unlock the thread list, relocking it later if necessary. It's
577 * possible a thread is in VMWAIT after calling dvmLockThreadList,
578 * and that function *doesn't* check for pending suspend after
579 * acquiring the lock. We want to let them finish their business
580 * and see the pending suspend before we continue here.
581 *
582 * There's no guarantee of mutex fairness, so this might not work.
583 * (The alternative is to have dvmLockThreadList check for suspend
584 * after acquiring the lock and back off, something we should consider.)
585 */
586 dvmUnlockThreadList();
587
588 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800589 bool complained = false;
590
Andy McFadden44860362009-08-06 17:56:14 -0700591 usleep(200 * 1000);
592
593 dvmLockThreadList(self);
594
595 /*
596 * Sleep for a bit until the threads have suspended. We're trying
597 * to exit, so don't wait for too long.
598 */
599 int i;
600 for (i = 0; i < 10; i++) {
601 bool allSuspended = true;
602
603 target = gDvm.threadList;
604 while (target != NULL) {
605 if (target == self) {
606 target = target->next;
607 continue;
608 }
609
Andy McFadden6dce9962010-08-23 16:45:24 -0700610 if (target->status == THREAD_RUNNING) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800611 if (!complained)
612 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700613 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800614 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700615 }
616
617 target = target->next;
618 }
619
620 if (allSuspended) {
621 LOGD("threadid=%d: all daemons have suspended\n", threadId);
622 break;
623 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800624 if (!complained) {
625 complained = true;
626 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
627 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800628 }
Andy McFadden44860362009-08-06 17:56:14 -0700629 }
630
631 usleep(200 * 1000);
632 }
633 dvmUnlockThreadList();
634 }
635
636#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
637 /*
638 * Abandon the threads and recover their resources.
639 */
640 target = gDvm.threadList;
641 while (target != NULL) {
642 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800643 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800644 freeThread(target);
645 target = nextTarget;
646 }
Andy McFadden44860362009-08-06 17:56:14 -0700647#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800648
Andy McFadden44860362009-08-06 17:56:14 -0700649 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800650}
651
652
653/*
654 * Finish preparing the parts of the Thread struct required to support
655 * JNI registration.
656 */
657bool dvmPrepMainForJni(JNIEnv* pEnv)
658{
659 Thread* self;
660
661 /* main thread is always first in list at this point */
662 self = gDvm.threadList;
663 assert(self->threadId == kMainThreadId);
664
665 /* create a "fake" JNI frame at the top of the main thread interp stack */
666 if (!createFakeEntryFrame(self))
667 return false;
668
669 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
670 dvmSetJniEnvThreadId(pEnv, self);
671 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
672
673 return true;
674}
675
676
677/*
678 * Finish preparing the main thread, allocating some objects to represent
679 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700680 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800681 */
682bool dvmPrepMainThread(void)
683{
684 Thread* thread;
685 Object* groupObj;
686 Object* threadObj;
687 Object* vmThreadObj;
688 StringObject* threadNameStr;
689 Method* init;
690 JValue unused;
691
692 LOGV("+++ finishing prep on main VM thread\n");
693
694 /* main thread is always first in list at this point */
695 thread = gDvm.threadList;
696 assert(thread->threadId == kMainThreadId);
697
698 /*
699 * Make sure the classes are initialized. We have to do this before
700 * we create an instance of them.
701 */
702 if (!dvmInitClass(gDvm.classJavaLangClass)) {
703 LOGE("'Class' class failed to initialize\n");
704 return false;
705 }
706 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
707 !dvmInitClass(gDvm.classJavaLangThread) ||
708 !dvmInitClass(gDvm.classJavaLangVMThread))
709 {
710 LOGE("thread classes failed to initialize\n");
711 return false;
712 }
713
714 groupObj = dvmGetMainThreadGroup();
715 if (groupObj == NULL)
716 return false;
717
718 /*
719 * Allocate and construct a Thread with the internal-creation
720 * constructor.
721 */
722 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
723 if (threadObj == NULL) {
724 LOGE("unable to allocate main thread object\n");
725 return false;
726 }
727 dvmReleaseTrackedAlloc(threadObj, NULL);
728
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700729 threadNameStr = dvmCreateStringFromCstr("main");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800730 if (threadNameStr == NULL)
731 return false;
732 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
733
734 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
735 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
736 assert(init != NULL);
737 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
738 THREAD_NORM_PRIORITY, false);
739 if (dvmCheckException(thread)) {
740 LOGE("exception thrown while constructing main thread object\n");
741 return false;
742 }
743
744 /*
745 * Allocate and construct a VMThread.
746 */
747 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
748 if (vmThreadObj == NULL) {
749 LOGE("unable to allocate main vmthread object\n");
750 return false;
751 }
752 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
753
754 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
755 "(Ljava/lang/Thread;)V");
756 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
757 if (dvmCheckException(thread)) {
758 LOGE("exception thrown while constructing main vmthread object\n");
759 return false;
760 }
761
762 /* set the VMThread.vmData field to our Thread struct */
763 assert(gDvm.offJavaLangVMThread_vmData != 0);
764 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
765
766 /*
767 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700768 * Threads will see that this Thread is running (at least, they would,
769 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800770 */
771 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
772 vmThreadObj);
773
774 thread->threadObj = threadObj;
775
776 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700777 * Set the context class loader. This invokes a ClassLoader method,
778 * which could conceivably call Thread.currentThread(), so we want the
779 * Thread to be fully configured before we do this.
780 */
781 Object* systemLoader = dvmGetSystemClassLoader();
782 if (systemLoader == NULL) {
783 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
784 /* keep going */
785 }
786 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
787 "contextClassLoader", "Ljava/lang/ClassLoader;");
788 if (ctxtClassLoaderOffset < 0) {
789 LOGE("Unable to find contextClassLoader field in Thread\n");
790 return false;
791 }
792 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
Andy McFadden50cab512010-10-07 15:11:43 -0700793 dvmReleaseTrackedAlloc(systemLoader, NULL);
Andy McFaddena1a7a342009-05-04 13:29:30 -0700794
795 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800796 * Finish our thread prep.
797 */
798
799 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
800 gDvm.nonDaemonThreadCount++;
801
802 return true;
803}
804
805
806/*
807 * Alloc and initialize a Thread struct.
808 *
Andy McFaddene3346d82010-06-02 15:37:21 -0700809 * Does not create any objects, just stuff on the system (malloc) heap.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800810 */
811static Thread* allocThread(int interpStackSize)
812{
813 Thread* thread;
814 u1* stackBottom;
815
816 thread = (Thread*) calloc(1, sizeof(Thread));
817 if (thread == NULL)
818 return NULL;
819
buzbee9a3147c2011-03-02 15:43:48 -0800820 /* Check sizes and alignment */
821 assert((((uintptr_t)&thread->interpBreak.all) & 0x7) == 0);
822 assert(sizeof(thread->interpBreak) == sizeof(thread->interpBreak.all));
823
824
Jeff Hao97319a82009-08-12 16:57:15 -0700825#if defined(WITH_SELF_VERIFICATION)
826 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
827 return NULL;
828#endif
829
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800830 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
831
832 thread->status = THREAD_INITIALIZING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800833
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800834 /*
835 * Allocate and initialize the interpreted code stack. We essentially
836 * "lose" the alloc pointer, which points at the bottom of the stack,
837 * but we can get it back later because we know how big the stack is.
838 *
839 * The stack must be aligned on a 4-byte boundary.
840 */
841#ifdef MALLOC_INTERP_STACK
842 stackBottom = (u1*) malloc(interpStackSize);
843 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700844#if defined(WITH_SELF_VERIFICATION)
845 dvmSelfVerificationShadowSpaceFree(thread);
846#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800847 free(thread);
848 return NULL;
849 }
850 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
851#else
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800852 stackBottom = (u1*) mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800853 MAP_PRIVATE | MAP_ANON, -1, 0);
854 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700855#if defined(WITH_SELF_VERIFICATION)
856 dvmSelfVerificationShadowSpaceFree(thread);
857#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800858 free(thread);
859 return NULL;
860 }
861#endif
862
863 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
864 thread->interpStackSize = interpStackSize;
865 thread->interpStackStart = stackBottom + interpStackSize;
866 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
867
buzbeea7d59bb2011-02-24 09:38:17 -0800868#ifndef DVM_NO_ASM_INTERP
869 thread->mainHandlerTable = dvmAsmInstructionStart;
870 thread->altHandlerTable = dvmAsmAltInstructionStart;
buzbee9a3147c2011-03-02 15:43:48 -0800871 thread->interpBreak.ctl.curHandlerTable = thread->mainHandlerTable;
buzbeea7d59bb2011-02-24 09:38:17 -0800872#endif
873
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800874 /* give the thread code a chance to set things up */
875 dvmInitInterpStack(thread, interpStackSize);
876
buzbee9f601a92011-02-11 17:48:20 -0800877 /* One-time setup for interpreter/JIT state */
878 dvmInitInterpreterState(thread);
879
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800880 return thread;
881}
882
883/*
884 * Get a meaningful thread ID. At present this only has meaning under Linux,
885 * where getpid() and gettid() sometimes agree and sometimes don't depending
886 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
887 */
888pid_t dvmGetSysThreadId(void)
889{
890#ifdef HAVE_GETTID
891 return gettid();
892#else
893 return getpid();
894#endif
895}
896
897/*
898 * Finish initialization of a Thread struct.
899 *
900 * This must be called while executing in the new thread, but before the
901 * thread is added to the thread list.
902 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700903 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800904 * assignThreadId()).
905 */
906static bool prepareThread(Thread* thread)
907{
908 assignThreadId(thread);
909 thread->handle = pthread_self();
910 thread->systemTid = dvmGetSysThreadId();
911
912 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
913 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700914 /*
915 * If we were called by dvmAttachCurrentThread, the self value is
916 * already correctly established as "thread".
917 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800918 setThreadSelf(thread);
919
920 LOGV("threadid=%d: interp stack at %p\n",
921 thread->threadId, thread->interpStackStart - thread->interpStackSize);
922
923 /*
924 * Initialize invokeReq.
925 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800926 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800927 pthread_cond_init(&thread->invokeReq.cv, NULL);
928
929 /*
930 * Initialize our reference tracking tables.
931 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800932 * Most threads won't use jniMonitorRefTable, so we clear out the
933 * structure but don't call the init function (which allocs storage).
934 */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700935 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
936 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
937 return false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800938 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
939 kInternalRefDefault, kInternalRefMax))
940 return false;
941
942 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
943
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800944 pthread_cond_init(&thread->waitCond, NULL);
945 dvmInitMutex(&thread->waitMutex);
946
buzbee94d65252011-03-24 16:41:03 -0700947 /* Initialize safepoint callback mechanism */
948 dvmInitMutex(&thread->callbackMutex);
949
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800950 return true;
951}
952
953/*
954 * Remove a thread from the internal list.
955 * Clear out the links to make it obvious that the thread is
956 * no longer on the list. Caller must hold gDvm.threadListLock.
957 */
958static void unlinkThread(Thread* thread)
959{
960 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
961 if (thread == gDvm.threadList) {
962 assert(thread->prev == NULL);
963 gDvm.threadList = thread->next;
964 } else {
965 assert(thread->prev != NULL);
966 thread->prev->next = thread->next;
967 }
968 if (thread->next != NULL)
969 thread->next->prev = thread->prev;
970 thread->prev = thread->next = NULL;
971}
972
973/*
974 * Free a Thread struct, and all the stuff allocated within.
975 */
976static void freeThread(Thread* thread)
977{
978 if (thread == NULL)
979 return;
980
981 /* thread->threadId is zero at this point */
982 LOGVV("threadid=%d: freeing\n", thread->threadId);
983
984 if (thread->interpStackStart != NULL) {
985 u1* interpStackBottom;
986
987 interpStackBottom = thread->interpStackStart;
988 interpStackBottom -= thread->interpStackSize;
989#ifdef MALLOC_INTERP_STACK
990 free(interpStackBottom);
991#else
992 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
993 LOGW("munmap(thread stack) failed\n");
994#endif
995 }
996
Andy McFaddend5ab7262009-08-25 07:19:34 -0700997 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800998 dvmClearReferenceTable(&thread->internalLocalRefTable);
999 if (&thread->jniMonitorRefTable.table != NULL)
1000 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1001
Jeff Hao97319a82009-08-12 16:57:15 -07001002#if defined(WITH_SELF_VERIFICATION)
1003 dvmSelfVerificationShadowSpaceFree(thread);
1004#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001005 free(thread);
1006}
1007
1008/*
1009 * Like pthread_self(), but on a Thread*.
1010 */
1011Thread* dvmThreadSelf(void)
1012{
1013 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1014}
1015
1016/*
1017 * Explore our sense of self. Stuffs the thread pointer into TLS.
1018 */
1019static void setThreadSelf(Thread* thread)
1020{
1021 int cc;
1022
1023 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1024 if (cc != 0) {
1025 /*
1026 * Sometimes this fails under Bionic with EINVAL during shutdown.
1027 * This can happen if the timing is just right, e.g. a thread
1028 * fails to attach during shutdown, but the "fail" path calls
1029 * here to ensure we clean up after ourselves.
1030 */
1031 if (thread != NULL) {
1032 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1033 dvmAbort(); /* the world is fundamentally hosed */
1034 }
1035 }
1036}
1037
1038/*
1039 * This is associated with the pthreadKeySelf key. It's called by the
1040 * pthread library when a thread is exiting and the "self" pointer in TLS
1041 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001042 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001043 *
1044 * This is mainly of use to ensure that we don't leak resources if, for
1045 * example, a thread attaches itself to us with AttachCurrentThread and
1046 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001047 *
1048 * We could do the detach here instead of aborting, but this will lead to
1049 * portability problems. Other implementations do not do this check and
1050 * will simply be unaware that the thread has exited, leading to resource
1051 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1052 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001053 *
1054 * Because some implementations may want to use the pthread destructor
1055 * to initiate the detach, and the ordering of destructors is not defined,
1056 * 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 -08001057 */
1058static void threadExitCheck(void* arg)
1059{
Andy McFadden909ce242009-12-10 16:38:30 -08001060 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001061
Andy McFadden909ce242009-12-10 16:38:30 -08001062 Thread* self = (Thread*) arg;
1063 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001064
Andy McFadden909ce242009-12-10 16:38:30 -08001065 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1066 self->threadId, arg, self->threadExitCheckCount);
1067
1068 if (self->status == THREAD_ZOMBIE) {
1069 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1070 self->threadId);
1071 return;
1072 }
1073
1074 if (self->threadExitCheckCount < kMaxCount) {
1075 /*
1076 * Spin a couple of times to let other destructors fire.
1077 */
1078 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1079 self->threadId, self->threadExitCheckCount);
1080 self->threadExitCheckCount++;
1081 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1082 if (cc != 0) {
1083 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1084 self->threadId);
1085 dvmAbort();
1086 }
1087 } else {
1088 LOGE("threadid=%d: native thread exited without detaching\n",
1089 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001090 dvmAbort();
1091 }
1092}
1093
1094
1095/*
1096 * Assign the threadId. This needs to be a small integer so that our
1097 * "thin" locks fit in a small number of bits.
1098 *
1099 * We reserve zero for use as an invalid ID.
1100 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001101 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001102 */
1103static void assignThreadId(Thread* thread)
1104{
Carl Shapiro59a93122010-01-26 17:12:51 -08001105 /*
1106 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001107 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1108 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001109 */
1110 int num = dvmAllocBit(gDvm.threadIdMap);
1111 if (num < 0) {
1112 LOGE("Ran out of thread IDs\n");
1113 dvmAbort(); // TODO: make this a non-fatal error result
1114 }
1115
Carl Shapiro59a93122010-01-26 17:12:51 -08001116 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001117
1118 assert(thread->threadId != 0);
1119 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1120}
1121
1122/*
1123 * Give back the thread ID.
1124 */
1125static void releaseThreadId(Thread* thread)
1126{
1127 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001128 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001129 thread->threadId = 0;
1130}
1131
1132
1133/*
1134 * Add a stack frame that makes it look like the native code in the main
1135 * thread was originally invoked from interpreted code. This gives us a
1136 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1137 * VM begins by executing "main" in a class, so in a way this brings us
1138 * closer to the spec.
1139 */
1140static bool createFakeEntryFrame(Thread* thread)
1141{
1142 assert(thread->threadId == kMainThreadId); // main thread only
1143
1144 /* find the method on first use */
1145 if (gDvm.methFakeNativeEntry == NULL) {
1146 ClassObject* nativeStart;
1147 Method* mainMeth;
1148
1149 nativeStart = dvmFindSystemClassNoInit(
1150 "Ldalvik/system/NativeStart;");
1151 if (nativeStart == NULL) {
1152 LOGE("Unable to find dalvik.system.NativeStart class\n");
1153 return false;
1154 }
1155
1156 /*
1157 * Because we are creating a frame that represents application code, we
1158 * want to stuff the application class loader into the method's class
1159 * loader field, even though we're using the system class loader to
1160 * load it. This makes life easier over in JNI FindClass (though it
1161 * could bite us in other ways).
1162 *
1163 * Unfortunately this is occurring too early in the initialization,
1164 * of necessity coming before JNI is initialized, and we're not quite
1165 * ready to set up the application class loader.
1166 *
1167 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1168 * and check it in FindClass. The method is private so nobody else
1169 * can call it.
1170 */
1171 //nativeStart->classLoader = dvmGetSystemClassLoader();
1172
1173 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1174 "main", "([Ljava/lang/String;)V");
1175 if (mainMeth == NULL) {
1176 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1177 return false;
1178 }
1179
1180 gDvm.methFakeNativeEntry = mainMeth;
1181 }
1182
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001183 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1184 return false;
1185
1186 /*
1187 * Null out the "String[] args" argument.
1188 */
1189 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1190 u4* framePtr = (u4*) thread->curFrame;
1191 framePtr[0] = 0;
1192
1193 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001194}
1195
1196
1197/*
1198 * Add a stack frame that makes it look like the native thread has been
1199 * executing interpreted code. This gives us a place to hang JNI local
1200 * references.
1201 */
1202static bool createFakeRunFrame(Thread* thread)
1203{
1204 ClassObject* nativeStart;
1205 Method* runMeth;
1206
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001207 /*
1208 * TODO: cache this result so we don't have to dig for it every time
1209 * somebody attaches a thread to the VM. Also consider changing this
1210 * to a static method so we don't have a null "this" pointer in the
1211 * "ins" on the stack. (Does it really need to look like a Runnable?)
1212 */
1213 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001214 if (nativeStart == NULL) {
1215 LOGE("Unable to find dalvik.system.NativeStart class\n");
1216 return false;
1217 }
1218
1219 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1220 if (runMeth == NULL) {
1221 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1222 return false;
1223 }
1224
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001225 if (!dvmPushJNIFrame(thread, runMeth))
1226 return false;
1227
1228 /*
1229 * Provide a NULL 'this' argument. The method we've put at the top of
1230 * the stack looks like a virtual call to run() in a Runnable class.
1231 * (If we declared the method static, it wouldn't take any arguments
1232 * and we wouldn't have to do this.)
1233 */
1234 assert(runMeth->registersSize == 1);
1235 u4* framePtr = (u4*) thread->curFrame;
1236 framePtr[0] = 0;
1237
1238 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001239}
1240
1241/*
1242 * Helper function to set the name of the current thread
1243 */
1244static void setThreadName(const char *threadName)
1245{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001246 int hasAt = 0;
1247 int hasDot = 0;
1248 const char *s = threadName;
1249 while (*s) {
1250 if (*s == '.') hasDot = 1;
1251 else if (*s == '@') hasAt = 1;
1252 s++;
1253 }
1254 int len = s - threadName;
1255 if (len < 15 || hasAt || !hasDot) {
1256 s = threadName;
1257 } else {
1258 s = threadName + len - 15;
1259 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001260#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001261 /* pthread_setname_np fails rather than truncating long strings */
1262 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1263 strncpy(buf, s, sizeof(buf)-1);
1264 buf[sizeof(buf)-1] = '\0';
1265 int err = pthread_setname_np(pthread_self(), buf);
1266 if (err != 0) {
1267 LOGW("Unable to set the name of current thread to '%s': %s\n",
1268 buf, strerror(err));
1269 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001270#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001271 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001272#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001273 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001274#endif
1275}
1276
1277/*
1278 * Create a thread as a result of java.lang.Thread.start().
1279 *
1280 * We do have to worry about some concurrency problems, e.g. programs
1281 * that try to call Thread.start() on the same object from multiple threads.
1282 * (This will fail for all but one, but we have to make sure that it succeeds
1283 * for exactly one.)
1284 *
1285 * Some of the complexity here arises from our desire to mimic the
1286 * Thread vs. VMThread class decomposition we inherited. We've been given
1287 * a Thread, and now we need to create a VMThread and then populate both
1288 * objects. We also need to create one of our internal Thread objects.
1289 *
1290 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001291 *
1292 * The "threadObj" reference must be pinned by the caller to prevent the GC
1293 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001294 */
1295bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1296{
1297 pthread_attr_t threadAttr;
1298 pthread_t threadHandle;
1299 Thread* self;
1300 Thread* newThread = NULL;
1301 Object* vmThreadObj = NULL;
1302 int stackSize;
1303
1304 assert(threadObj != NULL);
1305
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001306 self = dvmThreadSelf();
1307 if (reqStackSize == 0)
1308 stackSize = gDvm.stackSize;
1309 else if (reqStackSize < kMinStackSize)
1310 stackSize = kMinStackSize;
1311 else if (reqStackSize > kMaxStackSize)
1312 stackSize = kMaxStackSize;
1313 else
1314 stackSize = reqStackSize;
1315
1316 pthread_attr_init(&threadAttr);
1317 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1318
1319 /*
1320 * To minimize the time spent in the critical section, we allocate the
1321 * vmThread object here.
1322 */
1323 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1324 if (vmThreadObj == NULL)
1325 goto fail;
1326
1327 newThread = allocThread(stackSize);
1328 if (newThread == NULL)
1329 goto fail;
1330 newThread->threadObj = threadObj;
1331
1332 assert(newThread->status == THREAD_INITIALIZING);
1333
1334 /*
1335 * We need to lock out other threads while we test and set the
1336 * "vmThread" field in java.lang.Thread, because we use that to determine
1337 * if this thread has been started before. We use the thread list lock
1338 * because it's handy and we're going to need to grab it again soon
1339 * anyway.
1340 */
1341 dvmLockThreadList(self);
1342
1343 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1344 dvmUnlockThreadList();
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001345 dvmThrowIllegalThreadStateException(
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001346 "thread has already been started");
1347 goto fail;
1348 }
1349
1350 /*
1351 * There are actually three data structures: Thread (object), VMThread
1352 * (object), and Thread (C struct). All of them point to at least one
1353 * other.
1354 *
1355 * As soon as "VMThread.vmData" is assigned, other threads can start
1356 * making calls into us (e.g. setPriority).
1357 */
1358 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1359 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1360
1361 /*
1362 * Thread creation might take a while, so release the lock.
1363 */
1364 dvmUnlockThreadList();
1365
Carl Shapiro5617ad32010-07-02 10:50:57 -07001366 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1367 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001368 newThread);
1369 oldStatus = dvmChangeStatus(self, oldStatus);
1370
1371 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001372 /*
1373 * Failure generally indicates that we have exceeded system
1374 * resource limits. VirtualMachineError is probably too severe,
1375 * so use OutOfMemoryError.
1376 */
1377 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1378
1379 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1380
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001381 dvmThrowOutOfMemoryError("thread creation failed");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001382 goto fail;
1383 }
1384
1385 /*
1386 * We need to wait for the thread to start. Otherwise, depending on
1387 * the whims of the OS scheduler, we could return and the code in our
1388 * thread could try to do operations on the new thread before it had
1389 * finished starting.
1390 *
1391 * The new thread will lock the thread list, change its state to
1392 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1393 * on gDvm.threadStartCond (which uses the thread list lock). This
1394 * thread (the parent) will either see that the thread is already ready
1395 * after we grab the thread list lock, or will be awakened from the
1396 * condition variable on the broadcast.
1397 *
1398 * We don't want to stall the rest of the VM while the new thread
1399 * starts, which can happen if the GC wakes up at the wrong moment.
1400 * So, we change our own status to VMWAIT, and self-suspend if
1401 * necessary after we finish adding the new thread.
1402 *
1403 *
1404 * We have to deal with an odd race with the GC/debugger suspension
1405 * mechanism when creating a new thread. The information about whether
1406 * or not a thread should be suspended is contained entirely within
1407 * the Thread struct; this is usually cleaner to deal with than having
1408 * one or more globally-visible suspension flags. The trouble is that
1409 * we could create the thread while the VM is trying to suspend all
1410 * threads. The suspend-count won't be nonzero for the new thread,
1411 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1412 *
1413 * The easiest way to deal with this is to prevent the new thread from
1414 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001415 * following (correct) sequence of events for a "badly timed" GC
1416 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001417 *
1418 * - call pthread_create()
1419 * - lock thread list
1420 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1421 * - sleep on condition var (mutex = thread list lock) until child starts
1422 * + GC triggered by another thread
1423 * + thread list locked; suspend counts updated; thread list unlocked
1424 * + loop waiting for all runnable threads to suspend
1425 * + success, start GC
1426 * o child thread wakes, signals condition var to wake parent
1427 * o child waits for parent ack on condition variable
1428 * - we wake up, locking thread list
1429 * - add child to thread list
1430 * - unlock thread list
1431 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1432 * + GC finishes; all threads in thread list are resumed
1433 * - lock thread list
1434 * - set child to THREAD_VMWAIT, and signal it to start
1435 * - unlock thread list
1436 * o child resumes
1437 * o child changes state to THREAD_RUNNING
1438 *
1439 * The above shows the GC starting up during thread creation, but if
1440 * it starts anywhere after VMThread.create() is called it will
1441 * produce the same series of events.
1442 *
1443 * Once the child is in the thread list, it will be suspended and
1444 * resumed like any other thread. In the above scenario the resume-all
1445 * code will try to resume the new thread, which was never actually
1446 * suspended, and try to decrement the child's thread suspend count to -1.
1447 * We can catch this in the resume-all code.
1448 *
1449 * Bouncing back and forth between threads like this adds a small amount
1450 * of scheduler overhead to thread startup.
1451 *
1452 * One alternative to having the child wait for the parent would be
1453 * to have the child inherit the parents' suspension count. This
1454 * would work for a GC, since we can safely assume that the parent
1455 * thread didn't cause it, but we must only do so if the parent suspension
1456 * was caused by a suspend-all. If the parent was being asked to
1457 * suspend singly by the debugger, the child should not inherit the value.
1458 *
1459 * We could also have a global "new thread suspend count" that gets
1460 * picked up by new threads before changing state to THREAD_RUNNING.
1461 * This would be protected by the thread list lock and set by a
1462 * suspend-all.
1463 */
1464 dvmLockThreadList(self);
1465 assert(self->status == THREAD_RUNNING);
1466 self->status = THREAD_VMWAIT;
1467 while (newThread->status != THREAD_STARTING)
1468 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1469
1470 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1471 newThread->next = gDvm.threadList->next;
1472 if (newThread->next != NULL)
1473 newThread->next->prev = newThread;
1474 newThread->prev = gDvm.threadList;
1475 gDvm.threadList->next = newThread;
1476
1477 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1478 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1479
1480 dvmUnlockThreadList();
1481
1482 /* change status back to RUNNING, self-suspending if necessary */
1483 dvmChangeStatus(self, THREAD_RUNNING);
1484
1485 /*
1486 * Tell the new thread to start.
1487 *
1488 * We must hold the thread list lock before messing with another thread.
1489 * In the general case we would also need to verify that newThread was
1490 * still in the thread list, but in our case the thread has not started
1491 * executing user code and therefore has not had a chance to exit.
1492 *
1493 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1494 * comes with a suspend-pending check.
1495 */
1496 dvmLockThreadList(self);
1497
1498 assert(newThread->status == THREAD_STARTING);
1499 newThread->status = THREAD_VMWAIT;
1500 pthread_cond_broadcast(&gDvm.threadStartCond);
1501
1502 dvmUnlockThreadList();
1503
1504 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1505 return true;
1506
1507fail:
1508 freeThread(newThread);
1509 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1510 return false;
1511}
1512
1513/*
1514 * pthread entry function for threads started from interpreted code.
1515 */
1516static void* interpThreadStart(void* arg)
1517{
1518 Thread* self = (Thread*) arg;
1519
1520 char *threadName = dvmGetThreadName(self);
1521 setThreadName(threadName);
1522 free(threadName);
1523
1524 /*
1525 * Finish initializing the Thread struct.
1526 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001527 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001528 prepareThread(self);
1529
1530 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1531
1532 /*
1533 * Change our status and wake our parent, who will add us to the
1534 * thread list and advance our state to VMWAIT.
1535 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001536 self->status = THREAD_STARTING;
1537 pthread_cond_broadcast(&gDvm.threadStartCond);
1538
1539 /*
1540 * Wait until the parent says we can go. Assuming there wasn't a
1541 * suspend pending, this will happen immediately. When it completes,
1542 * we're full-fledged citizens of the VM.
1543 *
1544 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1545 * because the pthread_cond_wait below needs to reacquire a lock that
1546 * suspend-all is also interested in. If we get unlucky, the parent could
1547 * change us to THREAD_RUNNING, then a GC could start before we get
1548 * signaled, and suspend-all will grab the thread list lock and then
1549 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1550 * trying to get the lock.
1551 */
1552 while (self->status != THREAD_VMWAIT)
1553 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1554
1555 dvmUnlockThreadList();
1556
1557 /*
1558 * Add a JNI context.
1559 */
1560 self->jniEnv = dvmCreateJNIEnv(self);
1561
1562 /*
1563 * Change our state so the GC will wait for us from now on. If a GC is
1564 * in progress this call will suspend us.
1565 */
1566 dvmChangeStatus(self, THREAD_RUNNING);
1567
1568 /*
1569 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001570 * us to suspend ourselves (and others). The thread state may change
1571 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001572 */
1573 if (gDvm.debuggerConnected)
1574 dvmDbgPostThreadStart(self);
1575
1576 /*
1577 * Set the system thread priority according to the Thread object's
1578 * priority level. We don't usually need to do this, because both the
1579 * Thread object and system thread priorities inherit from parents. The
1580 * tricky case is when somebody creates a Thread object, calls
1581 * setPriority(), and then starts the thread. We could manage this with
1582 * a "needs priority update" flag to avoid the redundant call.
1583 */
Andy McFadden4879df92009-08-07 14:49:40 -07001584 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001585 gDvm.offJavaLangThread_priority);
1586 dvmChangeThreadPriority(self, priority);
1587
1588 /*
1589 * Execute the "run" method.
1590 *
1591 * At this point our stack is empty, so somebody who comes looking for
1592 * stack traces right now won't have much to look at. This is normal.
1593 */
1594 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1595 JValue unused;
1596
1597 LOGV("threadid=%d: calling run()\n", self->threadId);
1598 assert(strcmp(run->name, "run") == 0);
1599 dvmCallMethod(self, run, self->threadObj, &unused);
1600 LOGV("threadid=%d: exiting\n", self->threadId);
1601
1602 /*
1603 * Remove the thread from various lists, report its death, and free
1604 * its resources.
1605 */
1606 dvmDetachCurrentThread();
1607
1608 return NULL;
1609}
1610
1611/*
1612 * The current thread is exiting with an uncaught exception. The
1613 * Java programming language allows the application to provide a
1614 * thread-exit-uncaught-exception handler for the VM, for a specific
1615 * Thread, and for all threads in a ThreadGroup.
1616 *
1617 * Version 1.5 added the per-thread handler. We need to call
1618 * "uncaughtException" in the handler object, which is either the
1619 * ThreadGroup object or the Thread-specific handler.
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001620 *
1621 * This should only be called when an exception is pending. Before
1622 * returning, the exception will be cleared.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001623 */
1624static void threadExitUncaughtException(Thread* self, Object* group)
1625{
1626 Object* exception;
1627 Object* handlerObj;
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001628 Method* uncaughtHandler;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001629
1630 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1631 self->threadId, group);
1632 assert(group != NULL);
1633
1634 /*
1635 * Get a pointer to the exception, then clear out the one in the
1636 * thread. We don't want to have it set when executing interpreted code.
1637 */
1638 exception = dvmGetException(self);
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001639 assert(exception != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001640 dvmAddTrackedAlloc(exception, self);
1641 dvmClearException(self);
1642
1643 /*
1644 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1645 * else use "group" (which is an instance of UncaughtExceptionHandler).
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001646 * The ThreadGroup will handle it directly or call the default
1647 * uncaught exception handler.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001648 */
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001649 handlerObj = dvmGetFieldObject(self->threadObj,
1650 gDvm.offJavaLangThread_uncaughtHandler);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001651 if (handlerObj == NULL)
1652 handlerObj = group;
1653
1654 /*
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001655 * Find the "uncaughtException" method in this object. The method
1656 * was declared in the Thread.UncaughtExceptionHandler interface.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001657 */
1658 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1659 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1660
1661 if (uncaughtHandler != NULL) {
1662 //LOGI("+++ calling %s.uncaughtException\n",
1663 // handlerObj->clazz->descriptor);
1664 JValue unused;
1665 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1666 self->threadObj, exception);
1667 } else {
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001668 /* should be impossible, but handle it anyway */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001669 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1670 handlerObj->clazz->descriptor);
1671 dvmSetException(self, exception);
1672 dvmLogExceptionStackTrace();
1673 }
1674
Andy McFadden19cd2fc2011-03-24 13:45:14 -07001675 /* if the uncaught handler threw, clear it */
1676 dvmClearException(self);
1677
1678 dvmReleaseTrackedAlloc(exception, self);
1679
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001680 /* Remove this thread's suspendCount from global suspendCount sum */
1681 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08001682 dvmAddToSuspendCounts(self, -self->interpBreak.ctl.suspendCount, 0);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001683 unlockThreadSuspendCount();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001684}
1685
1686
1687/*
1688 * Create an internal VM thread, for things like JDWP and finalizers.
1689 *
1690 * The easiest way to do this is create a new thread and then use the
1691 * JNI AttachCurrentThread implementation.
1692 *
1693 * This does not return until after the new thread has begun executing.
1694 */
1695bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1696 InternalThreadStart func, void* funcArg)
1697{
1698 InternalStartArgs* pArgs;
1699 Object* systemGroup;
1700 pthread_attr_t threadAttr;
1701 volatile Thread* newThread = NULL;
1702 volatile int createStatus = 0;
1703
1704 systemGroup = dvmGetSystemThreadGroup();
1705 if (systemGroup == NULL)
1706 return false;
1707
1708 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1709 pArgs->func = func;
1710 pArgs->funcArg = funcArg;
1711 pArgs->name = strdup(name); // storage will be owned by new thread
1712 pArgs->group = systemGroup;
1713 pArgs->isDaemon = true;
1714 pArgs->pThread = &newThread;
1715 pArgs->pCreateStatus = &createStatus;
1716
1717 pthread_attr_init(&threadAttr);
1718 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1719
1720 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1721 pArgs) != 0)
1722 {
1723 LOGE("internal thread creation failed\n");
1724 free(pArgs->name);
1725 free(pArgs);
1726 return false;
1727 }
1728
1729 /*
1730 * Wait for the child to start. This gives us an opportunity to make
1731 * sure that the thread started correctly, and allows our caller to
1732 * assume that the thread has started running.
1733 *
1734 * Because we aren't holding a lock across the thread creation, it's
1735 * possible that the child will already have completed its
1736 * initialization. Because the child only adjusts "createStatus" while
1737 * holding the thread list lock, the initial condition on the "while"
1738 * loop will correctly avoid the wait if this occurs.
1739 *
1740 * It's also possible that we'll have to wait for the thread to finish
1741 * being created, and as part of allocating a Thread object it might
1742 * need to initiate a GC. We switch to VMWAIT while we pause.
1743 */
1744 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001745 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001746 dvmLockThreadList(self);
1747 while (createStatus == 0)
1748 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1749
1750 if (newThread == NULL) {
1751 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1752 assert(createStatus < 0);
1753 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1754 dvmUnlockThreadList();
1755 dvmChangeStatus(self, oldStatus);
1756 return false;
1757 }
1758
1759 /* thread could be in any state now (except early init states) */
1760 //assert(newThread->status == THREAD_RUNNING);
1761
1762 dvmUnlockThreadList();
1763 dvmChangeStatus(self, oldStatus);
1764
1765 return true;
1766}
1767
1768/*
1769 * pthread entry function for internally-created threads.
1770 *
1771 * We are expected to free "arg" and its contents. If we're a daemon
1772 * thread, and we get cancelled abruptly when the VM shuts down, the
1773 * storage won't be freed. If this becomes a concern we can make a copy
1774 * on the stack.
1775 */
1776static void* internalThreadStart(void* arg)
1777{
1778 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1779 JavaVMAttachArgs jniArgs;
1780
1781 jniArgs.version = JNI_VERSION_1_2;
1782 jniArgs.name = pArgs->name;
1783 jniArgs.group = pArgs->group;
1784
1785 setThreadName(pArgs->name);
1786
1787 /* use local jniArgs as stack top */
1788 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1789 /*
1790 * Tell the parent of our success.
1791 *
1792 * threadListLock is the mutex for threadStartCond.
1793 */
1794 dvmLockThreadList(dvmThreadSelf());
1795 *pArgs->pCreateStatus = 1;
1796 *pArgs->pThread = dvmThreadSelf();
1797 pthread_cond_broadcast(&gDvm.threadStartCond);
1798 dvmUnlockThreadList();
1799
1800 LOG_THREAD("threadid=%d: internal '%s'\n",
1801 dvmThreadSelf()->threadId, pArgs->name);
1802
1803 /* execute */
1804 (*pArgs->func)(pArgs->funcArg);
1805
1806 /* detach ourselves */
1807 dvmDetachCurrentThread();
1808 } else {
1809 /*
1810 * Tell the parent of our failure. We don't have a Thread struct,
1811 * so we can't be suspended, so we don't need to enter a critical
1812 * section.
1813 */
1814 dvmLockThreadList(dvmThreadSelf());
1815 *pArgs->pCreateStatus = -1;
1816 assert(*pArgs->pThread == NULL);
1817 pthread_cond_broadcast(&gDvm.threadStartCond);
1818 dvmUnlockThreadList();
1819
1820 assert(*pArgs->pThread == NULL);
1821 }
1822
1823 free(pArgs->name);
1824 free(pArgs);
1825 return NULL;
1826}
1827
1828/*
1829 * Attach the current thread to the VM.
1830 *
1831 * Used for internally-created threads and JNI's AttachCurrentThread.
1832 */
1833bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1834{
1835 Thread* self = NULL;
1836 Object* threadObj = NULL;
1837 Object* vmThreadObj = NULL;
1838 StringObject* threadNameStr = NULL;
1839 Method* init;
1840 bool ok, ret;
1841
Andy McFaddene3346d82010-06-02 15:37:21 -07001842 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001843 self = allocThread(gDvm.stackSize);
1844 if (self == NULL)
1845 goto fail;
1846 setThreadSelf(self);
1847
1848 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001849 * Finish our thread prep. We need to do this before adding ourselves
1850 * to the thread list or invoking any interpreted code. prepareThread()
1851 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001852 */
1853 dvmLockThreadList(self);
1854 ok = prepareThread(self);
1855 dvmUnlockThreadList();
1856 if (!ok)
1857 goto fail;
1858
1859 self->jniEnv = dvmCreateJNIEnv(self);
1860 if (self->jniEnv == NULL)
1861 goto fail;
1862
1863 /*
1864 * Create a "fake" JNI frame at the top of the main thread interp stack.
1865 * It isn't really necessary for the internal threads, but it gives
1866 * the debugger something to show. It is essential for the JNI-attached
1867 * threads.
1868 */
1869 if (!createFakeRunFrame(self))
1870 goto fail;
1871
1872 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001873 * The native side of the thread is ready; add it to the list. Once
1874 * 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 -08001875 */
1876 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1877
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001878 dvmLockThreadList(self);
1879
1880 self->next = gDvm.threadList->next;
1881 if (self->next != NULL)
1882 self->next->prev = self;
1883 self->prev = gDvm.threadList;
1884 gDvm.threadList->next = self;
1885 if (!isDaemon)
1886 gDvm.nonDaemonThreadCount++;
1887
1888 dvmUnlockThreadList();
1889
1890 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001891 * Switch state from initializing to running.
1892 *
1893 * It's possible that a GC began right before we added ourselves
1894 * to the thread list, and is still going. That means our thread
1895 * suspend count won't reflect the fact that we should be suspended.
1896 * To deal with this, we transition to VMWAIT, pulse the heap lock,
1897 * and then advance to RUNNING. That will ensure that we stall until
1898 * the GC completes.
1899 *
1900 * Once we're in RUNNING, we're like any other thread in the VM (except
1901 * for the lack of an initialized threadObj). We're then free to
1902 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001903 */
Andy McFaddene3346d82010-06-02 15:37:21 -07001904 assert(self->status == THREAD_INITIALIZING);
1905 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001906 dvmLockMutex(&gDvm.gcHeapLock);
1907 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07001908 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001909
1910 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001911 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001912 */
Andy McFaddene3346d82010-06-02 15:37:21 -07001913 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
1914 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1915 if (threadObj == NULL || vmThreadObj == NULL)
1916 goto fail_unlink;
1917
1918 /*
1919 * This makes threadObj visible to the GC. We still have it in the
1920 * tracked allocation table, so it can't move around on us.
1921 */
1922 self->threadObj = threadObj;
1923 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1924
1925 /*
1926 * Create a string for the thread name.
1927 */
1928 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07001929 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07001930 if (threadNameStr == NULL) {
1931 assert(dvmCheckException(dvmThreadSelf()));
1932 goto fail_unlink;
1933 }
1934 }
1935
1936 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1937 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1938 if (init == NULL) {
1939 assert(dvmCheckException(self));
1940 goto fail_unlink;
1941 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001942
1943 /*
1944 * Now we're ready to run some interpreted code.
1945 *
1946 * We need to construct the Thread object and set the VMThread field.
1947 * Setting VMThread tells interpreted code that we're alive.
1948 *
1949 * Call the (group, name, priority, daemon) constructor on the Thread.
1950 * This sets the thread's name and adds it to the specified group, and
1951 * provides values for priority and daemon (which are normally inherited
1952 * from the current thread).
1953 */
1954 JValue unused;
1955 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
1956 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
1957 if (dvmCheckException(self)) {
1958 LOGE("exception thrown while constructing attached thread object\n");
1959 goto fail_unlink;
1960 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001961
1962 /*
1963 * Set the VMThread field, which tells interpreted code that we're alive.
1964 *
1965 * The risk of a thread start collision here is very low; somebody
1966 * would have to be deliberately polling the ThreadGroup list and
1967 * trying to start threads against anything it sees, which would
1968 * generally cause problems for all thread creation. However, for
1969 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07001970 *
1971 * TODO: this still has a race, it's just smaller. Not sure this is
1972 * worth putting effort into fixing. Need to hold a lock while
1973 * fiddling with the field, or maybe initialize the Thread object in a
1974 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001975 */
1976 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07001977 LOGW("WOW: thread start hijack\n");
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001978 dvmThrowIllegalThreadStateException(
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001979 "thread has already been started");
1980 /* We don't want to free anything associated with the thread
1981 * because someone is obviously interested in it. Just let
1982 * it go and hope it will clean itself up when its finished.
1983 * This case should never happen anyway.
1984 *
1985 * Since we're letting it live, we need to finish setting it up.
1986 * We just have to let the caller know that the intended operation
1987 * has failed.
1988 *
1989 * [ This seems strange -- stepping on the vmThread object that's
1990 * already present seems like a bad idea. TODO: figure this out. ]
1991 */
1992 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07001993 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001994 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07001995 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001996 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1997
Andy McFaddene3346d82010-06-02 15:37:21 -07001998 /* we can now safely un-pin these */
1999 dvmReleaseTrackedAlloc(threadObj, self);
2000 dvmReleaseTrackedAlloc(vmThreadObj, self);
2001 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002002
2003 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2004 self->threadId, pArgs->name);
2005
2006 /* tell the debugger & DDM */
2007 if (gDvm.debuggerConnected)
2008 dvmDbgPostThreadStart(self);
2009
2010 return ret;
2011
2012fail_unlink:
2013 dvmLockThreadList(self);
2014 unlinkThread(self);
2015 if (!isDaemon)
2016 gDvm.nonDaemonThreadCount--;
2017 dvmUnlockThreadList();
2018 /* fall through to "fail" */
2019fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002020 dvmReleaseTrackedAlloc(threadObj, self);
2021 dvmReleaseTrackedAlloc(vmThreadObj, self);
2022 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002023 if (self != NULL) {
2024 if (self->jniEnv != NULL) {
2025 dvmDestroyJNIEnv(self->jniEnv);
2026 self->jniEnv = NULL;
2027 }
2028 freeThread(self);
2029 }
2030 setThreadSelf(NULL);
2031 return false;
2032}
2033
2034/*
2035 * Detach the thread from the various data structures, notify other threads
2036 * that are waiting to "join" it, and free up all heap-allocated storage.
2037 *
2038 * Used for all threads.
2039 *
2040 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2041 * requires us to enforce this for the DetachCurrentThread call, probably
2042 * because it also says that DetachCurrentThread causes all monitors
2043 * associated with the thread to be released. (Because the stack is empty,
2044 * we only have to worry about explicit JNI calls to MonitorEnter.)
2045 *
2046 * THOUGHT:
2047 * We might want to avoid freeing our internal Thread structure until the
2048 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2049 * get to once the thread shuts down, but there is a small possibility of
2050 * an operation starting in another thread before this thread halts, and
2051 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2052 * We don't want something like Thread.isInterrupted() crawling through
2053 * freed storage. Can do with a Thread finalizer, or by creating a
2054 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2055 * state into that.
2056 */
2057void dvmDetachCurrentThread(void)
2058{
2059 Thread* self = dvmThreadSelf();
2060 Object* vmThread;
2061 Object* group;
2062
2063 /*
2064 * Make sure we're not detaching a thread that's still running. (This
2065 * could happen with an explicit JNI detach call.)
2066 *
2067 * A thread created by interpreted code will finish with a depth of
2068 * zero, while a JNI-attached thread will have the synthetic "stack
2069 * starter" native method at the top.
2070 */
2071 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2072 if (curDepth != 0) {
2073 bool topIsNative = false;
2074
2075 if (curDepth == 1) {
2076 /* not expecting a lingering break frame; just look at curFrame */
Carl Shapirofc75f3e2010-12-07 11:43:38 -08002077 assert(!dvmIsBreakFrame((u4*)self->curFrame));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002078 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2079 if (dvmIsNativeMethod(ssa->method))
2080 topIsNative = true;
2081 }
2082
2083 if (!topIsNative) {
2084 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2085 curDepth);
2086 dvmDumpThread(self, false);
2087 dvmAbort();
2088 }
2089 }
2090
2091 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2092 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2093
2094 /*
2095 * Release any held monitors. Since there are no interpreted stack
2096 * frames, the only thing left are the monitors held by JNI MonitorEnter
2097 * calls.
2098 */
2099 dvmReleaseJniMonitors(self);
2100
2101 /*
2102 * Do some thread-exit uncaught exception processing if necessary.
2103 */
2104 if (dvmCheckException(self))
2105 threadExitUncaughtException(self, group);
2106
2107 /*
2108 * Remove the thread from the thread group.
2109 */
2110 if (group != NULL) {
2111 Method* removeThread =
2112 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2113 JValue unused;
2114 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2115 }
2116
2117 /*
2118 * Clear the vmThread reference in the Thread object. Interpreted code
2119 * will now see that this Thread is not running. As this may be the
2120 * only reference to the VMThread object that the VM knows about, we
2121 * have to create an internal reference to it first.
2122 */
2123 vmThread = dvmGetFieldObject(self->threadObj,
2124 gDvm.offJavaLangThread_vmThread);
2125 dvmAddTrackedAlloc(vmThread, self);
2126 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2127
2128 /* clear out our struct Thread pointer, since it's going away */
2129 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2130
2131 /*
2132 * Tell the debugger & DDM. This may cause the current thread or all
2133 * threads to suspend.
2134 *
2135 * The JDWP spec is somewhat vague about when this happens, other than
2136 * that it's issued by the dying thread, which may still appear in
2137 * an "all threads" listing.
2138 */
2139 if (gDvm.debuggerConnected)
2140 dvmDbgPostThreadDeath(self);
2141
2142 /*
2143 * Thread.join() is implemented as an Object.wait() on the VMThread
2144 * object. Signal anyone who is waiting.
2145 */
2146 dvmLockObject(self, vmThread);
2147 dvmObjectNotifyAll(self, vmThread);
2148 dvmUnlockObject(self, vmThread);
2149
2150 dvmReleaseTrackedAlloc(vmThread, self);
2151 vmThread = NULL;
2152
2153 /*
2154 * We're done manipulating objects, so it's okay if the GC runs in
2155 * parallel with us from here out. It's important to do this if
2156 * profiling is enabled, since we can wait indefinitely.
2157 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002158 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002159
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002160 /*
2161 * If we're doing method trace profiling, we don't want threads to exit,
2162 * because if they do we'll end up reusing thread IDs. This complicates
2163 * analysis and makes it impossible to have reasonable output in the
2164 * "threads" section of the "key" file.
2165 *
2166 * We need to do this after Thread.join() completes, or other threads
2167 * could get wedged. Since self->threadObj is still valid, the Thread
2168 * object will not get GCed even though we're no longer in the ThreadGroup
2169 * list (which is important since the profiling thread needs to get
2170 * the thread's name).
2171 */
2172 MethodTraceState* traceState = &gDvm.methodTrace;
2173
2174 dvmLockMutex(&traceState->startStopLock);
2175 if (traceState->traceEnabled) {
2176 LOGI("threadid=%d: waiting for method trace to finish\n",
2177 self->threadId);
2178 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002179 dvmWaitCond(&traceState->threadExitCond,
2180 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002181 }
2182 }
2183 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002184
2185 dvmLockThreadList(self);
2186
2187 /*
2188 * Lose the JNI context.
2189 */
2190 dvmDestroyJNIEnv(self->jniEnv);
2191 self->jniEnv = NULL;
2192
2193 self->status = THREAD_ZOMBIE;
2194
2195 /*
2196 * Remove ourselves from the internal thread list.
2197 */
2198 unlinkThread(self);
2199
2200 /*
2201 * If we're the last one standing, signal anybody waiting in
2202 * DestroyJavaVM that it's okay to exit.
2203 */
2204 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2205 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2206
2207 if (gDvm.nonDaemonThreadCount == 0) {
2208 int cc;
2209
2210 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2211 //dvmDumpAllThreads(false);
2212 // cond var guarded by threadListLock, which we already hold
2213 cc = pthread_cond_signal(&gDvm.vmExitCond);
2214 assert(cc == 0);
2215 }
2216 }
2217
2218 LOGV("threadid=%d: bye!\n", self->threadId);
2219 releaseThreadId(self);
2220 dvmUnlockThreadList();
2221
2222 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002223
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002224 freeThread(self);
2225}
2226
2227
2228/*
2229 * Suspend a single thread. Do not use to suspend yourself.
2230 *
2231 * This is used primarily for debugger/DDMS activity. Does not return
2232 * until the thread has suspended or is in a "safe" state (e.g. executing
2233 * native code outside the VM).
2234 *
2235 * The thread list lock should be held before calling here -- it's not
2236 * entirely safe to hang on to a Thread* from another thread otherwise.
2237 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2238 */
2239void dvmSuspendThread(Thread* thread)
2240{
2241 assert(thread != NULL);
2242 assert(thread != dvmThreadSelf());
2243 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2244
2245 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08002246 dvmAddToSuspendCounts(thread, 1, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002247
2248 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
buzbee9a3147c2011-03-02 15:43:48 -08002249 thread->threadId, thread->interpBreak.ctl.suspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002250 unlockThreadSuspendCount();
2251
2252 waitForThreadSuspend(dvmThreadSelf(), thread);
2253}
2254
2255/*
2256 * Reduce the suspend count of a thread. If it hits zero, tell it to
2257 * resume.
2258 *
2259 * Used primarily for debugger/DDMS activity. The thread in question
2260 * might have been suspended singly or as part of a suspend-all operation.
2261 *
2262 * The thread list lock should be held before calling here -- it's not
2263 * entirely safe to hang on to a Thread* from another thread otherwise.
2264 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2265 */
2266void dvmResumeThread(Thread* thread)
2267{
2268 assert(thread != NULL);
2269 assert(thread != dvmThreadSelf());
2270 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2271
2272 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08002273 if (thread->interpBreak.ctl.suspendCount > 0) {
2274 dvmAddToSuspendCounts(thread, -1, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002275 } else {
2276 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2277 thread->threadId);
2278 }
2279
2280 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
buzbee9a3147c2011-03-02 15:43:48 -08002281 thread->threadId, thread->interpBreak.ctl.suspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002282
buzbee9a3147c2011-03-02 15:43:48 -08002283 if (thread->interpBreak.ctl.suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002284 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002285 }
2286
2287 unlockThreadSuspendCount();
2288}
2289
2290/*
2291 * Suspend yourself, as a result of debugger activity.
2292 */
2293void dvmSuspendSelf(bool jdwpActivity)
2294{
2295 Thread* self = dvmThreadSelf();
2296
Andy McFadden6dce9962010-08-23 16:45:24 -07002297 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002298 assert(gDvm.jdwpState != NULL);
2299 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2300 assert(false);
2301 return;
2302 }
2303
2304 /*
2305 * Collisions with other suspends aren't really interesting. We want
2306 * to ensure that we're the only one fiddling with the suspend count
2307 * though.
2308 */
2309 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08002310 dvmAddToSuspendCounts(self, 1, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002311
2312 /*
2313 * Suspend ourselves.
2314 */
buzbee9a3147c2011-03-02 15:43:48 -08002315 assert(self->interpBreak.ctl.suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002316 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002317 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2318
2319 /*
2320 * Tell JDWP that we've completed suspension. The JDWP thread can't
2321 * tell us to resume before we're fully asleep because we hold the
2322 * suspend count lock.
2323 *
2324 * If we got here via waitForDebugger(), don't do this part.
2325 */
2326 if (jdwpActivity) {
2327 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2328 // self->threadId, (int) self->handle);
2329 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2330 }
2331
buzbee9a3147c2011-03-02 15:43:48 -08002332 while (self->interpBreak.ctl.suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002333 dvmWaitCond(&gDvm.threadSuspendCountCond,
2334 &gDvm.threadSuspendCountLock);
buzbee9a3147c2011-03-02 15:43:48 -08002335 if (self->interpBreak.ctl.suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002336 /*
2337 * The condition was signaled but we're still suspended. This
2338 * can happen if the debugger lets go while a SIGQUIT thread
2339 * dump event is pending (assuming SignalCatcher was resumed for
2340 * just long enough to try to grab the thread-suspend lock).
2341 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002342 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
buzbee9a3147c2011-03-02 15:43:48 -08002343 self->threadId, self->interpBreak.ctl.suspendCount,
2344 self->interpBreak.ctl.dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002345 }
2346 }
buzbee9a3147c2011-03-02 15:43:48 -08002347 assert(self->interpBreak.ctl.suspendCount == 0 &&
2348 self->interpBreak.ctl.dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002349 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002350 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2351 self->threadId, self->status);
2352
2353 unlockThreadSuspendCount();
2354}
2355
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002356/*
2357 * Dump the state of the current thread and that of another thread that
2358 * we think is wedged.
2359 */
2360static void dumpWedgedThread(Thread* thread)
2361{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002362 dvmDumpThread(dvmThreadSelf(), false);
Elliott Hughesabd4f6e2011-03-25 11:58:52 -07002363 dvmPrintNativeBackTrace();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002364
2365 // dumping a running thread is risky, but could be useful
2366 dvmDumpThread(thread, true);
2367
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002368 // stop now and get a core dump
2369 //abort();
2370}
2371
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002372/*
2373 * If the thread is running at below-normal priority, temporarily elevate
2374 * it to "normal".
2375 *
2376 * Returns zero if no changes were made. Otherwise, returns bit flags
2377 * indicating what was changed, storing the previous values in the
2378 * provided locations.
2379 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002380int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002381 SchedPolicy* pSavedThreadPolicy)
2382{
2383 errno = 0;
2384 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2385 if (errno != 0) {
2386 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2387 thread->threadId, thread->systemTid);
2388 return 0;
2389 }
2390 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2391 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2392 thread->threadId, thread->systemTid);
2393 return 0;
2394 }
2395
2396 int changeFlags = 0;
2397
2398 /*
2399 * Change the priority if we're in the background group.
2400 */
2401 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2402 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2403 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2404 } else {
2405 changeFlags |= kChangedPolicy;
2406 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2407 thread->systemTid, *pSavedThreadPolicy);
2408 }
2409 }
2410
2411 /*
2412 * getpriority() returns the "nice" value, so larger numbers indicate
2413 * lower priority, with 0 being normal.
2414 */
2415 if (*pSavedThreadPrio > 0) {
2416 const int kHigher = 0;
2417 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2418 LOGW("Couldn't raise priority on tid %d to %d\n",
2419 thread->systemTid, kHigher);
2420 } else {
2421 changeFlags |= kChangedPriority;
2422 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2423 thread->systemTid, *pSavedThreadPrio, kHigher);
2424 }
2425 }
2426
2427 return changeFlags;
2428}
2429
2430/*
2431 * Reset the priority values for the thread in question.
2432 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002433void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002434 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2435{
2436 if ((changeFlags & kChangedPolicy) != 0) {
2437 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2438 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2439 thread->systemTid, savedThreadPolicy);
2440 } else {
2441 LOGD("Restored policy of %d to %d\n",
2442 thread->systemTid, savedThreadPolicy);
2443 }
2444 }
2445
2446 if ((changeFlags & kChangedPriority) != 0) {
2447 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2448 {
2449 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2450 thread->systemTid, savedThreadPrio);
2451 } else {
2452 LOGD("Restored priority on %d to %d\n",
2453 thread->systemTid, savedThreadPrio);
2454 }
2455 }
2456}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002457
2458/*
2459 * Wait for another thread to see the pending suspension and stop running.
2460 * It can either suspend itself or go into a non-running state such as
2461 * VMWAIT or NATIVE in which it cannot interact with the GC.
2462 *
2463 * If we're running at a higher priority, sched_yield() may not do anything,
2464 * so we need to sleep for "long enough" to guarantee that the other
2465 * thread has a chance to finish what it's doing. Sleeping for too short
2466 * a period (e.g. less than the resolution of the sleep clock) might cause
2467 * the scheduler to return immediately, so we want to start with a
2468 * "reasonable" value and expand.
2469 *
2470 * This does not return until the other thread has stopped running.
2471 * Eventually we time out and the VM aborts.
2472 *
2473 * This does not try to detect the situation where two threads are
2474 * waiting for each other to suspend. In normal use this is part of a
2475 * suspend-all, which implies that the suspend-all lock is held, or as
2476 * part of a debugger action in which the JDWP thread is always the one
2477 * doing the suspending. (We may need to re-evaluate this now that
2478 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2479 *
2480 * TODO: track basic stats about time required to suspend VM.
2481 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002482#define FIRST_SLEEP (250*1000) /* 0.25s */
2483#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002484static void waitForThreadSuspend(Thread* self, Thread* thread)
2485{
2486 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002487 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002488 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002489 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002490 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002491 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002492
2493 int sleepIter = 0;
2494 int retryCount = 0;
2495 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002496 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002497
Andy McFadden6dce9962010-08-23 16:45:24 -07002498 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002499 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002500 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002501 if (firstStartWhen == 0) // first iteration of first attempt
2502 firstStartWhen = startWhen;
2503
2504 /*
2505 * After waiting for a bit, check to see if the target thread is
2506 * running at a reduced priority. If so, bump it up temporarily
2507 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002508 */
2509 if (retryCount == 2) {
2510 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002511 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002512 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002513 }
2514 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002515
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002516#if defined (WITH_JIT)
2517 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002518 * If we're still waiting after the first timeout, unchain all
2519 * translations iff:
2520 * 1) There are new chains formed since the last unchain
2521 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002522 */
Ben Cheng6999d842010-01-26 16:46:15 -08002523 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2524 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002525 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002526 dvmJitUnchainAll();
2527 }
2528#endif
2529
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002530 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002531 * Sleep briefly. The iterative sleep call returns false if we've
2532 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002533 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002534 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002535 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002536 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002537 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002538 thread->threadId, priChangeFlags);
2539 if (retryCount > 1) {
2540 /* stack trace logging is slow; skip on first iter */
2541 dumpWedgedThread(thread);
2542 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002543 complained = true;
2544 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002545
2546 // keep going; could be slow due to valgrind
2547 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002548 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002549
2550 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002551 LOGE("Fatal spin-on-suspend, dumping threads\n");
2552 dvmDumpAllThreads(false);
2553
2554 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002555 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2556 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002557
2558 /* try to get a debuggerd dump from the spinning thread */
2559 dvmNukeThread(thread);
2560 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002561 dvmAbort();
2562 }
2563 }
2564 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002565
2566 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002567 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2568 self->threadId,
2569 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002570 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2571 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002572 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002573 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002574 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002575 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002576}
2577
2578/*
2579 * Suspend all threads except the current one. This is used by the GC,
2580 * the debugger, and by any thread that hits a "suspend all threads"
2581 * debugger event (e.g. breakpoint or exception).
2582 *
2583 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2584 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2585 * create objects and even execute arbitrary code. The "why" argument
2586 * allows the caller to say why the suspension is taking place.
2587 *
2588 * This can be called when a global suspend has already happened, due to
2589 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2590 * doesn't work.
2591 *
2592 * DO NOT grab any locks before calling here. We grab & release the thread
2593 * lock and suspend lock here (and we're not using recursive threads), and
2594 * we might have to self-suspend if somebody else beats us here.
2595 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002596 * We know the current thread is in the thread list, because we attach the
2597 * thread before doing anything that could cause VM suspension (like object
2598 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002599 */
2600void dvmSuspendAllThreads(SuspendCause why)
2601{
2602 Thread* self = dvmThreadSelf();
2603 Thread* thread;
2604
2605 assert(why != 0);
2606
2607 /*
2608 * Start by grabbing the thread suspend lock. If we can't get it, most
2609 * likely somebody else is in the process of performing a suspend or
2610 * resume, so lockThreadSuspend() will cause us to self-suspend.
2611 *
2612 * We keep the lock until all other threads are suspended.
2613 */
2614 lockThreadSuspend("susp-all", why);
2615
2616 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2617
2618 /*
2619 * This is possible if the current thread was in VMWAIT mode when a
2620 * suspend-all happened, and then decided to do its own suspend-all.
2621 * This can happen when a couple of threads have simultaneous events
2622 * of interest to the debugger.
2623 */
buzbee9a3147c2011-03-02 15:43:48 -08002624 //assert(self->interpBreak.ctl.suspendCount == 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002625
2626 /*
2627 * Increment everybody's suspend count (except our own).
2628 */
2629 dvmLockThreadList(self);
2630
2631 lockThreadSuspendCount();
2632 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2633 if (thread == self)
2634 continue;
2635
2636 /* debugger events don't suspend JDWP thread */
2637 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2638 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2639 continue;
2640
buzbee9a3147c2011-03-02 15:43:48 -08002641 dvmAddToSuspendCounts(thread, 1,
2642 (why == SUSPEND_FOR_DEBUG ||
2643 why == SUSPEND_FOR_DEBUG_EVENT)
2644 ? 1 : 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002645 }
2646 unlockThreadSuspendCount();
2647
2648 /*
2649 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2650 * indicate the code is either running natively or sleeping quietly.
2651 * Any attempt to transition back to THREAD_RUNNING will cause a check
2652 * for suspension, so it should be impossible for anything to execute
2653 * interpreted code or modify objects (assuming native code plays nicely).
2654 *
2655 * It's also okay if the thread transitions to a non-RUNNING state.
2656 *
2657 * Note we released the threadSuspendCountLock before getting here,
2658 * so if another thread is fiddling with its suspend count (perhaps
2659 * self-suspending for the debugger) it won't block while we're waiting
2660 * in here.
2661 */
2662 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2663 if (thread == self)
2664 continue;
2665
2666 /* debugger events don't suspend JDWP thread */
2667 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2668 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2669 continue;
2670
2671 /* wait for the other thread to see the pending suspend */
2672 waitForThreadSuspend(self, thread);
2673
Andy McFadden6dce9962010-08-23 16:45:24 -07002674 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002675 self->threadId,
buzbee9a3147c2011-03-02 15:43:48 -08002676 thread->threadId, thread->status,
2677 thread->interpBreak.ctl.suspendCount,
2678 thread->interpBreak.ctl.dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002679 }
2680
2681 dvmUnlockThreadList();
2682 unlockThreadSuspend();
2683
2684 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2685}
2686
2687/*
2688 * Resume all threads that are currently suspended.
2689 *
2690 * The "why" must match with the previous suspend.
2691 */
2692void dvmResumeAllThreads(SuspendCause why)
2693{
2694 Thread* self = dvmThreadSelf();
2695 Thread* thread;
2696 int cc;
2697
2698 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2699 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2700
2701 /*
2702 * Decrement the suspend counts for all threads. No need for atomic
2703 * writes, since nobody should be moving until we decrement the count.
2704 * We do need to hold the thread list because of JNI attaches.
2705 */
2706 dvmLockThreadList(self);
2707 lockThreadSuspendCount();
2708 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2709 if (thread == self)
2710 continue;
2711
2712 /* debugger events don't suspend JDWP thread */
2713 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2714 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002715 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002716 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002717 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002718
buzbee9a3147c2011-03-02 15:43:48 -08002719 if (thread->interpBreak.ctl.suspendCount > 0) {
2720 dvmAddToSuspendCounts(thread, -1,
2721 (why == SUSPEND_FOR_DEBUG ||
2722 why == SUSPEND_FOR_DEBUG_EVENT)
2723 ? -1 : 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002724 } else {
2725 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2726 thread->threadId);
2727 }
2728 }
2729 unlockThreadSuspendCount();
2730 dvmUnlockThreadList();
2731
2732 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002733 * In some ways it makes sense to continue to hold the thread-suspend
2734 * lock while we issue the wakeup broadcast. It allows us to complete
2735 * one operation before moving on to the next, which simplifies the
2736 * thread activity debug traces.
2737 *
2738 * This approach caused us some difficulty under Linux, because the
2739 * condition variable broadcast not only made the threads runnable,
2740 * but actually caused them to execute, and it was a while before
2741 * the thread performing the wakeup had an opportunity to release the
2742 * thread-suspend lock.
2743 *
2744 * This is a problem because, when a thread tries to acquire that
2745 * lock, it times out after 3 seconds. If at some point the thread
2746 * is told to suspend, the clock resets; but since the VM is still
2747 * theoretically mid-resume, there's no suspend pending. If, for
2748 * example, the GC was waking threads up while the SIGQUIT handler
2749 * was trying to acquire the lock, we would occasionally time out on
2750 * a busy system and SignalCatcher would abort.
2751 *
2752 * We now perform the unlock before the wakeup broadcast. The next
2753 * suspend can't actually start until the broadcast completes and
2754 * returns, because we're holding the thread-suspend-count lock, but the
2755 * suspending thread is now able to make progress and we avoid the abort.
2756 *
2757 * (Technically there is a narrow window between when we release
2758 * the thread-suspend lock and grab the thread-suspend-count lock.
2759 * This could cause us to send a broadcast to threads with nonzero
2760 * suspend counts, but this is expected and they'll all just fall
2761 * right back to sleep. It's probably safe to grab the suspend-count
2762 * lock before releasing thread-suspend, since we're still following
2763 * the correct order of acquisition, but it feels weird.)
2764 */
2765
2766 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2767 unlockThreadSuspend();
2768
2769 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002770 * Broadcast a notification to all suspended threads, some or all of
2771 * which may choose to wake up. No need to wait for them.
2772 */
2773 lockThreadSuspendCount();
2774 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2775 assert(cc == 0);
2776 unlockThreadSuspendCount();
2777
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002778 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2779}
2780
2781/*
2782 * Undo any debugger suspensions. This is called when the debugger
2783 * disconnects.
2784 */
2785void dvmUndoDebuggerSuspensions(void)
2786{
2787 Thread* self = dvmThreadSelf();
2788 Thread* thread;
2789 int cc;
2790
2791 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2792 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2793
2794 /*
2795 * Decrement the suspend counts for all threads. No need for atomic
2796 * writes, since nobody should be moving until we decrement the count.
2797 * We do need to hold the thread list because of JNI attaches.
2798 */
2799 dvmLockThreadList(self);
2800 lockThreadSuspendCount();
2801 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2802 if (thread == self)
2803 continue;
2804
2805 /* debugger events don't suspend JDWP thread */
2806 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
buzbee9a3147c2011-03-02 15:43:48 -08002807 assert(thread->interpBreak.ctl.dbgSuspendCount == 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002808 continue;
2809 }
2810
buzbee9a3147c2011-03-02 15:43:48 -08002811 assert(thread->interpBreak.ctl.suspendCount >=
2812 thread->interpBreak.ctl.dbgSuspendCount);
2813 dvmAddToSuspendCounts(thread,
2814 -thread->interpBreak.ctl.dbgSuspendCount,
2815 -thread->interpBreak.ctl.dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002816 }
2817 unlockThreadSuspendCount();
2818 dvmUnlockThreadList();
2819
2820 /*
2821 * Broadcast a notification to all suspended threads, some or all of
2822 * which may choose to wake up. No need to wait for them.
2823 */
2824 lockThreadSuspendCount();
2825 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2826 assert(cc == 0);
2827 unlockThreadSuspendCount();
2828
2829 unlockThreadSuspend();
2830
2831 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2832}
2833
2834/*
2835 * Determine if a thread is suspended.
2836 *
2837 * As with all operations on foreign threads, the caller should hold
2838 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002839 *
2840 * If the thread is suspending or waking, these fields could be changing
2841 * out from under us (or the thread could change state right after we
2842 * examine it), making this generally unreliable. This is chiefly
2843 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002844 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002845bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002846{
2847 /*
2848 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07002849 * (1) Running happily. status is RUNNING, suspendCount is zero.
2850 * Return "false".
2851 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
2852 * Return "false".
2853 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002854 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07002855 * (4) Waking up. suspendCount is zero, status is SUSPENDED
2856 * Return "false" (since it could change out from under us, unless
2857 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002858 */
2859
buzbee9a3147c2011-03-02 15:43:48 -08002860 return (thread->interpBreak.ctl.suspendCount != 0 &&
2861 thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002862}
2863
2864/*
2865 * Wait until another thread self-suspends. This is specifically for
2866 * synchronization between the JDWP thread and a thread that has decided
2867 * to suspend itself after sending an event to the debugger.
2868 *
2869 * Threads that encounter "suspend all" events work as well -- the thread
2870 * in question suspends everybody else and then itself.
2871 *
2872 * We can't hold a thread lock here or in the caller, because we could
2873 * get here just before the to-be-waited-for-thread issues a "suspend all".
2874 * There's an opportunity for badness if the thread we're waiting for exits
2875 * and gets cleaned up, but since the thread in question is processing a
2876 * debugger event, that's not really a possibility. (To avoid deadlock,
2877 * it's important that we not be in THREAD_RUNNING while we wait.)
2878 */
2879void dvmWaitForSuspend(Thread* thread)
2880{
2881 Thread* self = dvmThreadSelf();
2882
2883 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
2884 self->threadId, thread->threadId);
2885
2886 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2887 assert(thread != self);
2888 assert(self->status != THREAD_RUNNING);
2889
2890 waitForThreadSuspend(self, thread);
2891
2892 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
2893 self->threadId, thread->threadId);
2894}
2895
2896/*
2897 * Check to see if we need to suspend ourselves. If so, go to sleep on
2898 * a condition variable.
2899 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002900 * Returns "true" if we suspended ourselves.
2901 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002902static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002903{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002904 assert(self != NULL);
buzbee9a3147c2011-03-02 15:43:48 -08002905 assert(self->interpBreak.ctl.suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002906
Andy McFadden6dce9962010-08-23 16:45:24 -07002907 /*
2908 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
buzbee9a3147c2011-03-02 15:43:48 -08002909 * access to self->interpBreak.ctl.suspendCount.
Andy McFadden6dce9962010-08-23 16:45:24 -07002910 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002911 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
2912
buzbee9a3147c2011-03-02 15:43:48 -08002913 bool needSuspend = (self->interpBreak.ctl.suspendCount != 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002914 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07002915 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07002916 ThreadStatus oldStatus = self->status; /* should be RUNNING */
2917 self->status = THREAD_SUSPENDED;
2918
buzbee9a3147c2011-03-02 15:43:48 -08002919 while (self->interpBreak.ctl.suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07002920 /*
2921 * Wait for wakeup signal, releasing lock. The act of releasing
2922 * and re-acquiring the lock provides the memory barriers we
2923 * need for correct behavior on SMP.
2924 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002925 dvmWaitCond(&gDvm.threadSuspendCountCond,
2926 &gDvm.threadSuspendCountLock);
2927 }
buzbee9a3147c2011-03-02 15:43:48 -08002928 assert(self->interpBreak.ctl.suspendCount == 0 &&
2929 self->interpBreak.ctl.dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002930 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07002931 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
2932 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002933 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002934
2935 unlockThreadSuspendCount();
2936
Andy McFadden6dce9962010-08-23 16:45:24 -07002937 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002938}
2939
2940/*
Andy McFadden6dce9962010-08-23 16:45:24 -07002941 * Check to see if a suspend is pending. If so, suspend the current
2942 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002943 */
2944bool dvmCheckSuspendPending(Thread* self)
2945{
Andy McFadden6dce9962010-08-23 16:45:24 -07002946 assert(self != NULL);
buzbee9a3147c2011-03-02 15:43:48 -08002947 if (self->interpBreak.ctl.suspendCount == 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07002948 return false;
2949 } else {
2950 return fullSuspendCheck(self);
2951 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002952}
2953
2954/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002955 * Update our status.
2956 *
2957 * The "self" argument, which may be NULL, is accepted as an optimization.
2958 *
2959 * Returns the old status.
2960 */
2961ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
2962{
2963 ThreadStatus oldStatus;
2964
2965 if (self == NULL)
2966 self = dvmThreadSelf();
2967
2968 LOGVV("threadid=%d: (status %d -> %d)\n",
2969 self->threadId, self->status, newStatus);
2970
2971 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07002972 if (oldStatus == newStatus)
2973 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002974
2975 if (newStatus == THREAD_RUNNING) {
2976 /*
2977 * Change our status to THREAD_RUNNING. The transition requires
2978 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002979 * us to be "asleep" in all other states, and another thread could
2980 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002981 *
Andy McFadden6dce9962010-08-23 16:45:24 -07002982 * The order of operations is very significant here. One way to
2983 * do this wrong is:
2984 *
2985 * GCing thread Our thread (in NATIVE)
2986 * ------------ ----------------------
2987 * check suspend count (== 0)
2988 * dvmSuspendAllThreads()
2989 * grab suspend-count lock
2990 * increment all suspend counts
2991 * release suspend-count lock
2992 * check thread state (== NATIVE)
2993 * all are suspended, begin GC
2994 * set state to RUNNING
2995 * (continue executing)
2996 *
2997 * We can correct this by grabbing the suspend-count lock and
2998 * performing both of our operations (check suspend count, set
2999 * state) while holding it, now we need to grab a mutex on every
3000 * transition to RUNNING.
3001 *
3002 * What we do instead is change the order of operations so that
3003 * the transition to RUNNING happens first. If we then detect
3004 * that the suspend count is nonzero, we switch to SUSPENDED.
3005 *
3006 * Appropriate compiler and memory barriers are required to ensure
3007 * that the operations are observed in the expected order.
3008 *
3009 * This does create a small window of opportunity where a GC in
3010 * progress could observe what appears to be a running thread (if
3011 * it happens to look between when we set to RUNNING and when we
3012 * switch to SUSPENDED). At worst this only affects assertions
3013 * and thread logging. (We could work around it with some sort
3014 * of intermediate "pre-running" state that is generally treated
3015 * as equivalent to running, but that doesn't seem worthwhile.)
3016 *
3017 * We can also solve this by combining the "status" and "suspend
3018 * count" fields into a single 32-bit value. This trades the
3019 * store/load barrier on transition to RUNNING for an atomic RMW
3020 * op on all transitions and all suspend count updates (also, all
3021 * accesses to status or the thread count require bit-fiddling).
3022 * It also eliminates the brief transition through RUNNING when
3023 * the thread is supposed to be suspended. This is possibly faster
3024 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003025 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003026 android_atomic_acquire_store(newStatus, &self->status);
buzbee9a3147c2011-03-02 15:43:48 -08003027 if (self->interpBreak.ctl.suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003028 fullSuspendCheck(self);
3029 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003030 } else {
3031 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003032 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003033 *
3034 * We use a releasing store to ensure that, if we were RUNNING,
3035 * any updates we previously made to objects on the managed heap
3036 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003037 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003038 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003039 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003040 }
3041
3042 return oldStatus;
3043}
3044
3045/*
3046 * Get a statically defined thread group from a field in the ThreadGroup
3047 * Class object. Expected arguments are "mMain" and "mSystem".
3048 */
3049static Object* getStaticThreadGroup(const char* fieldName)
3050{
3051 StaticField* groupField;
3052 Object* groupObj;
3053
3054 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3055 fieldName, "Ljava/lang/ThreadGroup;");
3056 if (groupField == NULL) {
3057 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
Dan Bornstein70b00ab2011-02-23 14:11:27 -08003058 dvmThrowInternalError("bad definition for ThreadGroup");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003059 return NULL;
3060 }
3061 groupObj = dvmGetStaticFieldObject(groupField);
3062 if (groupObj == NULL) {
3063 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08003064 dvmThrowInternalError(NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003065 return NULL;
3066 }
3067
3068 return groupObj;
3069}
3070Object* dvmGetSystemThreadGroup(void)
3071{
3072 return getStaticThreadGroup("mSystem");
3073}
3074Object* dvmGetMainThreadGroup(void)
3075{
3076 return getStaticThreadGroup("mMain");
3077}
3078
3079/*
3080 * Given a VMThread object, return the associated Thread*.
3081 *
3082 * NOTE: if the thread detaches, the struct Thread will disappear, and
3083 * we will be touching invalid data. For safety, lock the thread list
3084 * before calling this.
3085 */
3086Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3087{
3088 int vmData;
3089
3090 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003091
3092 if (false) {
3093 Thread* thread = gDvm.threadList;
3094 while (thread != NULL) {
3095 if ((Thread*)vmData == thread)
3096 break;
3097
3098 thread = thread->next;
3099 }
3100
3101 if (thread == NULL) {
3102 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3103 vmThreadObj, (Thread*)vmData);
3104 vmData = 0;
3105 }
3106 }
3107
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003108 return (Thread*) vmData;
3109}
3110
Andy McFadden2b94b302010-03-09 16:38:36 -08003111/*
3112 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003113 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003114 *
3115 * Returns NULL if the thread was not found.
3116 */
3117Thread* dvmGetThreadByHandle(pthread_t handle)
3118{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003119 Thread* thread;
3120 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003121 if (thread->handle == handle)
3122 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003123 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003124 return thread;
3125}
Andy McFadden2b94b302010-03-09 16:38:36 -08003126
Andy McFadden0a24ef92010-03-12 13:39:59 -08003127/*
3128 * Given a threadId, return the associated Thread*.
3129 * Caller must hold the thread list lock.
3130 *
3131 * Returns NULL if the thread was not found.
3132 */
3133Thread* dvmGetThreadByThreadId(u4 threadId)
3134{
3135 Thread* thread;
3136 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3137 if (thread->threadId == threadId)
3138 break;
3139 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003140 return thread;
3141}
3142
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003143
3144/*
3145 * Conversion map for "nice" values.
3146 *
3147 * We use Android thread priority constants to be consistent with the rest
3148 * of the system. In some cases adjacent entries may overlap.
3149 */
3150static const int kNiceValues[10] = {
3151 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3152 ANDROID_PRIORITY_BACKGROUND + 6,
3153 ANDROID_PRIORITY_BACKGROUND + 3,
3154 ANDROID_PRIORITY_BACKGROUND,
3155 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3156 ANDROID_PRIORITY_NORMAL - 2,
3157 ANDROID_PRIORITY_NORMAL - 4,
3158 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3159 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3160 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3161};
3162
3163/*
3164 * Change the priority of a system thread to match that of the Thread object.
3165 *
3166 * We map a priority value from 1-10 to Linux "nice" values, where lower
3167 * numbers indicate higher priority.
3168 */
3169void dvmChangeThreadPriority(Thread* thread, int newPriority)
3170{
3171 pid_t pid = thread->systemTid;
3172 int newNice;
3173
3174 if (newPriority < 1 || newPriority > 10) {
3175 LOGW("bad priority %d\n", newPriority);
3176 newPriority = 5;
3177 }
3178 newNice = kNiceValues[newPriority-1];
3179
Andy McFaddend62c0b52009-08-04 15:02:12 -07003180 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003181 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003182 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003183 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003184 }
3185
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003186 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3187 char* str = dvmGetThreadName(thread);
3188 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3189 pid, str, newPriority, newNice, strerror(errno));
3190 free(str);
3191 } else {
3192 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3193 pid, newPriority, newNice);
3194 }
3195}
3196
3197/*
3198 * Get the thread priority for the current thread by querying the system.
3199 * This is useful when attaching a thread through JNI.
3200 *
3201 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3202 */
3203static int getThreadPriorityFromSystem(void)
3204{
3205 int i, sysprio, jprio;
3206
3207 errno = 0;
3208 sysprio = getpriority(PRIO_PROCESS, 0);
3209 if (sysprio == -1 && errno != 0) {
3210 LOGW("getpriority() failed: %s\n", strerror(errno));
3211 return THREAD_NORM_PRIORITY;
3212 }
3213
3214 jprio = THREAD_MIN_PRIORITY;
3215 for (i = 0; i < NELEM(kNiceValues); i++) {
3216 if (sysprio >= kNiceValues[i])
3217 break;
3218 jprio++;
3219 }
3220 if (jprio > THREAD_MAX_PRIORITY)
3221 jprio = THREAD_MAX_PRIORITY;
3222
3223 return jprio;
3224}
3225
3226
3227/*
3228 * Return true if the thread is on gDvm.threadList.
3229 * Caller should not hold gDvm.threadListLock.
3230 */
3231bool dvmIsOnThreadList(const Thread* thread)
3232{
3233 bool ret = false;
3234
3235 dvmLockThreadList(NULL);
3236 if (thread == gDvm.threadList) {
3237 ret = true;
3238 } else {
3239 ret = thread->prev != NULL || thread->next != NULL;
3240 }
3241 dvmUnlockThreadList();
3242
3243 return ret;
3244}
3245
3246/*
3247 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3248 * output target.
3249 */
3250void dvmDumpThread(Thread* thread, bool isRunning)
3251{
3252 DebugOutputTarget target;
3253
3254 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3255 dvmDumpThreadEx(&target, thread, isRunning);
3256}
3257
3258/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003259 * Try to get the scheduler group.
3260 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003261 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003262 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003263 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003264 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003265 * We return the part on the "cpu" line after the '/', which will be an
3266 * empty string for the default cgroup. If the string is longer than
3267 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003268 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003269 * On error, -1 is returned, and an error description will be stored in
3270 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003271 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003272static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003273{
3274#ifdef HAVE_ANDROID_OS
3275 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003276 char lineBuf[256];
3277 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003278
Andy McFadden7f64ede2010-03-03 15:37:10 -08003279 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003280 if ((fp = fopen(pathBuf, "r")) == NULL) {
3281 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003282 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003283 }
3284
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003285 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3286 char* subsys;
3287 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003288 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003289
Andy McFadden7f64ede2010-03-03 15:37:10 -08003290 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003291 subsys = strchr(lineBuf, ':');
3292 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003293 goto out_bad_data;
3294 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003295
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003296 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003297 /* Not the subsys we're looking for */
3298 continue;
3299 }
3300
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003301 grp = strchr(subsys, '/');
3302 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003303 goto out_bad_data;
3304 }
3305 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003306
Andy McFadden7f64ede2010-03-03 15:37:10 -08003307 len = strlen(grp);
3308 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3309
3310 if (bufLen <= len) {
3311 len = bufLen - 1;
3312 }
3313 strncpy(buf, grp, len);
3314 buf[len] = '\0';
3315 fclose(fp);
3316 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003317 }
3318
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003319 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003320 fclose(fp);
3321 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003322
3323out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003324 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003325 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003326 fclose(fp);
3327 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003328
Andy McFaddend62c0b52009-08-04 15:02:12 -07003329#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003330 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003331 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003332#endif
3333}
3334
3335/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003336 * Convert ThreadStatus to a string.
3337 */
3338const char* dvmGetThreadStatusStr(ThreadStatus status)
3339{
3340 switch (status) {
3341 case THREAD_ZOMBIE: return "ZOMBIE";
3342 case THREAD_RUNNING: return "RUNNABLE";
3343 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3344 case THREAD_MONITOR: return "MONITOR";
3345 case THREAD_WAIT: return "WAIT";
3346 case THREAD_INITIALIZING: return "INITIALIZING";
3347 case THREAD_STARTING: return "STARTING";
3348 case THREAD_NATIVE: return "NATIVE";
3349 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003350 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003351 default: return "UNKNOWN";
3352 }
3353}
3354
3355/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003356 * Print information about the specified thread.
3357 *
3358 * Works best when the thread in question is "self" or has been suspended.
3359 * When dumping a separate thread that's still running, set "isRunning" to
3360 * use a more cautious thread dump function.
3361 */
3362void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3363 bool isRunning)
3364{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003365 Object* threadObj;
3366 Object* groupObj;
3367 StringObject* nameStr;
3368 char* threadName = NULL;
3369 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003370 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003371 bool isDaemon;
3372 int priority; // java.lang.Thread priority
3373 int policy; // pthread policy
3374 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003375 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003376
Andy McFaddene3346d82010-06-02 15:37:21 -07003377 /*
3378 * Get the java.lang.Thread object. This function gets called from
3379 * some weird debug contexts, so it's possible that there's a GC in
3380 * progress on some other thread. To decrease the chances of the
3381 * thread object being moved out from under us, we add the reference
3382 * to the tracked allocation list, which pins it in place.
3383 *
3384 * If threadObj is NULL, the thread is still in the process of being
3385 * attached to the VM, and there's really nothing interesting to
3386 * say about it yet.
3387 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003388 threadObj = thread->threadObj;
3389 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003390 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003391 return;
3392 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003393 dvmAddTrackedAlloc(threadObj, NULL);
3394
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003395 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3396 gDvm.offJavaLangThread_name);
3397 threadName = dvmCreateCstrFromString(nameStr);
3398
3399 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3400 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3401
3402 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3403 LOGW("Warning: pthread_getschedparam failed\n");
3404 policy = -1;
3405 sp.sched_priority = -1;
3406 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003407 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003408 sizeof(schedulerGroupBuf)) == 0 &&
3409 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003410 strcpy(schedulerGroupBuf, "default");
3411 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003412
3413 /* a null value for group is not expected, but deal with it anyway */
3414 groupObj = (Object*) dvmGetFieldObject(threadObj,
3415 gDvm.offJavaLangThread_group);
3416 if (groupObj != NULL) {
3417 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3418 "name", "Ljava/lang/String;");
3419 if (offset < 0) {
3420 LOGW("Unable to find 'name' field in ThreadGroup\n");
3421 } else {
3422 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3423 groupName = dvmCreateCstrFromString(nameStr);
3424 }
3425 }
3426 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003427 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003428
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003429 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003430 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003431 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003432 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3433#if defined(WITH_JIT)
3434 thread->inJitCodeCache ? " JIT" : ""
3435#else
3436 ""
3437#endif
3438 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003439 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003440 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
buzbee9a3147c2011-03-02 15:43:48 -08003441 groupName, thread->interpBreak.ctl.suspendCount,
3442 thread->interpBreak.ctl.dbgSuspendCount, thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003443 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003444 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003445 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003446 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003447
Andy McFadden0a3f6982010-08-31 13:50:08 -07003448 /* get some bits from /proc/self/stat */
3449 ProcStatData procStatData;
3450 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3451 /* failed, use zeroed values */
3452 memset(&procStatData, 0, sizeof(procStatData));
3453 }
3454
3455 /* grab the scheduler stats for this thread */
3456 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3457 thread->systemTid);
3458 int schedstatFd = open(schedstatBuf, O_RDONLY);
3459 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003460 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003461 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003462 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3463 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003464 if (bytes >= 1) {
3465 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003466 }
3467 }
3468
Andy McFadden0a3f6982010-08-31 13:50:08 -07003469 /* show what we got */
3470 dvmPrintDebugMessage(target,
3471 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3472 schedstatBuf, procStatData.utime, procStatData.stime,
3473 procStatData.processor);
3474
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003475 if (isRunning)
3476 dvmDumpRunningThreadStack(target, thread);
3477 else
3478 dvmDumpThreadStack(target, thread);
3479
Andy McFaddene3346d82010-06-02 15:37:21 -07003480 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003481 free(threadName);
3482 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003483}
3484
3485/*
3486 * Get the name of a thread.
3487 *
3488 * For correctness, the caller should hold the thread list lock to ensure
3489 * that the thread doesn't go away mid-call.
3490 *
3491 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3492 */
3493char* dvmGetThreadName(Thread* thread)
3494{
3495 StringObject* nameObj;
3496
3497 if (thread->threadObj == NULL) {
3498 LOGW("threadObj is NULL, name not available\n");
3499 return strdup("-unknown-");
3500 }
3501
3502 nameObj = (StringObject*)
3503 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3504 return dvmCreateCstrFromString(nameObj);
3505}
3506
3507/*
3508 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3509 * an output target.
3510 */
3511void dvmDumpAllThreads(bool grabLock)
3512{
3513 DebugOutputTarget target;
3514
3515 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3516 dvmDumpAllThreadsEx(&target, grabLock);
3517}
3518
3519/*
3520 * Print information about all known threads. Assumes they have been
3521 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3522 *
3523 * If "grabLock" is true, we grab the thread lock list. This is important
3524 * to do unless the caller already holds the lock.
3525 */
3526void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3527{
3528 Thread* thread;
3529
3530 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3531
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003532#ifdef HAVE_ANDROID_OS
3533 dvmPrintDebugMessage(target,
3534 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3535 gDvm.threadListLock.value,
3536 gDvm._threadSuspendLock.value,
3537 gDvm.threadSuspendCountLock.value,
3538 gDvm.gcHeapLock.value,
3539 gDvm.heapWorkerLock.value,
3540 gDvm.heapWorkerListLock.value);
3541#endif
3542
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003543 if (grabLock)
3544 dvmLockThreadList(dvmThreadSelf());
3545
3546 thread = gDvm.threadList;
3547 while (thread != NULL) {
3548 dvmDumpThreadEx(target, thread, false);
3549
3550 /* verify link */
3551 assert(thread->next == NULL || thread->next->prev == thread);
3552
3553 thread = thread->next;
3554 }
3555
3556 if (grabLock)
3557 dvmUnlockThreadList();
3558}
3559
Andy McFadden384ef6b2010-03-15 17:24:55 -07003560/*
3561 * Nuke the target thread from orbit.
3562 *
3563 * The idea is to send a "crash" signal to the target thread so that
3564 * debuggerd will take notice and dump an appropriate stack trace.
3565 * Because of the way debuggerd works, we have to throw the same signal
3566 * at it twice.
3567 *
3568 * This does not necessarily cause the entire process to stop, but once a
3569 * thread has been nuked the rest of the system is likely to be unstable.
3570 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003571 * performed, but it's advisable (and expected) to call dvmAbort soon.
3572 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003573 */
3574void dvmNukeThread(Thread* thread)
3575{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003576 int killResult;
3577
Andy McFaddena388a162010-03-18 16:27:14 -07003578 /* suppress the heapworker watchdog to assist anyone using a debugger */
3579 gDvm.nativeDebuggerActive = true;
3580
Andy McFadden384ef6b2010-03-15 17:24:55 -07003581 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003582 * Send the signals, separated by a brief interval to allow debuggerd
3583 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3584 * can be used instead of SIGSEGV to avoid making it look like the
3585 * code actually crashed at the current point of execution.
3586 *
3587 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3588 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3589 * you don't get the second stack trace; possibly something in the
3590 * kernel decides that a signal has already been sent and it's time
3591 * to just kill the process. The position in the current thread is
3592 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003593 *
Andy McFaddena388a162010-03-18 16:27:14 -07003594 * The target thread can continue to execute between the two signals.
3595 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003596 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003597 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3598 " cause debuggerd dump\n",
3599 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003600 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3601 if (killResult != 0) {
3602 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3603 }
Andy McFaddena388a162010-03-18 16:27:14 -07003604 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003605 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3606 if (killResult != 0) {
3607 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3608 }
Andy McFadden7122d862010-03-19 15:18:57 -07003609 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003610 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003611
3612 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3613 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003614 LOGD("Continuing\n");
3615}