blob: a003481246a7a242a4fd453f9632c720f22bfb89 [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
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800947 return true;
948}
949
950/*
951 * Remove a thread from the internal list.
952 * Clear out the links to make it obvious that the thread is
953 * no longer on the list. Caller must hold gDvm.threadListLock.
954 */
955static void unlinkThread(Thread* thread)
956{
957 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
958 if (thread == gDvm.threadList) {
959 assert(thread->prev == NULL);
960 gDvm.threadList = thread->next;
961 } else {
962 assert(thread->prev != NULL);
963 thread->prev->next = thread->next;
964 }
965 if (thread->next != NULL)
966 thread->next->prev = thread->prev;
967 thread->prev = thread->next = NULL;
968}
969
970/*
971 * Free a Thread struct, and all the stuff allocated within.
972 */
973static void freeThread(Thread* thread)
974{
975 if (thread == NULL)
976 return;
977
978 /* thread->threadId is zero at this point */
979 LOGVV("threadid=%d: freeing\n", thread->threadId);
980
981 if (thread->interpStackStart != NULL) {
982 u1* interpStackBottom;
983
984 interpStackBottom = thread->interpStackStart;
985 interpStackBottom -= thread->interpStackSize;
986#ifdef MALLOC_INTERP_STACK
987 free(interpStackBottom);
988#else
989 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
990 LOGW("munmap(thread stack) failed\n");
991#endif
992 }
993
Andy McFaddend5ab7262009-08-25 07:19:34 -0700994 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800995 dvmClearReferenceTable(&thread->internalLocalRefTable);
996 if (&thread->jniMonitorRefTable.table != NULL)
997 dvmClearReferenceTable(&thread->jniMonitorRefTable);
998
Jeff Hao97319a82009-08-12 16:57:15 -0700999#if defined(WITH_SELF_VERIFICATION)
1000 dvmSelfVerificationShadowSpaceFree(thread);
1001#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001002 free(thread);
1003}
1004
1005/*
1006 * Like pthread_self(), but on a Thread*.
1007 */
1008Thread* dvmThreadSelf(void)
1009{
1010 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1011}
1012
1013/*
1014 * Explore our sense of self. Stuffs the thread pointer into TLS.
1015 */
1016static void setThreadSelf(Thread* thread)
1017{
1018 int cc;
1019
1020 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1021 if (cc != 0) {
1022 /*
1023 * Sometimes this fails under Bionic with EINVAL during shutdown.
1024 * This can happen if the timing is just right, e.g. a thread
1025 * fails to attach during shutdown, but the "fail" path calls
1026 * here to ensure we clean up after ourselves.
1027 */
1028 if (thread != NULL) {
1029 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1030 dvmAbort(); /* the world is fundamentally hosed */
1031 }
1032 }
1033}
1034
1035/*
1036 * This is associated with the pthreadKeySelf key. It's called by the
1037 * pthread library when a thread is exiting and the "self" pointer in TLS
1038 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001039 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001040 *
1041 * This is mainly of use to ensure that we don't leak resources if, for
1042 * example, a thread attaches itself to us with AttachCurrentThread and
1043 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001044 *
1045 * We could do the detach here instead of aborting, but this will lead to
1046 * portability problems. Other implementations do not do this check and
1047 * will simply be unaware that the thread has exited, leading to resource
1048 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1049 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001050 *
1051 * Because some implementations may want to use the pthread destructor
1052 * to initiate the detach, and the ordering of destructors is not defined,
1053 * 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 -08001054 */
1055static void threadExitCheck(void* arg)
1056{
Andy McFadden909ce242009-12-10 16:38:30 -08001057 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001058
Andy McFadden909ce242009-12-10 16:38:30 -08001059 Thread* self = (Thread*) arg;
1060 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001061
Andy McFadden909ce242009-12-10 16:38:30 -08001062 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1063 self->threadId, arg, self->threadExitCheckCount);
1064
1065 if (self->status == THREAD_ZOMBIE) {
1066 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1067 self->threadId);
1068 return;
1069 }
1070
1071 if (self->threadExitCheckCount < kMaxCount) {
1072 /*
1073 * Spin a couple of times to let other destructors fire.
1074 */
1075 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1076 self->threadId, self->threadExitCheckCount);
1077 self->threadExitCheckCount++;
1078 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1079 if (cc != 0) {
1080 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1081 self->threadId);
1082 dvmAbort();
1083 }
1084 } else {
1085 LOGE("threadid=%d: native thread exited without detaching\n",
1086 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001087 dvmAbort();
1088 }
1089}
1090
1091
1092/*
1093 * Assign the threadId. This needs to be a small integer so that our
1094 * "thin" locks fit in a small number of bits.
1095 *
1096 * We reserve zero for use as an invalid ID.
1097 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001098 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001099 */
1100static void assignThreadId(Thread* thread)
1101{
Carl Shapiro59a93122010-01-26 17:12:51 -08001102 /*
1103 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001104 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1105 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001106 */
1107 int num = dvmAllocBit(gDvm.threadIdMap);
1108 if (num < 0) {
1109 LOGE("Ran out of thread IDs\n");
1110 dvmAbort(); // TODO: make this a non-fatal error result
1111 }
1112
Carl Shapiro59a93122010-01-26 17:12:51 -08001113 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001114
1115 assert(thread->threadId != 0);
1116 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1117}
1118
1119/*
1120 * Give back the thread ID.
1121 */
1122static void releaseThreadId(Thread* thread)
1123{
1124 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001125 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001126 thread->threadId = 0;
1127}
1128
1129
1130/*
1131 * Add a stack frame that makes it look like the native code in the main
1132 * thread was originally invoked from interpreted code. This gives us a
1133 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1134 * VM begins by executing "main" in a class, so in a way this brings us
1135 * closer to the spec.
1136 */
1137static bool createFakeEntryFrame(Thread* thread)
1138{
1139 assert(thread->threadId == kMainThreadId); // main thread only
1140
1141 /* find the method on first use */
1142 if (gDvm.methFakeNativeEntry == NULL) {
1143 ClassObject* nativeStart;
1144 Method* mainMeth;
1145
1146 nativeStart = dvmFindSystemClassNoInit(
1147 "Ldalvik/system/NativeStart;");
1148 if (nativeStart == NULL) {
1149 LOGE("Unable to find dalvik.system.NativeStart class\n");
1150 return false;
1151 }
1152
1153 /*
1154 * Because we are creating a frame that represents application code, we
1155 * want to stuff the application class loader into the method's class
1156 * loader field, even though we're using the system class loader to
1157 * load it. This makes life easier over in JNI FindClass (though it
1158 * could bite us in other ways).
1159 *
1160 * Unfortunately this is occurring too early in the initialization,
1161 * of necessity coming before JNI is initialized, and we're not quite
1162 * ready to set up the application class loader.
1163 *
1164 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1165 * and check it in FindClass. The method is private so nobody else
1166 * can call it.
1167 */
1168 //nativeStart->classLoader = dvmGetSystemClassLoader();
1169
1170 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1171 "main", "([Ljava/lang/String;)V");
1172 if (mainMeth == NULL) {
1173 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1174 return false;
1175 }
1176
1177 gDvm.methFakeNativeEntry = mainMeth;
1178 }
1179
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001180 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1181 return false;
1182
1183 /*
1184 * Null out the "String[] args" argument.
1185 */
1186 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1187 u4* framePtr = (u4*) thread->curFrame;
1188 framePtr[0] = 0;
1189
1190 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001191}
1192
1193
1194/*
1195 * Add a stack frame that makes it look like the native thread has been
1196 * executing interpreted code. This gives us a place to hang JNI local
1197 * references.
1198 */
1199static bool createFakeRunFrame(Thread* thread)
1200{
1201 ClassObject* nativeStart;
1202 Method* runMeth;
1203
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001204 /*
1205 * TODO: cache this result so we don't have to dig for it every time
1206 * somebody attaches a thread to the VM. Also consider changing this
1207 * to a static method so we don't have a null "this" pointer in the
1208 * "ins" on the stack. (Does it really need to look like a Runnable?)
1209 */
1210 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001211 if (nativeStart == NULL) {
1212 LOGE("Unable to find dalvik.system.NativeStart class\n");
1213 return false;
1214 }
1215
1216 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1217 if (runMeth == NULL) {
1218 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1219 return false;
1220 }
1221
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001222 if (!dvmPushJNIFrame(thread, runMeth))
1223 return false;
1224
1225 /*
1226 * Provide a NULL 'this' argument. The method we've put at the top of
1227 * the stack looks like a virtual call to run() in a Runnable class.
1228 * (If we declared the method static, it wouldn't take any arguments
1229 * and we wouldn't have to do this.)
1230 */
1231 assert(runMeth->registersSize == 1);
1232 u4* framePtr = (u4*) thread->curFrame;
1233 framePtr[0] = 0;
1234
1235 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001236}
1237
1238/*
1239 * Helper function to set the name of the current thread
1240 */
1241static void setThreadName(const char *threadName)
1242{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001243 int hasAt = 0;
1244 int hasDot = 0;
1245 const char *s = threadName;
1246 while (*s) {
1247 if (*s == '.') hasDot = 1;
1248 else if (*s == '@') hasAt = 1;
1249 s++;
1250 }
1251 int len = s - threadName;
1252 if (len < 15 || hasAt || !hasDot) {
1253 s = threadName;
1254 } else {
1255 s = threadName + len - 15;
1256 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001257#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001258 /* pthread_setname_np fails rather than truncating long strings */
1259 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1260 strncpy(buf, s, sizeof(buf)-1);
1261 buf[sizeof(buf)-1] = '\0';
1262 int err = pthread_setname_np(pthread_self(), buf);
1263 if (err != 0) {
1264 LOGW("Unable to set the name of current thread to '%s': %s\n",
1265 buf, strerror(err));
1266 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001267#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001268 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001269#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001270 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001271#endif
1272}
1273
1274/*
1275 * Create a thread as a result of java.lang.Thread.start().
1276 *
1277 * We do have to worry about some concurrency problems, e.g. programs
1278 * that try to call Thread.start() on the same object from multiple threads.
1279 * (This will fail for all but one, but we have to make sure that it succeeds
1280 * for exactly one.)
1281 *
1282 * Some of the complexity here arises from our desire to mimic the
1283 * Thread vs. VMThread class decomposition we inherited. We've been given
1284 * a Thread, and now we need to create a VMThread and then populate both
1285 * objects. We also need to create one of our internal Thread objects.
1286 *
1287 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001288 *
1289 * The "threadObj" reference must be pinned by the caller to prevent the GC
1290 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001291 */
1292bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1293{
1294 pthread_attr_t threadAttr;
1295 pthread_t threadHandle;
1296 Thread* self;
1297 Thread* newThread = NULL;
1298 Object* vmThreadObj = NULL;
1299 int stackSize;
1300
1301 assert(threadObj != NULL);
1302
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001303 self = dvmThreadSelf();
1304 if (reqStackSize == 0)
1305 stackSize = gDvm.stackSize;
1306 else if (reqStackSize < kMinStackSize)
1307 stackSize = kMinStackSize;
1308 else if (reqStackSize > kMaxStackSize)
1309 stackSize = kMaxStackSize;
1310 else
1311 stackSize = reqStackSize;
1312
1313 pthread_attr_init(&threadAttr);
1314 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1315
1316 /*
1317 * To minimize the time spent in the critical section, we allocate the
1318 * vmThread object here.
1319 */
1320 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1321 if (vmThreadObj == NULL)
1322 goto fail;
1323
1324 newThread = allocThread(stackSize);
1325 if (newThread == NULL)
1326 goto fail;
1327 newThread->threadObj = threadObj;
1328
1329 assert(newThread->status == THREAD_INITIALIZING);
1330
1331 /*
1332 * We need to lock out other threads while we test and set the
1333 * "vmThread" field in java.lang.Thread, because we use that to determine
1334 * if this thread has been started before. We use the thread list lock
1335 * because it's handy and we're going to need to grab it again soon
1336 * anyway.
1337 */
1338 dvmLockThreadList(self);
1339
1340 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1341 dvmUnlockThreadList();
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001342 dvmThrowIllegalThreadStateException(
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001343 "thread has already been started");
1344 goto fail;
1345 }
1346
1347 /*
1348 * There are actually three data structures: Thread (object), VMThread
1349 * (object), and Thread (C struct). All of them point to at least one
1350 * other.
1351 *
1352 * As soon as "VMThread.vmData" is assigned, other threads can start
1353 * making calls into us (e.g. setPriority).
1354 */
1355 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1356 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1357
1358 /*
1359 * Thread creation might take a while, so release the lock.
1360 */
1361 dvmUnlockThreadList();
1362
Carl Shapiro5617ad32010-07-02 10:50:57 -07001363 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1364 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001365 newThread);
1366 oldStatus = dvmChangeStatus(self, oldStatus);
1367
1368 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001369 /*
1370 * Failure generally indicates that we have exceeded system
1371 * resource limits. VirtualMachineError is probably too severe,
1372 * so use OutOfMemoryError.
1373 */
1374 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1375
1376 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1377
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001378 dvmThrowOutOfMemoryError("thread creation failed");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001379 goto fail;
1380 }
1381
1382 /*
1383 * We need to wait for the thread to start. Otherwise, depending on
1384 * the whims of the OS scheduler, we could return and the code in our
1385 * thread could try to do operations on the new thread before it had
1386 * finished starting.
1387 *
1388 * The new thread will lock the thread list, change its state to
1389 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1390 * on gDvm.threadStartCond (which uses the thread list lock). This
1391 * thread (the parent) will either see that the thread is already ready
1392 * after we grab the thread list lock, or will be awakened from the
1393 * condition variable on the broadcast.
1394 *
1395 * We don't want to stall the rest of the VM while the new thread
1396 * starts, which can happen if the GC wakes up at the wrong moment.
1397 * So, we change our own status to VMWAIT, and self-suspend if
1398 * necessary after we finish adding the new thread.
1399 *
1400 *
1401 * We have to deal with an odd race with the GC/debugger suspension
1402 * mechanism when creating a new thread. The information about whether
1403 * or not a thread should be suspended is contained entirely within
1404 * the Thread struct; this is usually cleaner to deal with than having
1405 * one or more globally-visible suspension flags. The trouble is that
1406 * we could create the thread while the VM is trying to suspend all
1407 * threads. The suspend-count won't be nonzero for the new thread,
1408 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1409 *
1410 * The easiest way to deal with this is to prevent the new thread from
1411 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001412 * following (correct) sequence of events for a "badly timed" GC
1413 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001414 *
1415 * - call pthread_create()
1416 * - lock thread list
1417 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1418 * - sleep on condition var (mutex = thread list lock) until child starts
1419 * + GC triggered by another thread
1420 * + thread list locked; suspend counts updated; thread list unlocked
1421 * + loop waiting for all runnable threads to suspend
1422 * + success, start GC
1423 * o child thread wakes, signals condition var to wake parent
1424 * o child waits for parent ack on condition variable
1425 * - we wake up, locking thread list
1426 * - add child to thread list
1427 * - unlock thread list
1428 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1429 * + GC finishes; all threads in thread list are resumed
1430 * - lock thread list
1431 * - set child to THREAD_VMWAIT, and signal it to start
1432 * - unlock thread list
1433 * o child resumes
1434 * o child changes state to THREAD_RUNNING
1435 *
1436 * The above shows the GC starting up during thread creation, but if
1437 * it starts anywhere after VMThread.create() is called it will
1438 * produce the same series of events.
1439 *
1440 * Once the child is in the thread list, it will be suspended and
1441 * resumed like any other thread. In the above scenario the resume-all
1442 * code will try to resume the new thread, which was never actually
1443 * suspended, and try to decrement the child's thread suspend count to -1.
1444 * We can catch this in the resume-all code.
1445 *
1446 * Bouncing back and forth between threads like this adds a small amount
1447 * of scheduler overhead to thread startup.
1448 *
1449 * One alternative to having the child wait for the parent would be
1450 * to have the child inherit the parents' suspension count. This
1451 * would work for a GC, since we can safely assume that the parent
1452 * thread didn't cause it, but we must only do so if the parent suspension
1453 * was caused by a suspend-all. If the parent was being asked to
1454 * suspend singly by the debugger, the child should not inherit the value.
1455 *
1456 * We could also have a global "new thread suspend count" that gets
1457 * picked up by new threads before changing state to THREAD_RUNNING.
1458 * This would be protected by the thread list lock and set by a
1459 * suspend-all.
1460 */
1461 dvmLockThreadList(self);
1462 assert(self->status == THREAD_RUNNING);
1463 self->status = THREAD_VMWAIT;
1464 while (newThread->status != THREAD_STARTING)
1465 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1466
1467 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1468 newThread->next = gDvm.threadList->next;
1469 if (newThread->next != NULL)
1470 newThread->next->prev = newThread;
1471 newThread->prev = gDvm.threadList;
1472 gDvm.threadList->next = newThread;
1473
1474 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1475 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1476
1477 dvmUnlockThreadList();
1478
1479 /* change status back to RUNNING, self-suspending if necessary */
1480 dvmChangeStatus(self, THREAD_RUNNING);
1481
1482 /*
1483 * Tell the new thread to start.
1484 *
1485 * We must hold the thread list lock before messing with another thread.
1486 * In the general case we would also need to verify that newThread was
1487 * still in the thread list, but in our case the thread has not started
1488 * executing user code and therefore has not had a chance to exit.
1489 *
1490 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1491 * comes with a suspend-pending check.
1492 */
1493 dvmLockThreadList(self);
1494
1495 assert(newThread->status == THREAD_STARTING);
1496 newThread->status = THREAD_VMWAIT;
1497 pthread_cond_broadcast(&gDvm.threadStartCond);
1498
1499 dvmUnlockThreadList();
1500
1501 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1502 return true;
1503
1504fail:
1505 freeThread(newThread);
1506 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1507 return false;
1508}
1509
1510/*
1511 * pthread entry function for threads started from interpreted code.
1512 */
1513static void* interpThreadStart(void* arg)
1514{
1515 Thread* self = (Thread*) arg;
1516
1517 char *threadName = dvmGetThreadName(self);
1518 setThreadName(threadName);
1519 free(threadName);
1520
1521 /*
1522 * Finish initializing the Thread struct.
1523 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001524 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001525 prepareThread(self);
1526
1527 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1528
1529 /*
1530 * Change our status and wake our parent, who will add us to the
1531 * thread list and advance our state to VMWAIT.
1532 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001533 self->status = THREAD_STARTING;
1534 pthread_cond_broadcast(&gDvm.threadStartCond);
1535
1536 /*
1537 * Wait until the parent says we can go. Assuming there wasn't a
1538 * suspend pending, this will happen immediately. When it completes,
1539 * we're full-fledged citizens of the VM.
1540 *
1541 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1542 * because the pthread_cond_wait below needs to reacquire a lock that
1543 * suspend-all is also interested in. If we get unlucky, the parent could
1544 * change us to THREAD_RUNNING, then a GC could start before we get
1545 * signaled, and suspend-all will grab the thread list lock and then
1546 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1547 * trying to get the lock.
1548 */
1549 while (self->status != THREAD_VMWAIT)
1550 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1551
1552 dvmUnlockThreadList();
1553
1554 /*
1555 * Add a JNI context.
1556 */
1557 self->jniEnv = dvmCreateJNIEnv(self);
1558
1559 /*
1560 * Change our state so the GC will wait for us from now on. If a GC is
1561 * in progress this call will suspend us.
1562 */
1563 dvmChangeStatus(self, THREAD_RUNNING);
1564
1565 /*
1566 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001567 * us to suspend ourselves (and others). The thread state may change
1568 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001569 */
1570 if (gDvm.debuggerConnected)
1571 dvmDbgPostThreadStart(self);
1572
1573 /*
1574 * Set the system thread priority according to the Thread object's
1575 * priority level. We don't usually need to do this, because both the
1576 * Thread object and system thread priorities inherit from parents. The
1577 * tricky case is when somebody creates a Thread object, calls
1578 * setPriority(), and then starts the thread. We could manage this with
1579 * a "needs priority update" flag to avoid the redundant call.
1580 */
Andy McFadden4879df92009-08-07 14:49:40 -07001581 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001582 gDvm.offJavaLangThread_priority);
1583 dvmChangeThreadPriority(self, priority);
1584
1585 /*
1586 * Execute the "run" method.
1587 *
1588 * At this point our stack is empty, so somebody who comes looking for
1589 * stack traces right now won't have much to look at. This is normal.
1590 */
1591 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1592 JValue unused;
1593
1594 LOGV("threadid=%d: calling run()\n", self->threadId);
1595 assert(strcmp(run->name, "run") == 0);
1596 dvmCallMethod(self, run, self->threadObj, &unused);
1597 LOGV("threadid=%d: exiting\n", self->threadId);
1598
1599 /*
1600 * Remove the thread from various lists, report its death, and free
1601 * its resources.
1602 */
1603 dvmDetachCurrentThread();
1604
1605 return NULL;
1606}
1607
1608/*
1609 * The current thread is exiting with an uncaught exception. The
1610 * Java programming language allows the application to provide a
1611 * thread-exit-uncaught-exception handler for the VM, for a specific
1612 * Thread, and for all threads in a ThreadGroup.
1613 *
1614 * Version 1.5 added the per-thread handler. We need to call
1615 * "uncaughtException" in the handler object, which is either the
1616 * ThreadGroup object or the Thread-specific handler.
1617 */
1618static void threadExitUncaughtException(Thread* self, Object* group)
1619{
1620 Object* exception;
1621 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001622 Method* uncaughtHandler = NULL;
1623 InstField* threadHandler;
1624
1625 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1626 self->threadId, group);
1627 assert(group != NULL);
1628
1629 /*
1630 * Get a pointer to the exception, then clear out the one in the
1631 * thread. We don't want to have it set when executing interpreted code.
1632 */
1633 exception = dvmGetException(self);
1634 dvmAddTrackedAlloc(exception, self);
1635 dvmClearException(self);
1636
1637 /*
1638 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1639 * else use "group" (which is an instance of UncaughtExceptionHandler).
1640 */
1641 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1642 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1643 if (threadHandler == NULL) {
1644 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1645 goto bail;
1646 }
1647 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1648 if (handlerObj == NULL)
1649 handlerObj = group;
1650
1651 /*
1652 * Find the "uncaughtHandler" field in this object.
1653 */
1654 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1655 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1656
1657 if (uncaughtHandler != NULL) {
1658 //LOGI("+++ calling %s.uncaughtException\n",
1659 // handlerObj->clazz->descriptor);
1660 JValue unused;
1661 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1662 self->threadObj, exception);
1663 } else {
1664 /* restore it and dump a stack trace */
1665 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1666 handlerObj->clazz->descriptor);
1667 dvmSetException(self, exception);
1668 dvmLogExceptionStackTrace();
1669 }
1670
1671bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001672 /* Remove this thread's suspendCount from global suspendCount sum */
1673 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08001674 dvmAddToSuspendCounts(self, -self->interpBreak.ctl.suspendCount, 0);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001675 unlockThreadSuspendCount();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001676 dvmReleaseTrackedAlloc(exception, self);
1677}
1678
1679
1680/*
1681 * Create an internal VM thread, for things like JDWP and finalizers.
1682 *
1683 * The easiest way to do this is create a new thread and then use the
1684 * JNI AttachCurrentThread implementation.
1685 *
1686 * This does not return until after the new thread has begun executing.
1687 */
1688bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1689 InternalThreadStart func, void* funcArg)
1690{
1691 InternalStartArgs* pArgs;
1692 Object* systemGroup;
1693 pthread_attr_t threadAttr;
1694 volatile Thread* newThread = NULL;
1695 volatile int createStatus = 0;
1696
1697 systemGroup = dvmGetSystemThreadGroup();
1698 if (systemGroup == NULL)
1699 return false;
1700
1701 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1702 pArgs->func = func;
1703 pArgs->funcArg = funcArg;
1704 pArgs->name = strdup(name); // storage will be owned by new thread
1705 pArgs->group = systemGroup;
1706 pArgs->isDaemon = true;
1707 pArgs->pThread = &newThread;
1708 pArgs->pCreateStatus = &createStatus;
1709
1710 pthread_attr_init(&threadAttr);
1711 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1712
1713 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1714 pArgs) != 0)
1715 {
1716 LOGE("internal thread creation failed\n");
1717 free(pArgs->name);
1718 free(pArgs);
1719 return false;
1720 }
1721
1722 /*
1723 * Wait for the child to start. This gives us an opportunity to make
1724 * sure that the thread started correctly, and allows our caller to
1725 * assume that the thread has started running.
1726 *
1727 * Because we aren't holding a lock across the thread creation, it's
1728 * possible that the child will already have completed its
1729 * initialization. Because the child only adjusts "createStatus" while
1730 * holding the thread list lock, the initial condition on the "while"
1731 * loop will correctly avoid the wait if this occurs.
1732 *
1733 * It's also possible that we'll have to wait for the thread to finish
1734 * being created, and as part of allocating a Thread object it might
1735 * need to initiate a GC. We switch to VMWAIT while we pause.
1736 */
1737 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001738 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001739 dvmLockThreadList(self);
1740 while (createStatus == 0)
1741 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1742
1743 if (newThread == NULL) {
1744 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1745 assert(createStatus < 0);
1746 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1747 dvmUnlockThreadList();
1748 dvmChangeStatus(self, oldStatus);
1749 return false;
1750 }
1751
1752 /* thread could be in any state now (except early init states) */
1753 //assert(newThread->status == THREAD_RUNNING);
1754
1755 dvmUnlockThreadList();
1756 dvmChangeStatus(self, oldStatus);
1757
1758 return true;
1759}
1760
1761/*
1762 * pthread entry function for internally-created threads.
1763 *
1764 * We are expected to free "arg" and its contents. If we're a daemon
1765 * thread, and we get cancelled abruptly when the VM shuts down, the
1766 * storage won't be freed. If this becomes a concern we can make a copy
1767 * on the stack.
1768 */
1769static void* internalThreadStart(void* arg)
1770{
1771 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1772 JavaVMAttachArgs jniArgs;
1773
1774 jniArgs.version = JNI_VERSION_1_2;
1775 jniArgs.name = pArgs->name;
1776 jniArgs.group = pArgs->group;
1777
1778 setThreadName(pArgs->name);
1779
1780 /* use local jniArgs as stack top */
1781 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1782 /*
1783 * Tell the parent of our success.
1784 *
1785 * threadListLock is the mutex for threadStartCond.
1786 */
1787 dvmLockThreadList(dvmThreadSelf());
1788 *pArgs->pCreateStatus = 1;
1789 *pArgs->pThread = dvmThreadSelf();
1790 pthread_cond_broadcast(&gDvm.threadStartCond);
1791 dvmUnlockThreadList();
1792
1793 LOG_THREAD("threadid=%d: internal '%s'\n",
1794 dvmThreadSelf()->threadId, pArgs->name);
1795
1796 /* execute */
1797 (*pArgs->func)(pArgs->funcArg);
1798
1799 /* detach ourselves */
1800 dvmDetachCurrentThread();
1801 } else {
1802 /*
1803 * Tell the parent of our failure. We don't have a Thread struct,
1804 * so we can't be suspended, so we don't need to enter a critical
1805 * section.
1806 */
1807 dvmLockThreadList(dvmThreadSelf());
1808 *pArgs->pCreateStatus = -1;
1809 assert(*pArgs->pThread == NULL);
1810 pthread_cond_broadcast(&gDvm.threadStartCond);
1811 dvmUnlockThreadList();
1812
1813 assert(*pArgs->pThread == NULL);
1814 }
1815
1816 free(pArgs->name);
1817 free(pArgs);
1818 return NULL;
1819}
1820
1821/*
1822 * Attach the current thread to the VM.
1823 *
1824 * Used for internally-created threads and JNI's AttachCurrentThread.
1825 */
1826bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1827{
1828 Thread* self = NULL;
1829 Object* threadObj = NULL;
1830 Object* vmThreadObj = NULL;
1831 StringObject* threadNameStr = NULL;
1832 Method* init;
1833 bool ok, ret;
1834
Andy McFaddene3346d82010-06-02 15:37:21 -07001835 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001836 self = allocThread(gDvm.stackSize);
1837 if (self == NULL)
1838 goto fail;
1839 setThreadSelf(self);
1840
1841 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001842 * Finish our thread prep. We need to do this before adding ourselves
1843 * to the thread list or invoking any interpreted code. prepareThread()
1844 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001845 */
1846 dvmLockThreadList(self);
1847 ok = prepareThread(self);
1848 dvmUnlockThreadList();
1849 if (!ok)
1850 goto fail;
1851
1852 self->jniEnv = dvmCreateJNIEnv(self);
1853 if (self->jniEnv == NULL)
1854 goto fail;
1855
1856 /*
1857 * Create a "fake" JNI frame at the top of the main thread interp stack.
1858 * It isn't really necessary for the internal threads, but it gives
1859 * the debugger something to show. It is essential for the JNI-attached
1860 * threads.
1861 */
1862 if (!createFakeRunFrame(self))
1863 goto fail;
1864
1865 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001866 * The native side of the thread is ready; add it to the list. Once
1867 * 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 -08001868 */
1869 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1870
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001871 dvmLockThreadList(self);
1872
1873 self->next = gDvm.threadList->next;
1874 if (self->next != NULL)
1875 self->next->prev = self;
1876 self->prev = gDvm.threadList;
1877 gDvm.threadList->next = self;
1878 if (!isDaemon)
1879 gDvm.nonDaemonThreadCount++;
1880
1881 dvmUnlockThreadList();
1882
1883 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001884 * Switch state from initializing to running.
1885 *
1886 * It's possible that a GC began right before we added ourselves
1887 * to the thread list, and is still going. That means our thread
1888 * suspend count won't reflect the fact that we should be suspended.
1889 * To deal with this, we transition to VMWAIT, pulse the heap lock,
1890 * and then advance to RUNNING. That will ensure that we stall until
1891 * the GC completes.
1892 *
1893 * Once we're in RUNNING, we're like any other thread in the VM (except
1894 * for the lack of an initialized threadObj). We're then free to
1895 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001896 */
Andy McFaddene3346d82010-06-02 15:37:21 -07001897 assert(self->status == THREAD_INITIALIZING);
1898 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001899 dvmLockMutex(&gDvm.gcHeapLock);
1900 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07001901 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001902
1903 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001904 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001905 */
Andy McFaddene3346d82010-06-02 15:37:21 -07001906 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
1907 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1908 if (threadObj == NULL || vmThreadObj == NULL)
1909 goto fail_unlink;
1910
1911 /*
1912 * This makes threadObj visible to the GC. We still have it in the
1913 * tracked allocation table, so it can't move around on us.
1914 */
1915 self->threadObj = threadObj;
1916 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1917
1918 /*
1919 * Create a string for the thread name.
1920 */
1921 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07001922 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07001923 if (threadNameStr == NULL) {
1924 assert(dvmCheckException(dvmThreadSelf()));
1925 goto fail_unlink;
1926 }
1927 }
1928
1929 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1930 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1931 if (init == NULL) {
1932 assert(dvmCheckException(self));
1933 goto fail_unlink;
1934 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001935
1936 /*
1937 * Now we're ready to run some interpreted code.
1938 *
1939 * We need to construct the Thread object and set the VMThread field.
1940 * Setting VMThread tells interpreted code that we're alive.
1941 *
1942 * Call the (group, name, priority, daemon) constructor on the Thread.
1943 * This sets the thread's name and adds it to the specified group, and
1944 * provides values for priority and daemon (which are normally inherited
1945 * from the current thread).
1946 */
1947 JValue unused;
1948 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
1949 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
1950 if (dvmCheckException(self)) {
1951 LOGE("exception thrown while constructing attached thread object\n");
1952 goto fail_unlink;
1953 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001954
1955 /*
1956 * Set the VMThread field, which tells interpreted code that we're alive.
1957 *
1958 * The risk of a thread start collision here is very low; somebody
1959 * would have to be deliberately polling the ThreadGroup list and
1960 * trying to start threads against anything it sees, which would
1961 * generally cause problems for all thread creation. However, for
1962 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07001963 *
1964 * TODO: this still has a race, it's just smaller. Not sure this is
1965 * worth putting effort into fixing. Need to hold a lock while
1966 * fiddling with the field, or maybe initialize the Thread object in a
1967 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001968 */
1969 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07001970 LOGW("WOW: thread start hijack\n");
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08001971 dvmThrowIllegalThreadStateException(
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001972 "thread has already been started");
1973 /* We don't want to free anything associated with the thread
1974 * because someone is obviously interested in it. Just let
1975 * it go and hope it will clean itself up when its finished.
1976 * This case should never happen anyway.
1977 *
1978 * Since we're letting it live, we need to finish setting it up.
1979 * We just have to let the caller know that the intended operation
1980 * has failed.
1981 *
1982 * [ This seems strange -- stepping on the vmThread object that's
1983 * already present seems like a bad idea. TODO: figure this out. ]
1984 */
1985 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07001986 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001987 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07001988 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001989 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1990
Andy McFaddene3346d82010-06-02 15:37:21 -07001991 /* we can now safely un-pin these */
1992 dvmReleaseTrackedAlloc(threadObj, self);
1993 dvmReleaseTrackedAlloc(vmThreadObj, self);
1994 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001995
1996 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
1997 self->threadId, pArgs->name);
1998
1999 /* tell the debugger & DDM */
2000 if (gDvm.debuggerConnected)
2001 dvmDbgPostThreadStart(self);
2002
2003 return ret;
2004
2005fail_unlink:
2006 dvmLockThreadList(self);
2007 unlinkThread(self);
2008 if (!isDaemon)
2009 gDvm.nonDaemonThreadCount--;
2010 dvmUnlockThreadList();
2011 /* fall through to "fail" */
2012fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002013 dvmReleaseTrackedAlloc(threadObj, self);
2014 dvmReleaseTrackedAlloc(vmThreadObj, self);
2015 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002016 if (self != NULL) {
2017 if (self->jniEnv != NULL) {
2018 dvmDestroyJNIEnv(self->jniEnv);
2019 self->jniEnv = NULL;
2020 }
2021 freeThread(self);
2022 }
2023 setThreadSelf(NULL);
2024 return false;
2025}
2026
2027/*
2028 * Detach the thread from the various data structures, notify other threads
2029 * that are waiting to "join" it, and free up all heap-allocated storage.
2030 *
2031 * Used for all threads.
2032 *
2033 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2034 * requires us to enforce this for the DetachCurrentThread call, probably
2035 * because it also says that DetachCurrentThread causes all monitors
2036 * associated with the thread to be released. (Because the stack is empty,
2037 * we only have to worry about explicit JNI calls to MonitorEnter.)
2038 *
2039 * THOUGHT:
2040 * We might want to avoid freeing our internal Thread structure until the
2041 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2042 * get to once the thread shuts down, but there is a small possibility of
2043 * an operation starting in another thread before this thread halts, and
2044 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2045 * We don't want something like Thread.isInterrupted() crawling through
2046 * freed storage. Can do with a Thread finalizer, or by creating a
2047 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2048 * state into that.
2049 */
2050void dvmDetachCurrentThread(void)
2051{
2052 Thread* self = dvmThreadSelf();
2053 Object* vmThread;
2054 Object* group;
2055
2056 /*
2057 * Make sure we're not detaching a thread that's still running. (This
2058 * could happen with an explicit JNI detach call.)
2059 *
2060 * A thread created by interpreted code will finish with a depth of
2061 * zero, while a JNI-attached thread will have the synthetic "stack
2062 * starter" native method at the top.
2063 */
2064 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2065 if (curDepth != 0) {
2066 bool topIsNative = false;
2067
2068 if (curDepth == 1) {
2069 /* not expecting a lingering break frame; just look at curFrame */
Carl Shapirofc75f3e2010-12-07 11:43:38 -08002070 assert(!dvmIsBreakFrame((u4*)self->curFrame));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002071 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2072 if (dvmIsNativeMethod(ssa->method))
2073 topIsNative = true;
2074 }
2075
2076 if (!topIsNative) {
2077 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2078 curDepth);
2079 dvmDumpThread(self, false);
2080 dvmAbort();
2081 }
2082 }
2083
2084 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2085 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2086
2087 /*
2088 * Release any held monitors. Since there are no interpreted stack
2089 * frames, the only thing left are the monitors held by JNI MonitorEnter
2090 * calls.
2091 */
2092 dvmReleaseJniMonitors(self);
2093
2094 /*
2095 * Do some thread-exit uncaught exception processing if necessary.
2096 */
2097 if (dvmCheckException(self))
2098 threadExitUncaughtException(self, group);
2099
2100 /*
2101 * Remove the thread from the thread group.
2102 */
2103 if (group != NULL) {
2104 Method* removeThread =
2105 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2106 JValue unused;
2107 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2108 }
2109
2110 /*
2111 * Clear the vmThread reference in the Thread object. Interpreted code
2112 * will now see that this Thread is not running. As this may be the
2113 * only reference to the VMThread object that the VM knows about, we
2114 * have to create an internal reference to it first.
2115 */
2116 vmThread = dvmGetFieldObject(self->threadObj,
2117 gDvm.offJavaLangThread_vmThread);
2118 dvmAddTrackedAlloc(vmThread, self);
2119 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2120
2121 /* clear out our struct Thread pointer, since it's going away */
2122 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2123
2124 /*
2125 * Tell the debugger & DDM. This may cause the current thread or all
2126 * threads to suspend.
2127 *
2128 * The JDWP spec is somewhat vague about when this happens, other than
2129 * that it's issued by the dying thread, which may still appear in
2130 * an "all threads" listing.
2131 */
2132 if (gDvm.debuggerConnected)
2133 dvmDbgPostThreadDeath(self);
2134
2135 /*
2136 * Thread.join() is implemented as an Object.wait() on the VMThread
2137 * object. Signal anyone who is waiting.
2138 */
2139 dvmLockObject(self, vmThread);
2140 dvmObjectNotifyAll(self, vmThread);
2141 dvmUnlockObject(self, vmThread);
2142
2143 dvmReleaseTrackedAlloc(vmThread, self);
2144 vmThread = NULL;
2145
2146 /*
2147 * We're done manipulating objects, so it's okay if the GC runs in
2148 * parallel with us from here out. It's important to do this if
2149 * profiling is enabled, since we can wait indefinitely.
2150 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002151 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002152
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002153 /*
2154 * If we're doing method trace profiling, we don't want threads to exit,
2155 * because if they do we'll end up reusing thread IDs. This complicates
2156 * analysis and makes it impossible to have reasonable output in the
2157 * "threads" section of the "key" file.
2158 *
2159 * We need to do this after Thread.join() completes, or other threads
2160 * could get wedged. Since self->threadObj is still valid, the Thread
2161 * object will not get GCed even though we're no longer in the ThreadGroup
2162 * list (which is important since the profiling thread needs to get
2163 * the thread's name).
2164 */
2165 MethodTraceState* traceState = &gDvm.methodTrace;
2166
2167 dvmLockMutex(&traceState->startStopLock);
2168 if (traceState->traceEnabled) {
2169 LOGI("threadid=%d: waiting for method trace to finish\n",
2170 self->threadId);
2171 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002172 dvmWaitCond(&traceState->threadExitCond,
2173 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002174 }
2175 }
2176 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002177
2178 dvmLockThreadList(self);
2179
2180 /*
2181 * Lose the JNI context.
2182 */
2183 dvmDestroyJNIEnv(self->jniEnv);
2184 self->jniEnv = NULL;
2185
2186 self->status = THREAD_ZOMBIE;
2187
2188 /*
2189 * Remove ourselves from the internal thread list.
2190 */
2191 unlinkThread(self);
2192
2193 /*
2194 * If we're the last one standing, signal anybody waiting in
2195 * DestroyJavaVM that it's okay to exit.
2196 */
2197 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2198 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2199
2200 if (gDvm.nonDaemonThreadCount == 0) {
2201 int cc;
2202
2203 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2204 //dvmDumpAllThreads(false);
2205 // cond var guarded by threadListLock, which we already hold
2206 cc = pthread_cond_signal(&gDvm.vmExitCond);
2207 assert(cc == 0);
2208 }
2209 }
2210
2211 LOGV("threadid=%d: bye!\n", self->threadId);
2212 releaseThreadId(self);
2213 dvmUnlockThreadList();
2214
2215 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002216
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002217 freeThread(self);
2218}
2219
2220
2221/*
2222 * Suspend a single thread. Do not use to suspend yourself.
2223 *
2224 * This is used primarily for debugger/DDMS activity. Does not return
2225 * until the thread has suspended or is in a "safe" state (e.g. executing
2226 * native code outside the VM).
2227 *
2228 * The thread list lock should be held before calling here -- it's not
2229 * entirely safe to hang on to a Thread* from another thread otherwise.
2230 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2231 */
2232void dvmSuspendThread(Thread* thread)
2233{
2234 assert(thread != NULL);
2235 assert(thread != dvmThreadSelf());
2236 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2237
2238 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08002239 dvmAddToSuspendCounts(thread, 1, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002240
2241 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
buzbee9a3147c2011-03-02 15:43:48 -08002242 thread->threadId, thread->interpBreak.ctl.suspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002243 unlockThreadSuspendCount();
2244
2245 waitForThreadSuspend(dvmThreadSelf(), thread);
2246}
2247
2248/*
2249 * Reduce the suspend count of a thread. If it hits zero, tell it to
2250 * resume.
2251 *
2252 * Used primarily for debugger/DDMS activity. The thread in question
2253 * might have been suspended singly or as part of a suspend-all operation.
2254 *
2255 * The thread list lock should be held before calling here -- it's not
2256 * entirely safe to hang on to a Thread* from another thread otherwise.
2257 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2258 */
2259void dvmResumeThread(Thread* thread)
2260{
2261 assert(thread != NULL);
2262 assert(thread != dvmThreadSelf());
2263 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2264
2265 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08002266 if (thread->interpBreak.ctl.suspendCount > 0) {
2267 dvmAddToSuspendCounts(thread, -1, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002268 } else {
2269 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2270 thread->threadId);
2271 }
2272
2273 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
buzbee9a3147c2011-03-02 15:43:48 -08002274 thread->threadId, thread->interpBreak.ctl.suspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002275
buzbee9a3147c2011-03-02 15:43:48 -08002276 if (thread->interpBreak.ctl.suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002277 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002278 }
2279
2280 unlockThreadSuspendCount();
2281}
2282
2283/*
2284 * Suspend yourself, as a result of debugger activity.
2285 */
2286void dvmSuspendSelf(bool jdwpActivity)
2287{
2288 Thread* self = dvmThreadSelf();
2289
Andy McFadden6dce9962010-08-23 16:45:24 -07002290 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002291 assert(gDvm.jdwpState != NULL);
2292 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2293 assert(false);
2294 return;
2295 }
2296
2297 /*
2298 * Collisions with other suspends aren't really interesting. We want
2299 * to ensure that we're the only one fiddling with the suspend count
2300 * though.
2301 */
2302 lockThreadSuspendCount();
buzbee9a3147c2011-03-02 15:43:48 -08002303 dvmAddToSuspendCounts(self, 1, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002304
2305 /*
2306 * Suspend ourselves.
2307 */
buzbee9a3147c2011-03-02 15:43:48 -08002308 assert(self->interpBreak.ctl.suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002309 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002310 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2311
2312 /*
2313 * Tell JDWP that we've completed suspension. The JDWP thread can't
2314 * tell us to resume before we're fully asleep because we hold the
2315 * suspend count lock.
2316 *
2317 * If we got here via waitForDebugger(), don't do this part.
2318 */
2319 if (jdwpActivity) {
2320 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2321 // self->threadId, (int) self->handle);
2322 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2323 }
2324
buzbee9a3147c2011-03-02 15:43:48 -08002325 while (self->interpBreak.ctl.suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002326 dvmWaitCond(&gDvm.threadSuspendCountCond,
2327 &gDvm.threadSuspendCountLock);
buzbee9a3147c2011-03-02 15:43:48 -08002328 if (self->interpBreak.ctl.suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002329 /*
2330 * The condition was signaled but we're still suspended. This
2331 * can happen if the debugger lets go while a SIGQUIT thread
2332 * dump event is pending (assuming SignalCatcher was resumed for
2333 * just long enough to try to grab the thread-suspend lock).
2334 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002335 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
buzbee9a3147c2011-03-02 15:43:48 -08002336 self->threadId, self->interpBreak.ctl.suspendCount,
2337 self->interpBreak.ctl.dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002338 }
2339 }
buzbee9a3147c2011-03-02 15:43:48 -08002340 assert(self->interpBreak.ctl.suspendCount == 0 &&
2341 self->interpBreak.ctl.dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002342 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002343 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2344 self->threadId, self->status);
2345
2346 unlockThreadSuspendCount();
2347}
2348
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002349/*
2350 * Dump the state of the current thread and that of another thread that
2351 * we think is wedged.
2352 */
2353static void dumpWedgedThread(Thread* thread)
2354{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002355 dvmDumpThread(dvmThreadSelf(), false);
Elliott Hughesabd4f6e2011-03-25 11:58:52 -07002356 dvmPrintNativeBackTrace();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002357
2358 // dumping a running thread is risky, but could be useful
2359 dvmDumpThread(thread, true);
2360
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002361 // stop now and get a core dump
2362 //abort();
2363}
2364
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002365/*
2366 * If the thread is running at below-normal priority, temporarily elevate
2367 * it to "normal".
2368 *
2369 * Returns zero if no changes were made. Otherwise, returns bit flags
2370 * indicating what was changed, storing the previous values in the
2371 * provided locations.
2372 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002373int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002374 SchedPolicy* pSavedThreadPolicy)
2375{
2376 errno = 0;
2377 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2378 if (errno != 0) {
2379 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2380 thread->threadId, thread->systemTid);
2381 return 0;
2382 }
2383 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2384 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2385 thread->threadId, thread->systemTid);
2386 return 0;
2387 }
2388
2389 int changeFlags = 0;
2390
2391 /*
2392 * Change the priority if we're in the background group.
2393 */
2394 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2395 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2396 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2397 } else {
2398 changeFlags |= kChangedPolicy;
2399 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2400 thread->systemTid, *pSavedThreadPolicy);
2401 }
2402 }
2403
2404 /*
2405 * getpriority() returns the "nice" value, so larger numbers indicate
2406 * lower priority, with 0 being normal.
2407 */
2408 if (*pSavedThreadPrio > 0) {
2409 const int kHigher = 0;
2410 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2411 LOGW("Couldn't raise priority on tid %d to %d\n",
2412 thread->systemTid, kHigher);
2413 } else {
2414 changeFlags |= kChangedPriority;
2415 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2416 thread->systemTid, *pSavedThreadPrio, kHigher);
2417 }
2418 }
2419
2420 return changeFlags;
2421}
2422
2423/*
2424 * Reset the priority values for the thread in question.
2425 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002426void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002427 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2428{
2429 if ((changeFlags & kChangedPolicy) != 0) {
2430 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2431 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2432 thread->systemTid, savedThreadPolicy);
2433 } else {
2434 LOGD("Restored policy of %d to %d\n",
2435 thread->systemTid, savedThreadPolicy);
2436 }
2437 }
2438
2439 if ((changeFlags & kChangedPriority) != 0) {
2440 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2441 {
2442 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2443 thread->systemTid, savedThreadPrio);
2444 } else {
2445 LOGD("Restored priority on %d to %d\n",
2446 thread->systemTid, savedThreadPrio);
2447 }
2448 }
2449}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002450
2451/*
2452 * Wait for another thread to see the pending suspension and stop running.
2453 * It can either suspend itself or go into a non-running state such as
2454 * VMWAIT or NATIVE in which it cannot interact with the GC.
2455 *
2456 * If we're running at a higher priority, sched_yield() may not do anything,
2457 * so we need to sleep for "long enough" to guarantee that the other
2458 * thread has a chance to finish what it's doing. Sleeping for too short
2459 * a period (e.g. less than the resolution of the sleep clock) might cause
2460 * the scheduler to return immediately, so we want to start with a
2461 * "reasonable" value and expand.
2462 *
2463 * This does not return until the other thread has stopped running.
2464 * Eventually we time out and the VM aborts.
2465 *
2466 * This does not try to detect the situation where two threads are
2467 * waiting for each other to suspend. In normal use this is part of a
2468 * suspend-all, which implies that the suspend-all lock is held, or as
2469 * part of a debugger action in which the JDWP thread is always the one
2470 * doing the suspending. (We may need to re-evaluate this now that
2471 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2472 *
2473 * TODO: track basic stats about time required to suspend VM.
2474 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002475#define FIRST_SLEEP (250*1000) /* 0.25s */
2476#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002477static void waitForThreadSuspend(Thread* self, Thread* thread)
2478{
2479 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002480 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002481 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002482 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002483 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002484 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002485
2486 int sleepIter = 0;
2487 int retryCount = 0;
2488 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002489 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002490
Andy McFadden6dce9962010-08-23 16:45:24 -07002491 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002492 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002493 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002494 if (firstStartWhen == 0) // first iteration of first attempt
2495 firstStartWhen = startWhen;
2496
2497 /*
2498 * After waiting for a bit, check to see if the target thread is
2499 * running at a reduced priority. If so, bump it up temporarily
2500 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002501 */
2502 if (retryCount == 2) {
2503 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002504 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002505 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002506 }
2507 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002508
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002509#if defined (WITH_JIT)
2510 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002511 * If we're still waiting after the first timeout, unchain all
2512 * translations iff:
2513 * 1) There are new chains formed since the last unchain
2514 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002515 */
Ben Cheng6999d842010-01-26 16:46:15 -08002516 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2517 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002518 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002519 dvmJitUnchainAll();
2520 }
2521#endif
2522
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002523 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002524 * Sleep briefly. The iterative sleep call returns false if we've
2525 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002526 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002527 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002528 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002529 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002530 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002531 thread->threadId, priChangeFlags);
2532 if (retryCount > 1) {
2533 /* stack trace logging is slow; skip on first iter */
2534 dumpWedgedThread(thread);
2535 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002536 complained = true;
2537 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002538
2539 // keep going; could be slow due to valgrind
2540 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002541 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002542
2543 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002544 LOGE("Fatal spin-on-suspend, dumping threads\n");
2545 dvmDumpAllThreads(false);
2546
2547 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002548 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2549 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002550
2551 /* try to get a debuggerd dump from the spinning thread */
2552 dvmNukeThread(thread);
2553 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002554 dvmAbort();
2555 }
2556 }
2557 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002558
2559 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002560 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2561 self->threadId,
2562 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002563 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2564 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002565 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002566 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002567 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002568 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002569}
2570
2571/*
2572 * Suspend all threads except the current one. This is used by the GC,
2573 * the debugger, and by any thread that hits a "suspend all threads"
2574 * debugger event (e.g. breakpoint or exception).
2575 *
2576 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2577 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2578 * create objects and even execute arbitrary code. The "why" argument
2579 * allows the caller to say why the suspension is taking place.
2580 *
2581 * This can be called when a global suspend has already happened, due to
2582 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2583 * doesn't work.
2584 *
2585 * DO NOT grab any locks before calling here. We grab & release the thread
2586 * lock and suspend lock here (and we're not using recursive threads), and
2587 * we might have to self-suspend if somebody else beats us here.
2588 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002589 * We know the current thread is in the thread list, because we attach the
2590 * thread before doing anything that could cause VM suspension (like object
2591 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002592 */
2593void dvmSuspendAllThreads(SuspendCause why)
2594{
2595 Thread* self = dvmThreadSelf();
2596 Thread* thread;
2597
2598 assert(why != 0);
2599
2600 /*
2601 * Start by grabbing the thread suspend lock. If we can't get it, most
2602 * likely somebody else is in the process of performing a suspend or
2603 * resume, so lockThreadSuspend() will cause us to self-suspend.
2604 *
2605 * We keep the lock until all other threads are suspended.
2606 */
2607 lockThreadSuspend("susp-all", why);
2608
2609 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2610
2611 /*
2612 * This is possible if the current thread was in VMWAIT mode when a
2613 * suspend-all happened, and then decided to do its own suspend-all.
2614 * This can happen when a couple of threads have simultaneous events
2615 * of interest to the debugger.
2616 */
buzbee9a3147c2011-03-02 15:43:48 -08002617 //assert(self->interpBreak.ctl.suspendCount == 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002618
2619 /*
2620 * Increment everybody's suspend count (except our own).
2621 */
2622 dvmLockThreadList(self);
2623
2624 lockThreadSuspendCount();
2625 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2626 if (thread == self)
2627 continue;
2628
2629 /* debugger events don't suspend JDWP thread */
2630 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2631 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2632 continue;
2633
buzbee9a3147c2011-03-02 15:43:48 -08002634 dvmAddToSuspendCounts(thread, 1,
2635 (why == SUSPEND_FOR_DEBUG ||
2636 why == SUSPEND_FOR_DEBUG_EVENT)
2637 ? 1 : 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002638 }
2639 unlockThreadSuspendCount();
2640
2641 /*
2642 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2643 * indicate the code is either running natively or sleeping quietly.
2644 * Any attempt to transition back to THREAD_RUNNING will cause a check
2645 * for suspension, so it should be impossible for anything to execute
2646 * interpreted code or modify objects (assuming native code plays nicely).
2647 *
2648 * It's also okay if the thread transitions to a non-RUNNING state.
2649 *
2650 * Note we released the threadSuspendCountLock before getting here,
2651 * so if another thread is fiddling with its suspend count (perhaps
2652 * self-suspending for the debugger) it won't block while we're waiting
2653 * in here.
2654 */
2655 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2656 if (thread == self)
2657 continue;
2658
2659 /* debugger events don't suspend JDWP thread */
2660 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2661 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2662 continue;
2663
2664 /* wait for the other thread to see the pending suspend */
2665 waitForThreadSuspend(self, thread);
2666
Andy McFadden6dce9962010-08-23 16:45:24 -07002667 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002668 self->threadId,
buzbee9a3147c2011-03-02 15:43:48 -08002669 thread->threadId, thread->status,
2670 thread->interpBreak.ctl.suspendCount,
2671 thread->interpBreak.ctl.dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002672 }
2673
2674 dvmUnlockThreadList();
2675 unlockThreadSuspend();
2676
2677 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2678}
2679
2680/*
2681 * Resume all threads that are currently suspended.
2682 *
2683 * The "why" must match with the previous suspend.
2684 */
2685void dvmResumeAllThreads(SuspendCause why)
2686{
2687 Thread* self = dvmThreadSelf();
2688 Thread* thread;
2689 int cc;
2690
2691 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2692 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2693
2694 /*
2695 * Decrement the suspend counts for all threads. No need for atomic
2696 * writes, since nobody should be moving until we decrement the count.
2697 * We do need to hold the thread list because of JNI attaches.
2698 */
2699 dvmLockThreadList(self);
2700 lockThreadSuspendCount();
2701 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2702 if (thread == self)
2703 continue;
2704
2705 /* debugger events don't suspend JDWP thread */
2706 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2707 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002708 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002709 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002710 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002711
buzbee9a3147c2011-03-02 15:43:48 -08002712 if (thread->interpBreak.ctl.suspendCount > 0) {
2713 dvmAddToSuspendCounts(thread, -1,
2714 (why == SUSPEND_FOR_DEBUG ||
2715 why == SUSPEND_FOR_DEBUG_EVENT)
2716 ? -1 : 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002717 } else {
2718 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2719 thread->threadId);
2720 }
2721 }
2722 unlockThreadSuspendCount();
2723 dvmUnlockThreadList();
2724
2725 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002726 * In some ways it makes sense to continue to hold the thread-suspend
2727 * lock while we issue the wakeup broadcast. It allows us to complete
2728 * one operation before moving on to the next, which simplifies the
2729 * thread activity debug traces.
2730 *
2731 * This approach caused us some difficulty under Linux, because the
2732 * condition variable broadcast not only made the threads runnable,
2733 * but actually caused them to execute, and it was a while before
2734 * the thread performing the wakeup had an opportunity to release the
2735 * thread-suspend lock.
2736 *
2737 * This is a problem because, when a thread tries to acquire that
2738 * lock, it times out after 3 seconds. If at some point the thread
2739 * is told to suspend, the clock resets; but since the VM is still
2740 * theoretically mid-resume, there's no suspend pending. If, for
2741 * example, the GC was waking threads up while the SIGQUIT handler
2742 * was trying to acquire the lock, we would occasionally time out on
2743 * a busy system and SignalCatcher would abort.
2744 *
2745 * We now perform the unlock before the wakeup broadcast. The next
2746 * suspend can't actually start until the broadcast completes and
2747 * returns, because we're holding the thread-suspend-count lock, but the
2748 * suspending thread is now able to make progress and we avoid the abort.
2749 *
2750 * (Technically there is a narrow window between when we release
2751 * the thread-suspend lock and grab the thread-suspend-count lock.
2752 * This could cause us to send a broadcast to threads with nonzero
2753 * suspend counts, but this is expected and they'll all just fall
2754 * right back to sleep. It's probably safe to grab the suspend-count
2755 * lock before releasing thread-suspend, since we're still following
2756 * the correct order of acquisition, but it feels weird.)
2757 */
2758
2759 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2760 unlockThreadSuspend();
2761
2762 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002763 * Broadcast a notification to all suspended threads, some or all of
2764 * which may choose to wake up. No need to wait for them.
2765 */
2766 lockThreadSuspendCount();
2767 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2768 assert(cc == 0);
2769 unlockThreadSuspendCount();
2770
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002771 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2772}
2773
2774/*
2775 * Undo any debugger suspensions. This is called when the debugger
2776 * disconnects.
2777 */
2778void dvmUndoDebuggerSuspensions(void)
2779{
2780 Thread* self = dvmThreadSelf();
2781 Thread* thread;
2782 int cc;
2783
2784 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2785 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2786
2787 /*
2788 * Decrement the suspend counts for all threads. No need for atomic
2789 * writes, since nobody should be moving until we decrement the count.
2790 * We do need to hold the thread list because of JNI attaches.
2791 */
2792 dvmLockThreadList(self);
2793 lockThreadSuspendCount();
2794 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2795 if (thread == self)
2796 continue;
2797
2798 /* debugger events don't suspend JDWP thread */
2799 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
buzbee9a3147c2011-03-02 15:43:48 -08002800 assert(thread->interpBreak.ctl.dbgSuspendCount == 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002801 continue;
2802 }
2803
buzbee9a3147c2011-03-02 15:43:48 -08002804 assert(thread->interpBreak.ctl.suspendCount >=
2805 thread->interpBreak.ctl.dbgSuspendCount);
2806 dvmAddToSuspendCounts(thread,
2807 -thread->interpBreak.ctl.dbgSuspendCount,
2808 -thread->interpBreak.ctl.dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002809 }
2810 unlockThreadSuspendCount();
2811 dvmUnlockThreadList();
2812
2813 /*
2814 * Broadcast a notification to all suspended threads, some or all of
2815 * which may choose to wake up. No need to wait for them.
2816 */
2817 lockThreadSuspendCount();
2818 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2819 assert(cc == 0);
2820 unlockThreadSuspendCount();
2821
2822 unlockThreadSuspend();
2823
2824 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2825}
2826
2827/*
2828 * Determine if a thread is suspended.
2829 *
2830 * As with all operations on foreign threads, the caller should hold
2831 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002832 *
2833 * If the thread is suspending or waking, these fields could be changing
2834 * out from under us (or the thread could change state right after we
2835 * examine it), making this generally unreliable. This is chiefly
2836 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002837 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002838bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002839{
2840 /*
2841 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07002842 * (1) Running happily. status is RUNNING, suspendCount is zero.
2843 * Return "false".
2844 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
2845 * Return "false".
2846 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002847 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07002848 * (4) Waking up. suspendCount is zero, status is SUSPENDED
2849 * Return "false" (since it could change out from under us, unless
2850 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002851 */
2852
buzbee9a3147c2011-03-02 15:43:48 -08002853 return (thread->interpBreak.ctl.suspendCount != 0 &&
2854 thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002855}
2856
2857/*
2858 * Wait until another thread self-suspends. This is specifically for
2859 * synchronization between the JDWP thread and a thread that has decided
2860 * to suspend itself after sending an event to the debugger.
2861 *
2862 * Threads that encounter "suspend all" events work as well -- the thread
2863 * in question suspends everybody else and then itself.
2864 *
2865 * We can't hold a thread lock here or in the caller, because we could
2866 * get here just before the to-be-waited-for-thread issues a "suspend all".
2867 * There's an opportunity for badness if the thread we're waiting for exits
2868 * and gets cleaned up, but since the thread in question is processing a
2869 * debugger event, that's not really a possibility. (To avoid deadlock,
2870 * it's important that we not be in THREAD_RUNNING while we wait.)
2871 */
2872void dvmWaitForSuspend(Thread* thread)
2873{
2874 Thread* self = dvmThreadSelf();
2875
2876 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
2877 self->threadId, thread->threadId);
2878
2879 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2880 assert(thread != self);
2881 assert(self->status != THREAD_RUNNING);
2882
2883 waitForThreadSuspend(self, thread);
2884
2885 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
2886 self->threadId, thread->threadId);
2887}
2888
2889/*
2890 * Check to see if we need to suspend ourselves. If so, go to sleep on
2891 * a condition variable.
2892 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002893 * Returns "true" if we suspended ourselves.
2894 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002895static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002896{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002897 assert(self != NULL);
buzbee9a3147c2011-03-02 15:43:48 -08002898 assert(self->interpBreak.ctl.suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002899
Andy McFadden6dce9962010-08-23 16:45:24 -07002900 /*
2901 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
buzbee9a3147c2011-03-02 15:43:48 -08002902 * access to self->interpBreak.ctl.suspendCount.
Andy McFadden6dce9962010-08-23 16:45:24 -07002903 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002904 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
2905
buzbee9a3147c2011-03-02 15:43:48 -08002906 bool needSuspend = (self->interpBreak.ctl.suspendCount != 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002907 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07002908 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07002909 ThreadStatus oldStatus = self->status; /* should be RUNNING */
2910 self->status = THREAD_SUSPENDED;
2911
buzbee9a3147c2011-03-02 15:43:48 -08002912 while (self->interpBreak.ctl.suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07002913 /*
2914 * Wait for wakeup signal, releasing lock. The act of releasing
2915 * and re-acquiring the lock provides the memory barriers we
2916 * need for correct behavior on SMP.
2917 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002918 dvmWaitCond(&gDvm.threadSuspendCountCond,
2919 &gDvm.threadSuspendCountLock);
2920 }
buzbee9a3147c2011-03-02 15:43:48 -08002921 assert(self->interpBreak.ctl.suspendCount == 0 &&
2922 self->interpBreak.ctl.dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002923 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07002924 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
2925 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002926 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002927
2928 unlockThreadSuspendCount();
2929
Andy McFadden6dce9962010-08-23 16:45:24 -07002930 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002931}
2932
2933/*
Andy McFadden6dce9962010-08-23 16:45:24 -07002934 * Check to see if a suspend is pending. If so, suspend the current
2935 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002936 */
2937bool dvmCheckSuspendPending(Thread* self)
2938{
Andy McFadden6dce9962010-08-23 16:45:24 -07002939 assert(self != NULL);
buzbee9a3147c2011-03-02 15:43:48 -08002940 if (self->interpBreak.ctl.suspendCount == 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07002941 return false;
2942 } else {
2943 return fullSuspendCheck(self);
2944 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002945}
2946
2947/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002948 * Update our status.
2949 *
2950 * The "self" argument, which may be NULL, is accepted as an optimization.
2951 *
2952 * Returns the old status.
2953 */
2954ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
2955{
2956 ThreadStatus oldStatus;
2957
2958 if (self == NULL)
2959 self = dvmThreadSelf();
2960
2961 LOGVV("threadid=%d: (status %d -> %d)\n",
2962 self->threadId, self->status, newStatus);
2963
2964 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07002965 if (oldStatus == newStatus)
2966 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002967
2968 if (newStatus == THREAD_RUNNING) {
2969 /*
2970 * Change our status to THREAD_RUNNING. The transition requires
2971 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002972 * us to be "asleep" in all other states, and another thread could
2973 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002974 *
Andy McFadden6dce9962010-08-23 16:45:24 -07002975 * The order of operations is very significant here. One way to
2976 * do this wrong is:
2977 *
2978 * GCing thread Our thread (in NATIVE)
2979 * ------------ ----------------------
2980 * check suspend count (== 0)
2981 * dvmSuspendAllThreads()
2982 * grab suspend-count lock
2983 * increment all suspend counts
2984 * release suspend-count lock
2985 * check thread state (== NATIVE)
2986 * all are suspended, begin GC
2987 * set state to RUNNING
2988 * (continue executing)
2989 *
2990 * We can correct this by grabbing the suspend-count lock and
2991 * performing both of our operations (check suspend count, set
2992 * state) while holding it, now we need to grab a mutex on every
2993 * transition to RUNNING.
2994 *
2995 * What we do instead is change the order of operations so that
2996 * the transition to RUNNING happens first. If we then detect
2997 * that the suspend count is nonzero, we switch to SUSPENDED.
2998 *
2999 * Appropriate compiler and memory barriers are required to ensure
3000 * that the operations are observed in the expected order.
3001 *
3002 * This does create a small window of opportunity where a GC in
3003 * progress could observe what appears to be a running thread (if
3004 * it happens to look between when we set to RUNNING and when we
3005 * switch to SUSPENDED). At worst this only affects assertions
3006 * and thread logging. (We could work around it with some sort
3007 * of intermediate "pre-running" state that is generally treated
3008 * as equivalent to running, but that doesn't seem worthwhile.)
3009 *
3010 * We can also solve this by combining the "status" and "suspend
3011 * count" fields into a single 32-bit value. This trades the
3012 * store/load barrier on transition to RUNNING for an atomic RMW
3013 * op on all transitions and all suspend count updates (also, all
3014 * accesses to status or the thread count require bit-fiddling).
3015 * It also eliminates the brief transition through RUNNING when
3016 * the thread is supposed to be suspended. This is possibly faster
3017 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003018 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003019 android_atomic_acquire_store(newStatus, &self->status);
buzbee9a3147c2011-03-02 15:43:48 -08003020 if (self->interpBreak.ctl.suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003021 fullSuspendCheck(self);
3022 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003023 } else {
3024 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003025 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003026 *
3027 * We use a releasing store to ensure that, if we were RUNNING,
3028 * any updates we previously made to objects on the managed heap
3029 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003030 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003031 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003032 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003033 }
3034
3035 return oldStatus;
3036}
3037
3038/*
3039 * Get a statically defined thread group from a field in the ThreadGroup
3040 * Class object. Expected arguments are "mMain" and "mSystem".
3041 */
3042static Object* getStaticThreadGroup(const char* fieldName)
3043{
3044 StaticField* groupField;
3045 Object* groupObj;
3046
3047 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3048 fieldName, "Ljava/lang/ThreadGroup;");
3049 if (groupField == NULL) {
3050 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
Dan Bornstein70b00ab2011-02-23 14:11:27 -08003051 dvmThrowInternalError("bad definition for ThreadGroup");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003052 return NULL;
3053 }
3054 groupObj = dvmGetStaticFieldObject(groupField);
3055 if (groupObj == NULL) {
3056 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
Dan Bornsteind27f3cf2011-02-23 13:07:07 -08003057 dvmThrowInternalError(NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003058 return NULL;
3059 }
3060
3061 return groupObj;
3062}
3063Object* dvmGetSystemThreadGroup(void)
3064{
3065 return getStaticThreadGroup("mSystem");
3066}
3067Object* dvmGetMainThreadGroup(void)
3068{
3069 return getStaticThreadGroup("mMain");
3070}
3071
3072/*
3073 * Given a VMThread object, return the associated Thread*.
3074 *
3075 * NOTE: if the thread detaches, the struct Thread will disappear, and
3076 * we will be touching invalid data. For safety, lock the thread list
3077 * before calling this.
3078 */
3079Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3080{
3081 int vmData;
3082
3083 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003084
3085 if (false) {
3086 Thread* thread = gDvm.threadList;
3087 while (thread != NULL) {
3088 if ((Thread*)vmData == thread)
3089 break;
3090
3091 thread = thread->next;
3092 }
3093
3094 if (thread == NULL) {
3095 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3096 vmThreadObj, (Thread*)vmData);
3097 vmData = 0;
3098 }
3099 }
3100
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003101 return (Thread*) vmData;
3102}
3103
Andy McFadden2b94b302010-03-09 16:38:36 -08003104/*
3105 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003106 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003107 *
3108 * Returns NULL if the thread was not found.
3109 */
3110Thread* dvmGetThreadByHandle(pthread_t handle)
3111{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003112 Thread* thread;
3113 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003114 if (thread->handle == handle)
3115 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003116 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003117 return thread;
3118}
Andy McFadden2b94b302010-03-09 16:38:36 -08003119
Andy McFadden0a24ef92010-03-12 13:39:59 -08003120/*
3121 * Given a threadId, return the associated Thread*.
3122 * Caller must hold the thread list lock.
3123 *
3124 * Returns NULL if the thread was not found.
3125 */
3126Thread* dvmGetThreadByThreadId(u4 threadId)
3127{
3128 Thread* thread;
3129 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3130 if (thread->threadId == threadId)
3131 break;
3132 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003133 return thread;
3134}
3135
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003136
3137/*
3138 * Conversion map for "nice" values.
3139 *
3140 * We use Android thread priority constants to be consistent with the rest
3141 * of the system. In some cases adjacent entries may overlap.
3142 */
3143static const int kNiceValues[10] = {
3144 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3145 ANDROID_PRIORITY_BACKGROUND + 6,
3146 ANDROID_PRIORITY_BACKGROUND + 3,
3147 ANDROID_PRIORITY_BACKGROUND,
3148 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3149 ANDROID_PRIORITY_NORMAL - 2,
3150 ANDROID_PRIORITY_NORMAL - 4,
3151 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3152 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3153 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3154};
3155
3156/*
3157 * Change the priority of a system thread to match that of the Thread object.
3158 *
3159 * We map a priority value from 1-10 to Linux "nice" values, where lower
3160 * numbers indicate higher priority.
3161 */
3162void dvmChangeThreadPriority(Thread* thread, int newPriority)
3163{
3164 pid_t pid = thread->systemTid;
3165 int newNice;
3166
3167 if (newPriority < 1 || newPriority > 10) {
3168 LOGW("bad priority %d\n", newPriority);
3169 newPriority = 5;
3170 }
3171 newNice = kNiceValues[newPriority-1];
3172
Andy McFaddend62c0b52009-08-04 15:02:12 -07003173 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003174 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003175 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003176 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003177 }
3178
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003179 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3180 char* str = dvmGetThreadName(thread);
3181 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3182 pid, str, newPriority, newNice, strerror(errno));
3183 free(str);
3184 } else {
3185 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3186 pid, newPriority, newNice);
3187 }
3188}
3189
3190/*
3191 * Get the thread priority for the current thread by querying the system.
3192 * This is useful when attaching a thread through JNI.
3193 *
3194 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3195 */
3196static int getThreadPriorityFromSystem(void)
3197{
3198 int i, sysprio, jprio;
3199
3200 errno = 0;
3201 sysprio = getpriority(PRIO_PROCESS, 0);
3202 if (sysprio == -1 && errno != 0) {
3203 LOGW("getpriority() failed: %s\n", strerror(errno));
3204 return THREAD_NORM_PRIORITY;
3205 }
3206
3207 jprio = THREAD_MIN_PRIORITY;
3208 for (i = 0; i < NELEM(kNiceValues); i++) {
3209 if (sysprio >= kNiceValues[i])
3210 break;
3211 jprio++;
3212 }
3213 if (jprio > THREAD_MAX_PRIORITY)
3214 jprio = THREAD_MAX_PRIORITY;
3215
3216 return jprio;
3217}
3218
3219
3220/*
3221 * Return true if the thread is on gDvm.threadList.
3222 * Caller should not hold gDvm.threadListLock.
3223 */
3224bool dvmIsOnThreadList(const Thread* thread)
3225{
3226 bool ret = false;
3227
3228 dvmLockThreadList(NULL);
3229 if (thread == gDvm.threadList) {
3230 ret = true;
3231 } else {
3232 ret = thread->prev != NULL || thread->next != NULL;
3233 }
3234 dvmUnlockThreadList();
3235
3236 return ret;
3237}
3238
3239/*
3240 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3241 * output target.
3242 */
3243void dvmDumpThread(Thread* thread, bool isRunning)
3244{
3245 DebugOutputTarget target;
3246
3247 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3248 dvmDumpThreadEx(&target, thread, isRunning);
3249}
3250
3251/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003252 * Try to get the scheduler group.
3253 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003254 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003255 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003256 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003257 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003258 * We return the part on the "cpu" line after the '/', which will be an
3259 * empty string for the default cgroup. If the string is longer than
3260 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003261 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003262 * On error, -1 is returned, and an error description will be stored in
3263 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003264 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003265static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003266{
3267#ifdef HAVE_ANDROID_OS
3268 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003269 char lineBuf[256];
3270 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003271
Andy McFadden7f64ede2010-03-03 15:37:10 -08003272 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003273 if ((fp = fopen(pathBuf, "r")) == NULL) {
3274 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003275 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003276 }
3277
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003278 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3279 char* subsys;
3280 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003281 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003282
Andy McFadden7f64ede2010-03-03 15:37:10 -08003283 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003284 subsys = strchr(lineBuf, ':');
3285 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003286 goto out_bad_data;
3287 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003288
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003289 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003290 /* Not the subsys we're looking for */
3291 continue;
3292 }
3293
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003294 grp = strchr(subsys, '/');
3295 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003296 goto out_bad_data;
3297 }
3298 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003299
Andy McFadden7f64ede2010-03-03 15:37:10 -08003300 len = strlen(grp);
3301 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3302
3303 if (bufLen <= len) {
3304 len = bufLen - 1;
3305 }
3306 strncpy(buf, grp, len);
3307 buf[len] = '\0';
3308 fclose(fp);
3309 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003310 }
3311
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003312 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003313 fclose(fp);
3314 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003315
3316out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003317 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003318 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003319 fclose(fp);
3320 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003321
Andy McFaddend62c0b52009-08-04 15:02:12 -07003322#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003323 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003324 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003325#endif
3326}
3327
3328/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003329 * Convert ThreadStatus to a string.
3330 */
3331const char* dvmGetThreadStatusStr(ThreadStatus status)
3332{
3333 switch (status) {
3334 case THREAD_ZOMBIE: return "ZOMBIE";
3335 case THREAD_RUNNING: return "RUNNABLE";
3336 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3337 case THREAD_MONITOR: return "MONITOR";
3338 case THREAD_WAIT: return "WAIT";
3339 case THREAD_INITIALIZING: return "INITIALIZING";
3340 case THREAD_STARTING: return "STARTING";
3341 case THREAD_NATIVE: return "NATIVE";
3342 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003343 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003344 default: return "UNKNOWN";
3345 }
3346}
3347
3348/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003349 * Print information about the specified thread.
3350 *
3351 * Works best when the thread in question is "self" or has been suspended.
3352 * When dumping a separate thread that's still running, set "isRunning" to
3353 * use a more cautious thread dump function.
3354 */
3355void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3356 bool isRunning)
3357{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003358 Object* threadObj;
3359 Object* groupObj;
3360 StringObject* nameStr;
3361 char* threadName = NULL;
3362 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003363 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003364 bool isDaemon;
3365 int priority; // java.lang.Thread priority
3366 int policy; // pthread policy
3367 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003368 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003369
Andy McFaddene3346d82010-06-02 15:37:21 -07003370 /*
3371 * Get the java.lang.Thread object. This function gets called from
3372 * some weird debug contexts, so it's possible that there's a GC in
3373 * progress on some other thread. To decrease the chances of the
3374 * thread object being moved out from under us, we add the reference
3375 * to the tracked allocation list, which pins it in place.
3376 *
3377 * If threadObj is NULL, the thread is still in the process of being
3378 * attached to the VM, and there's really nothing interesting to
3379 * say about it yet.
3380 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003381 threadObj = thread->threadObj;
3382 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003383 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003384 return;
3385 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003386 dvmAddTrackedAlloc(threadObj, NULL);
3387
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003388 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3389 gDvm.offJavaLangThread_name);
3390 threadName = dvmCreateCstrFromString(nameStr);
3391
3392 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3393 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3394
3395 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3396 LOGW("Warning: pthread_getschedparam failed\n");
3397 policy = -1;
3398 sp.sched_priority = -1;
3399 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003400 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003401 sizeof(schedulerGroupBuf)) == 0 &&
3402 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003403 strcpy(schedulerGroupBuf, "default");
3404 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003405
3406 /* a null value for group is not expected, but deal with it anyway */
3407 groupObj = (Object*) dvmGetFieldObject(threadObj,
3408 gDvm.offJavaLangThread_group);
3409 if (groupObj != NULL) {
3410 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3411 "name", "Ljava/lang/String;");
3412 if (offset < 0) {
3413 LOGW("Unable to find 'name' field in ThreadGroup\n");
3414 } else {
3415 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3416 groupName = dvmCreateCstrFromString(nameStr);
3417 }
3418 }
3419 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003420 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003421
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003422 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003423 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003424 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003425 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3426#if defined(WITH_JIT)
3427 thread->inJitCodeCache ? " JIT" : ""
3428#else
3429 ""
3430#endif
3431 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003432 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003433 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
buzbee9a3147c2011-03-02 15:43:48 -08003434 groupName, thread->interpBreak.ctl.suspendCount,
3435 thread->interpBreak.ctl.dbgSuspendCount, thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003436 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003437 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003438 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003439 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003440
Andy McFadden0a3f6982010-08-31 13:50:08 -07003441 /* get some bits from /proc/self/stat */
3442 ProcStatData procStatData;
3443 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3444 /* failed, use zeroed values */
3445 memset(&procStatData, 0, sizeof(procStatData));
3446 }
3447
3448 /* grab the scheduler stats for this thread */
3449 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3450 thread->systemTid);
3451 int schedstatFd = open(schedstatBuf, O_RDONLY);
3452 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003453 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003454 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003455 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3456 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003457 if (bytes >= 1) {
3458 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003459 }
3460 }
3461
Andy McFadden0a3f6982010-08-31 13:50:08 -07003462 /* show what we got */
3463 dvmPrintDebugMessage(target,
3464 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3465 schedstatBuf, procStatData.utime, procStatData.stime,
3466 procStatData.processor);
3467
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003468 if (isRunning)
3469 dvmDumpRunningThreadStack(target, thread);
3470 else
3471 dvmDumpThreadStack(target, thread);
3472
Andy McFaddene3346d82010-06-02 15:37:21 -07003473 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003474 free(threadName);
3475 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003476}
3477
3478/*
3479 * Get the name of a thread.
3480 *
3481 * For correctness, the caller should hold the thread list lock to ensure
3482 * that the thread doesn't go away mid-call.
3483 *
3484 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3485 */
3486char* dvmGetThreadName(Thread* thread)
3487{
3488 StringObject* nameObj;
3489
3490 if (thread->threadObj == NULL) {
3491 LOGW("threadObj is NULL, name not available\n");
3492 return strdup("-unknown-");
3493 }
3494
3495 nameObj = (StringObject*)
3496 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3497 return dvmCreateCstrFromString(nameObj);
3498}
3499
3500/*
3501 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3502 * an output target.
3503 */
3504void dvmDumpAllThreads(bool grabLock)
3505{
3506 DebugOutputTarget target;
3507
3508 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3509 dvmDumpAllThreadsEx(&target, grabLock);
3510}
3511
3512/*
3513 * Print information about all known threads. Assumes they have been
3514 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3515 *
3516 * If "grabLock" is true, we grab the thread lock list. This is important
3517 * to do unless the caller already holds the lock.
3518 */
3519void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3520{
3521 Thread* thread;
3522
3523 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3524
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003525#ifdef HAVE_ANDROID_OS
3526 dvmPrintDebugMessage(target,
3527 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3528 gDvm.threadListLock.value,
3529 gDvm._threadSuspendLock.value,
3530 gDvm.threadSuspendCountLock.value,
3531 gDvm.gcHeapLock.value,
3532 gDvm.heapWorkerLock.value,
3533 gDvm.heapWorkerListLock.value);
3534#endif
3535
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003536 if (grabLock)
3537 dvmLockThreadList(dvmThreadSelf());
3538
3539 thread = gDvm.threadList;
3540 while (thread != NULL) {
3541 dvmDumpThreadEx(target, thread, false);
3542
3543 /* verify link */
3544 assert(thread->next == NULL || thread->next->prev == thread);
3545
3546 thread = thread->next;
3547 }
3548
3549 if (grabLock)
3550 dvmUnlockThreadList();
3551}
3552
Andy McFadden384ef6b2010-03-15 17:24:55 -07003553/*
3554 * Nuke the target thread from orbit.
3555 *
3556 * The idea is to send a "crash" signal to the target thread so that
3557 * debuggerd will take notice and dump an appropriate stack trace.
3558 * Because of the way debuggerd works, we have to throw the same signal
3559 * at it twice.
3560 *
3561 * This does not necessarily cause the entire process to stop, but once a
3562 * thread has been nuked the rest of the system is likely to be unstable.
3563 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003564 * performed, but it's advisable (and expected) to call dvmAbort soon.
3565 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003566 */
3567void dvmNukeThread(Thread* thread)
3568{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003569 int killResult;
3570
Andy McFaddena388a162010-03-18 16:27:14 -07003571 /* suppress the heapworker watchdog to assist anyone using a debugger */
3572 gDvm.nativeDebuggerActive = true;
3573
Andy McFadden384ef6b2010-03-15 17:24:55 -07003574 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003575 * Send the signals, separated by a brief interval to allow debuggerd
3576 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3577 * can be used instead of SIGSEGV to avoid making it look like the
3578 * code actually crashed at the current point of execution.
3579 *
3580 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3581 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3582 * you don't get the second stack trace; possibly something in the
3583 * kernel decides that a signal has already been sent and it's time
3584 * to just kill the process. The position in the current thread is
3585 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003586 *
Andy McFaddena388a162010-03-18 16:27:14 -07003587 * The target thread can continue to execute between the two signals.
3588 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003589 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003590 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3591 " cause debuggerd dump\n",
3592 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003593 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3594 if (killResult != 0) {
3595 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3596 }
Andy McFaddena388a162010-03-18 16:27:14 -07003597 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003598 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3599 if (killResult != 0) {
3600 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3601 }
Andy McFadden7122d862010-03-19 15:18:57 -07003602 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003603 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003604
3605 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3606 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003607 LOGD("Continuing\n");
3608}