blob: a98dbd000c0bea3bdc6eb2da1e097ae310d5f1b9 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
The Android Open Source Project99409882009-03-18 22:20:24 -070016
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080017/*
18 * Thread support.
19 */
20#include "Dalvik.h"
21
22#include "utils/threads.h" // need Android thread priorities
23
24#include <stdlib.h>
25#include <unistd.h>
26#include <sys/time.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070027#include <sys/types.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080028#include <sys/resource.h>
29#include <sys/mman.h>
Andy McFadden384ef6b2010-03-15 17:24:55 -070030#include <signal.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080031#include <errno.h>
Andy McFaddend62c0b52009-08-04 15:02:12 -070032#include <fcntl.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080033
34#if defined(HAVE_PRCTL)
35#include <sys/prctl.h>
36#endif
37
Ben Chengfe1be872009-08-21 16:18:46 -070038#if defined(WITH_SELF_VERIFICATION)
39#include "interp/Jit.h" // need for self verification
40#endif
41
42
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080043/* desktop Linux needs a little help with gettid() */
44#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
45#define __KERNEL__
46# include <linux/unistd.h>
47#ifdef _syscall0
48_syscall0(pid_t,gettid)
49#else
50pid_t gettid() { return syscall(__NR_gettid);}
51#endif
52#undef __KERNEL__
53#endif
54
San Mehat256fc152009-04-21 14:03:06 -070055// Change this to enable logging on cgroup errors
56#define ENABLE_CGROUP_ERR_LOGGING 0
57
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080058// change this to LOGV/LOGD to debug thread activity
59#define LOG_THREAD LOGVV
60
61/*
62Notes on Threading
63
64All threads are native pthreads. All threads, except the JDWP debugger
65thread, are visible to code running in the VM and to the debugger. (We
66don't want the debugger to try to manipulate the thread that listens for
67instructions from the debugger.) Internal VM threads are in the "system"
68ThreadGroup, all others are in the "main" ThreadGroup, per convention.
69
70The GC only runs when all threads have been suspended. Threads are
71expected to suspend themselves, using a "safe point" mechanism. We check
72for a suspend request at certain points in the main interpreter loop,
73and on requests coming in from native code (e.g. all JNI functions).
74Certain debugger events may inspire threads to self-suspend.
75
76Native methods must use JNI calls to modify object references to avoid
77clashes with the GC. JNI doesn't provide a way for native code to access
78arrays of objects as such -- code must always get/set individual entries --
79so it should be possible to fully control access through JNI.
80
81Internal native VM threads, such as the finalizer thread, must explicitly
82check for suspension periodically. In most cases they will be sound
83asleep on a condition variable, and won't notice the suspension anyway.
84
85Threads may be suspended by the GC, debugger, or the SIGQUIT listener
86thread. The debugger may suspend or resume individual threads, while the
87GC always suspends all threads. Each thread has a "suspend count" that
88is incremented on suspend requests and decremented on resume requests.
89When the count is zero, the thread is runnable. This allows us to fulfill
90a debugger requirement: if the debugger suspends a thread, the thread is
91not allowed to run again until the debugger resumes it (or disconnects,
92in which case we must resume all debugger-suspended threads).
93
94Paused threads sleep on a condition variable, and are awoken en masse.
95Certain "slow" VM operations, such as starting up a new thread, will be
96done in a separate "VMWAIT" state, so that the rest of the VM doesn't
97freeze up waiting for the operation to finish. Threads must check for
98pending suspension when leaving VMWAIT.
99
100Because threads suspend themselves while interpreting code or when native
101code makes JNI calls, there is no risk of suspending while holding internal
102VM locks. All threads can enter a suspended (or native-code-only) state.
103Also, we don't have to worry about object references existing solely
104in hardware registers.
105
106We do, however, have to worry about objects that were allocated internally
107and aren't yet visible to anything else in the VM. If we allocate an
108object, and then go to sleep on a mutex after changing to a non-RUNNING
109state (e.g. while trying to allocate a second object), the first object
110could be garbage-collected out from under us while we sleep. To manage
111this, we automatically add all allocated objects to an internal object
112tracking list, and only remove them when we know we won't be suspended
113before the object appears in the GC root set.
114
115The debugger may choose to suspend or resume a single thread, which can
116lead to application-level deadlocks; this is expected behavior. The VM
117will only check for suspension of single threads when the debugger is
118active (the java.lang.Thread calls for this are deprecated and hence are
119not supported). Resumption of a single thread is handled by decrementing
120the thread's suspend count and sending a broadcast signal to the condition
121variable. (This will cause all threads to wake up and immediately go back
122to sleep, which isn't tremendously efficient, but neither is having the
123debugger attached.)
124
125The debugger is not allowed to resume threads suspended by the GC. This
126is trivially enforced by ignoring debugger requests while the GC is running
127(the JDWP thread is suspended during GC).
128
129The VM maintains a Thread struct for every pthread known to the VM. There
130is a java/lang/Thread object associated with every Thread. At present,
131there is no safe way to go from a Thread object to a Thread struct except by
132locking and scanning the list; this is necessary because the lifetimes of
133the two are not closely coupled. We may want to change this behavior,
134though at present the only performance impact is on the debugger (see
135threadObjToThread()). See also notes about dvmDetachCurrentThread().
136*/
137/*
138Alternate implementation (signal-based):
139
140Threads run without safe points -- zero overhead. The VM uses a signal
141(e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
142
143The trouble with using signals to suspend threads is that it means a thread
144can be in the middle of an operation when garbage collection starts.
145To prevent some sticky situations, we have to introduce critical sections
146to the VM code.
147
148Critical sections temporarily block suspension for a given thread.
149The thread must move to a non-blocked state (and self-suspend) after
150finishing its current task. If the thread blocks on a resource held
151by a suspended thread, we're hosed.
152
153One approach is to require that no blocking operations, notably
154acquisition of mutexes, can be performed within a critical section.
155This is too limiting. For example, if thread A gets suspended while
156holding the thread list lock, it will prevent the GC or debugger from
157being able to safely access the thread list. We need to wrap the critical
158section around the entire operation (enter critical, get lock, do stuff,
159release lock, exit critical).
160
161A better approach is to declare that certain resources can only be held
162within critical sections. A thread that enters a critical section and
163then gets blocked on the thread list lock knows that the thread it is
164waiting for is also in a critical section, and will release the lock
165before suspending itself. Eventually all threads will complete their
166operations and self-suspend. For this to work, the VM must:
167
168 (1) Determine the set of resources that may be accessed from the GC or
169 debugger threads. The mutexes guarding those go into the "critical
170 resource set" (CRS).
171 (2) Ensure that no resource in the CRS can be acquired outside of a
172 critical section. This can be verified with an assert().
173 (3) Ensure that only resources in the CRS can be held while in a critical
174 section. This is harder to enforce.
175
176If any of these conditions are not met, deadlock can ensue when grabbing
177resources in the GC or debugger (#1) or waiting for threads to suspend
178(#2,#3). (You won't actually deadlock in the GC, because if the semantics
179above are followed you don't need to lock anything in the GC. The risk is
180rather that the GC will access data structures in an intermediate state.)
181
182This approach requires more care and awareness in the VM than
183safe-pointing. Because the GC and debugger are fairly intrusive, there
184really aren't any internal VM resources that aren't shared. Thus, the
185enter/exit critical calls can be added to internal mutex wrappers, which
186makes it easy to get #1 and #2 right.
187
188An ordering should be established for all locks to avoid deadlocks.
189
190Monitor locks, which are also implemented with pthread calls, should not
191cause any problems here. Threads fighting over such locks will not be in
192critical sections and can be suspended freely.
193
194This can get tricky if we ever need exclusive access to VM and non-VM
195resources at the same time. It's not clear if this is a real concern.
196
197There are (at least) two ways to handle the incoming signals:
198
199 (a) Always accept signals. If we're in a critical section, the signal
200 handler just returns without doing anything (the "suspend level"
201 should have been incremented before the signal was sent). Otherwise,
202 if the "suspend level" is nonzero, we go to sleep.
203 (b) Block signals in critical sections. This ensures that we can't be
204 interrupted in a critical section, but requires pthread_sigmask()
205 calls on entry and exit.
206
207This is a choice between blocking the message and blocking the messenger.
208Because UNIX signals are unreliable (you can only know that you have been
209signaled, not whether you were signaled once or 10 times), the choice is
210not significant for correctness. The choice depends on the efficiency
211of pthread_sigmask() and the desire to actually block signals. Either way,
212it is best to ensure that there is only one indication of "blocked";
213having two (i.e. block signals and set a flag, then only send a signal
214if the flag isn't set) can lead to race conditions.
215
216The signal handler must take care to copy registers onto the stack (via
217setjmp), so that stack scans find all references. Because we have to scan
218native stacks, "exact" GC is not possible with this approach.
219
220Some other concerns with flinging signals around:
221 - Odd interactions with some debuggers (e.g. gdb on the Mac)
222 - Restrictions on some standard library calls during GC (e.g. don't
223 use printf on stdout to print GC debug messages)
224*/
225
Carl Shapiro59a93122010-01-26 17:12:51 -0800226#define kMaxThreadId ((1 << 16) - 1)
227#define kMainThreadId 1
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800228
229
230static Thread* allocThread(int interpStackSize);
231static bool prepareThread(Thread* thread);
232static void setThreadSelf(Thread* thread);
233static void unlinkThread(Thread* thread);
234static void freeThread(Thread* thread);
235static void assignThreadId(Thread* thread);
236static bool createFakeEntryFrame(Thread* thread);
237static bool createFakeRunFrame(Thread* thread);
238static void* interpThreadStart(void* arg);
239static void* internalThreadStart(void* arg);
240static void threadExitUncaughtException(Thread* thread, Object* group);
241static void threadExitCheck(void* arg);
242static void waitForThreadSuspend(Thread* self, Thread* thread);
243static int getThreadPriorityFromSystem(void);
244
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700245/*
246 * The JIT needs to know if any thread is suspended. We do this by
247 * maintaining a global sum of all threads' suspend counts. All suspendCount
248 * updates should go through this after aquiring threadSuspendCountLock.
249 */
250static inline void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
251{
252 *pSuspendCount += delta;
253 gDvm.sumThreadSuspendCount += delta;
254}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800255
256/*
257 * Initialize thread list and main thread's environment. We need to set
258 * up some basic stuff so that dvmThreadSelf() will work when we start
259 * loading classes (e.g. to check for exceptions).
260 */
261bool dvmThreadStartup(void)
262{
263 Thread* thread;
264
265 /* allocate a TLS slot */
266 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
267 LOGE("ERROR: pthread_key_create failed\n");
268 return false;
269 }
270
271 /* test our pthread lib */
272 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
273 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
274
275 /* prep thread-related locks and conditions */
276 dvmInitMutex(&gDvm.threadListLock);
277 pthread_cond_init(&gDvm.threadStartCond, NULL);
278 //dvmInitMutex(&gDvm.vmExitLock);
279 pthread_cond_init(&gDvm.vmExitCond, NULL);
280 dvmInitMutex(&gDvm._threadSuspendLock);
281 dvmInitMutex(&gDvm.threadSuspendCountLock);
282 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
283#ifdef WITH_DEADLOCK_PREDICTION
284 dvmInitMutex(&gDvm.deadlockHistoryLock);
285#endif
286
287 /*
288 * Dedicated monitor for Thread.sleep().
289 * TODO: change this to an Object* so we don't have to expose this
290 * call, and we interact better with JDWP monitor calls. Requires
291 * deferring the object creation to much later (e.g. final "main"
292 * thread prep) or until first use.
293 */
294 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
295
296 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
297
298 thread = allocThread(gDvm.stackSize);
299 if (thread == NULL)
300 return false;
301
302 /* switch mode for when we run initializers */
303 thread->status = THREAD_RUNNING;
304
305 /*
306 * We need to assign the threadId early so we can lock/notify
307 * object monitors. We'll set the "threadObj" field later.
308 */
309 prepareThread(thread);
310 gDvm.threadList = thread;
311
312#ifdef COUNT_PRECISE_METHODS
313 gDvm.preciseMethods = dvmPointerSetAlloc(200);
314#endif
315
316 return true;
317}
318
319/*
320 * We're a little farther up now, and can load some basic classes.
321 *
322 * We're far enough along that we can poke at java.lang.Thread and friends,
323 * but should not assume that static initializers have run (or cause them
324 * to do so). That means no object allocations yet.
325 */
326bool dvmThreadObjStartup(void)
327{
328 /*
329 * Cache the locations of these classes. It's likely that we're the
330 * first to reference them, so they're being loaded now.
331 */
332 gDvm.classJavaLangThread =
333 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
334 gDvm.classJavaLangVMThread =
335 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
336 gDvm.classJavaLangThreadGroup =
337 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
338 if (gDvm.classJavaLangThread == NULL ||
339 gDvm.classJavaLangThreadGroup == NULL ||
340 gDvm.classJavaLangThreadGroup == NULL)
341 {
342 LOGE("Could not find one or more essential thread classes\n");
343 return false;
344 }
345
346 /*
347 * Cache field offsets. This makes things a little faster, at the
348 * expense of hard-coding non-public field names into the VM.
349 */
350 gDvm.offJavaLangThread_vmThread =
351 dvmFindFieldOffset(gDvm.classJavaLangThread,
352 "vmThread", "Ljava/lang/VMThread;");
353 gDvm.offJavaLangThread_group =
354 dvmFindFieldOffset(gDvm.classJavaLangThread,
355 "group", "Ljava/lang/ThreadGroup;");
356 gDvm.offJavaLangThread_daemon =
357 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
358 gDvm.offJavaLangThread_name =
359 dvmFindFieldOffset(gDvm.classJavaLangThread,
360 "name", "Ljava/lang/String;");
361 gDvm.offJavaLangThread_priority =
362 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
363
364 if (gDvm.offJavaLangThread_vmThread < 0 ||
365 gDvm.offJavaLangThread_group < 0 ||
366 gDvm.offJavaLangThread_daemon < 0 ||
367 gDvm.offJavaLangThread_name < 0 ||
368 gDvm.offJavaLangThread_priority < 0)
369 {
370 LOGE("Unable to find all fields in java.lang.Thread\n");
371 return false;
372 }
373
374 gDvm.offJavaLangVMThread_thread =
375 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
376 "thread", "Ljava/lang/Thread;");
377 gDvm.offJavaLangVMThread_vmData =
378 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
379 if (gDvm.offJavaLangVMThread_thread < 0 ||
380 gDvm.offJavaLangVMThread_vmData < 0)
381 {
382 LOGE("Unable to find all fields in java.lang.VMThread\n");
383 return false;
384 }
385
386 /*
387 * Cache the vtable offset for "run()".
388 *
389 * We don't want to keep the Method* because then we won't find see
390 * methods defined in subclasses.
391 */
392 Method* meth;
393 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
394 if (meth == NULL) {
395 LOGE("Unable to find run() in java.lang.Thread\n");
396 return false;
397 }
398 gDvm.voffJavaLangThread_run = meth->methodIndex;
399
400 /*
401 * Cache vtable offsets for ThreadGroup methods.
402 */
403 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
404 "removeThread", "(Ljava/lang/Thread;)V");
405 if (meth == NULL) {
406 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
407 return false;
408 }
409 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
410
411 return true;
412}
413
414/*
415 * All threads should be stopped by now. Clean up some thread globals.
416 */
417void dvmThreadShutdown(void)
418{
419 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700420 /*
421 * If we walk through the thread list and try to free the
422 * lingering thread structures (which should only be for daemon
423 * threads), the daemon threads may crash if they execute before
424 * the process dies. Let them leak.
425 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800426 freeThread(gDvm.threadList);
427 gDvm.threadList = NULL;
428 }
429
430 dvmFreeBitVector(gDvm.threadIdMap);
431
432 dvmFreeMonitorList();
433
434 pthread_key_delete(gDvm.pthreadKeySelf);
435}
436
437
438/*
439 * Grab the suspend count global lock.
440 */
441static inline void lockThreadSuspendCount(void)
442{
443 /*
444 * Don't try to change to VMWAIT here. When we change back to RUNNING
445 * we have to check for a pending suspend, which results in grabbing
446 * this lock recursively. Doesn't work with "fast" pthread mutexes.
447 *
448 * This lock is always held for very brief periods, so as long as
449 * mutex ordering is respected we shouldn't stall.
450 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700451 dvmLockMutex(&gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800452}
453
454/*
455 * Release the suspend count global lock.
456 */
457static inline void unlockThreadSuspendCount(void)
458{
459 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
460}
461
462/*
463 * Grab the thread list global lock.
464 *
465 * This is held while "suspend all" is trying to make everybody stop. If
466 * the shutdown is in progress, and somebody tries to grab the lock, they'll
467 * have to wait for the GC to finish. Therefore it's important that the
468 * thread not be in RUNNING mode.
469 *
470 * We don't have to check to see if we should be suspended once we have
471 * the lock. Nobody can suspend all threads without holding the thread list
472 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700473 *
Andy McFadden3469a7e2010-08-04 16:09:10 -0700474 * This function deliberately avoids the use of dvmChangeStatus(),
475 * which could grab threadSuspendCountLock. To avoid deadlock, threads
476 * are required to grab the thread list lock before the thread suspend
477 * count lock. (See comment in DvmGlobals.)
478 *
Andy McFadden44860362009-08-06 17:56:14 -0700479 * TODO: consider checking for suspend after acquiring the lock, and
480 * backing off if set. As stated above, it can't happen during normal
481 * execution, but it *can* happen during shutdown when daemon threads
482 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800483 */
484void dvmLockThreadList(Thread* self)
485{
486 ThreadStatus oldStatus;
487
488 if (self == NULL) /* try to get it from TLS */
489 self = dvmThreadSelf();
490
491 if (self != NULL) {
492 oldStatus = self->status;
493 self->status = THREAD_VMWAIT;
494 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700495 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800496 //LOGW("NULL self in dvmLockThreadList\n");
497 oldStatus = -1; // shut up gcc
498 }
499
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700500 dvmLockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800501
502 if (self != NULL)
503 self->status = oldStatus;
504}
505
506/*
Andy McFaddend19988d2010-10-22 13:32:12 -0700507 * Try to lock the thread list.
508 *
509 * Returns "true" if we locked it. This is a "fast" mutex, so if the
510 * current thread holds the lock this will fail.
511 */
512bool dvmTryLockThreadList(void)
513{
514 return (dvmTryLockMutex(&gDvm.threadListLock) == 0);
515}
516
517/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800518 * Release the thread list global lock.
519 */
520void dvmUnlockThreadList(void)
521{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700522 dvmUnlockMutex(&gDvm.threadListLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800523}
524
The Android Open Source Project99409882009-03-18 22:20:24 -0700525/*
526 * Convert SuspendCause to a string.
527 */
528static const char* getSuspendCauseStr(SuspendCause why)
529{
530 switch (why) {
531 case SUSPEND_NOT: return "NOT?";
532 case SUSPEND_FOR_GC: return "gc";
533 case SUSPEND_FOR_DEBUG: return "debug";
534 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
535 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700536 case SUSPEND_FOR_VERIFY: return "verify";
Ben Chenga8e64a72009-10-20 13:01:36 -0700537#if defined(WITH_JIT)
538 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
539 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800540 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800541 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700542#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700543 default: return "UNKNOWN";
544 }
545}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546
547/*
548 * Grab the "thread suspend" lock. This is required to prevent the
549 * GC and the debugger from simultaneously suspending all threads.
550 *
551 * If we fail to get the lock, somebody else is trying to suspend all
552 * threads -- including us. If we go to sleep on the lock we'll deadlock
553 * the VM. Loop until we get it or somebody puts us to sleep.
554 */
555static void lockThreadSuspend(const char* who, SuspendCause why)
556{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800557 const int kSpinSleepTime = 3*1000*1000; /* 3s */
558 u8 startWhen = 0; // init req'd to placate gcc
559 int sleepIter = 0;
560 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700561
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800562 do {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700563 cc = dvmTryLockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800564 if (cc != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700565 Thread* self = dvmThreadSelf();
566
567 if (!dvmCheckSuspendPending(self)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800568 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700569 * Could be that a resume-all is in progress, and something
570 * grabbed the CPU when the wakeup was broadcast. The thread
571 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700572 * thread suspend lock. (We release before the broadcast,
573 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700574 *
575 * Could be we hit the window as a suspend was started,
576 * and the lock has been grabbed but the suspend counts
577 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700578 *
579 * Could be an unusual JNI thread-attach thing.
580 *
581 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800582 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700583 *
584 * Could be two app threads both want to patch predicted
585 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800586 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700587 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
588 " it's held, no suspend pending\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700589 self->threadId, who, getSuspendCauseStr(why));
The Android Open Source Project99409882009-03-18 22:20:24 -0700590 } else {
591 /* we suspended; reset timeout */
592 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800593 }
594
595 /* give the lock-holder a chance to do some work */
596 if (sleepIter == 0)
597 startWhen = dvmGetRelativeTimeUsec();
598 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700599 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800600 " bailing\n",
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700601 self->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700602 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800603 dvmDumpAllThreads(false);
604 dvmAbort();
605 }
606 }
607 } while (cc != 0);
608 assert(cc == 0);
609}
610
611/*
612 * Release the "thread suspend" lock.
613 */
614static inline void unlockThreadSuspend(void)
615{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -0700616 dvmUnlockMutex(&gDvm._threadSuspendLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800617}
618
619
620/*
621 * Kill any daemon threads that still exist. All of ours should be
622 * stopped, so these should be Thread objects or JNI-attached threads
623 * started by the application. Actively-running threads are likely
624 * to crash the process if they continue to execute while the VM
625 * shuts down, so we really need to kill or suspend them. (If we want
626 * the VM to restart within this process, we need to kill them, but that
627 * leaves open the possibility of orphaned resources.)
628 *
629 * Waiting for the thread to suspend may be unwise at this point, but
630 * if one of these is wedged in a critical section then we probably
631 * would've locked up on the last GC attempt.
632 *
633 * It's possible for this function to get called after a failed
634 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700635 *
636 * This will be called from whatever thread calls DestroyJavaVM, usually
637 * but not necessarily the main thread. It's likely, but not guaranteed,
638 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800639 */
640void dvmSlayDaemons(void)
641{
Andy McFadden44860362009-08-06 17:56:14 -0700642 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800643 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700644 int threadId = 0;
645 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800646
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800647 dvmLockThreadList(self);
648
Andy McFadden44860362009-08-06 17:56:14 -0700649 if (self != NULL)
650 threadId = self->threadId;
651
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800652 target = gDvm.threadList;
653 while (target != NULL) {
654 if (target == self) {
655 target = target->next;
656 continue;
657 }
658
659 if (!dvmGetFieldBoolean(target->threadObj,
660 gDvm.offJavaLangThread_daemon))
661 {
Andy McFadden44860362009-08-06 17:56:14 -0700662 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800663 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700664 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800665 }
666
Andy McFadden44860362009-08-06 17:56:14 -0700667 char* threadName = dvmGetThreadName(target);
668 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
669 threadId, target->threadId, threadName);
670 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800671
Andy McFadden44860362009-08-06 17:56:14 -0700672 /* mark as suspended */
673 lockThreadSuspendCount();
674 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
675 unlockThreadSuspendCount();
676 doWait = true;
677
678 target = target->next;
679 }
680
681 //dvmDumpAllThreads(false);
682
683 /*
684 * Unlock the thread list, relocking it later if necessary. It's
685 * possible a thread is in VMWAIT after calling dvmLockThreadList,
686 * and that function *doesn't* check for pending suspend after
687 * acquiring the lock. We want to let them finish their business
688 * and see the pending suspend before we continue here.
689 *
690 * There's no guarantee of mutex fairness, so this might not work.
691 * (The alternative is to have dvmLockThreadList check for suspend
692 * after acquiring the lock and back off, something we should consider.)
693 */
694 dvmUnlockThreadList();
695
696 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800697 bool complained = false;
698
Andy McFadden44860362009-08-06 17:56:14 -0700699 usleep(200 * 1000);
700
701 dvmLockThreadList(self);
702
703 /*
704 * Sleep for a bit until the threads have suspended. We're trying
705 * to exit, so don't wait for too long.
706 */
707 int i;
708 for (i = 0; i < 10; i++) {
709 bool allSuspended = true;
710
711 target = gDvm.threadList;
712 while (target != NULL) {
713 if (target == self) {
714 target = target->next;
715 continue;
716 }
717
Andy McFadden6dce9962010-08-23 16:45:24 -0700718 if (target->status == THREAD_RUNNING) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800719 if (!complained)
720 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700721 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800722 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700723 }
724
725 target = target->next;
726 }
727
728 if (allSuspended) {
729 LOGD("threadid=%d: all daemons have suspended\n", threadId);
730 break;
731 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800732 if (!complained) {
733 complained = true;
734 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
735 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800736 }
Andy McFadden44860362009-08-06 17:56:14 -0700737 }
738
739 usleep(200 * 1000);
740 }
741 dvmUnlockThreadList();
742 }
743
744#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
745 /*
746 * Abandon the threads and recover their resources.
747 */
748 target = gDvm.threadList;
749 while (target != NULL) {
750 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800751 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800752 freeThread(target);
753 target = nextTarget;
754 }
Andy McFadden44860362009-08-06 17:56:14 -0700755#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800756
Andy McFadden44860362009-08-06 17:56:14 -0700757 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800758}
759
760
761/*
762 * Finish preparing the parts of the Thread struct required to support
763 * JNI registration.
764 */
765bool dvmPrepMainForJni(JNIEnv* pEnv)
766{
767 Thread* self;
768
769 /* main thread is always first in list at this point */
770 self = gDvm.threadList;
771 assert(self->threadId == kMainThreadId);
772
773 /* create a "fake" JNI frame at the top of the main thread interp stack */
774 if (!createFakeEntryFrame(self))
775 return false;
776
777 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
778 dvmSetJniEnvThreadId(pEnv, self);
779 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
780
781 return true;
782}
783
784
785/*
786 * Finish preparing the main thread, allocating some objects to represent
787 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700788 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800789 */
790bool dvmPrepMainThread(void)
791{
792 Thread* thread;
793 Object* groupObj;
794 Object* threadObj;
795 Object* vmThreadObj;
796 StringObject* threadNameStr;
797 Method* init;
798 JValue unused;
799
800 LOGV("+++ finishing prep on main VM thread\n");
801
802 /* main thread is always first in list at this point */
803 thread = gDvm.threadList;
804 assert(thread->threadId == kMainThreadId);
805
806 /*
807 * Make sure the classes are initialized. We have to do this before
808 * we create an instance of them.
809 */
810 if (!dvmInitClass(gDvm.classJavaLangClass)) {
811 LOGE("'Class' class failed to initialize\n");
812 return false;
813 }
814 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
815 !dvmInitClass(gDvm.classJavaLangThread) ||
816 !dvmInitClass(gDvm.classJavaLangVMThread))
817 {
818 LOGE("thread classes failed to initialize\n");
819 return false;
820 }
821
822 groupObj = dvmGetMainThreadGroup();
823 if (groupObj == NULL)
824 return false;
825
826 /*
827 * Allocate and construct a Thread with the internal-creation
828 * constructor.
829 */
830 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
831 if (threadObj == NULL) {
832 LOGE("unable to allocate main thread object\n");
833 return false;
834 }
835 dvmReleaseTrackedAlloc(threadObj, NULL);
836
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700837 threadNameStr = dvmCreateStringFromCstr("main");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800838 if (threadNameStr == NULL)
839 return false;
840 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
841
842 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
843 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
844 assert(init != NULL);
845 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
846 THREAD_NORM_PRIORITY, false);
847 if (dvmCheckException(thread)) {
848 LOGE("exception thrown while constructing main thread object\n");
849 return false;
850 }
851
852 /*
853 * Allocate and construct a VMThread.
854 */
855 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
856 if (vmThreadObj == NULL) {
857 LOGE("unable to allocate main vmthread object\n");
858 return false;
859 }
860 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
861
862 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
863 "(Ljava/lang/Thread;)V");
864 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
865 if (dvmCheckException(thread)) {
866 LOGE("exception thrown while constructing main vmthread object\n");
867 return false;
868 }
869
870 /* set the VMThread.vmData field to our Thread struct */
871 assert(gDvm.offJavaLangVMThread_vmData != 0);
872 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
873
874 /*
875 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700876 * Threads will see that this Thread is running (at least, they would,
877 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800878 */
879 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
880 vmThreadObj);
881
882 thread->threadObj = threadObj;
883
884 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700885 * Set the context class loader. This invokes a ClassLoader method,
886 * which could conceivably call Thread.currentThread(), so we want the
887 * Thread to be fully configured before we do this.
888 */
889 Object* systemLoader = dvmGetSystemClassLoader();
890 if (systemLoader == NULL) {
891 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
892 /* keep going */
893 }
894 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
895 "contextClassLoader", "Ljava/lang/ClassLoader;");
896 if (ctxtClassLoaderOffset < 0) {
897 LOGE("Unable to find contextClassLoader field in Thread\n");
898 return false;
899 }
900 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
Andy McFadden50cab512010-10-07 15:11:43 -0700901 dvmReleaseTrackedAlloc(systemLoader, NULL);
Andy McFaddena1a7a342009-05-04 13:29:30 -0700902
903 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800904 * Finish our thread prep.
905 */
906
907 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
908 gDvm.nonDaemonThreadCount++;
909
910 return true;
911}
912
913
914/*
915 * Alloc and initialize a Thread struct.
916 *
Andy McFaddene3346d82010-06-02 15:37:21 -0700917 * Does not create any objects, just stuff on the system (malloc) heap.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800918 */
919static Thread* allocThread(int interpStackSize)
920{
921 Thread* thread;
922 u1* stackBottom;
923
924 thread = (Thread*) calloc(1, sizeof(Thread));
925 if (thread == NULL)
926 return NULL;
927
Jeff Hao97319a82009-08-12 16:57:15 -0700928#if defined(WITH_SELF_VERIFICATION)
929 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
930 return NULL;
931#endif
932
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800933 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
934
935 thread->status = THREAD_INITIALIZING;
936 thread->suspendCount = 0;
937
938#ifdef WITH_ALLOC_LIMITS
939 thread->allocLimit = -1;
940#endif
941
942 /*
943 * Allocate and initialize the interpreted code stack. We essentially
944 * "lose" the alloc pointer, which points at the bottom of the stack,
945 * but we can get it back later because we know how big the stack is.
946 *
947 * The stack must be aligned on a 4-byte boundary.
948 */
949#ifdef MALLOC_INTERP_STACK
950 stackBottom = (u1*) malloc(interpStackSize);
951 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700952#if defined(WITH_SELF_VERIFICATION)
953 dvmSelfVerificationShadowSpaceFree(thread);
954#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800955 free(thread);
956 return NULL;
957 }
958 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
959#else
960 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
961 MAP_PRIVATE | MAP_ANON, -1, 0);
962 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700963#if defined(WITH_SELF_VERIFICATION)
964 dvmSelfVerificationShadowSpaceFree(thread);
965#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800966 free(thread);
967 return NULL;
968 }
969#endif
970
971 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
972 thread->interpStackSize = interpStackSize;
973 thread->interpStackStart = stackBottom + interpStackSize;
974 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
975
976 /* give the thread code a chance to set things up */
977 dvmInitInterpStack(thread, interpStackSize);
978
979 return thread;
980}
981
982/*
983 * Get a meaningful thread ID. At present this only has meaning under Linux,
984 * where getpid() and gettid() sometimes agree and sometimes don't depending
985 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
986 */
987pid_t dvmGetSysThreadId(void)
988{
989#ifdef HAVE_GETTID
990 return gettid();
991#else
992 return getpid();
993#endif
994}
995
996/*
997 * Finish initialization of a Thread struct.
998 *
999 * This must be called while executing in the new thread, but before the
1000 * thread is added to the thread list.
1001 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001002 * NOTE: The threadListLock must be held by the caller (needed for
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001003 * assignThreadId()).
1004 */
1005static bool prepareThread(Thread* thread)
1006{
1007 assignThreadId(thread);
1008 thread->handle = pthread_self();
1009 thread->systemTid = dvmGetSysThreadId();
1010
1011 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1012 // (int) getpid());
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001013 /*
1014 * If we were called by dvmAttachCurrentThread, the self value is
1015 * already correctly established as "thread".
1016 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001017 setThreadSelf(thread);
1018
1019 LOGV("threadid=%d: interp stack at %p\n",
1020 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1021
1022 /*
1023 * Initialize invokeReq.
1024 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001025 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001026 pthread_cond_init(&thread->invokeReq.cv, NULL);
1027
1028 /*
1029 * Initialize our reference tracking tables.
1030 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001031 * Most threads won't use jniMonitorRefTable, so we clear out the
1032 * structure but don't call the init function (which allocs storage).
1033 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001034#ifdef USE_INDIRECT_REF
1035 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1036 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1037 return false;
1038#else
1039 /*
1040 * The JNI local ref table *must* be fixed-size because we keep pointers
1041 * into the table in our stack frames.
1042 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001043 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1044 kJniLocalRefMax, kJniLocalRefMax))
1045 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001046#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001047 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1048 kInternalRefDefault, kInternalRefMax))
1049 return false;
1050
1051 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1052
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001053 pthread_cond_init(&thread->waitCond, NULL);
1054 dvmInitMutex(&thread->waitMutex);
1055
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001056 return true;
1057}
1058
1059/*
1060 * Remove a thread from the internal list.
1061 * Clear out the links to make it obvious that the thread is
1062 * no longer on the list. Caller must hold gDvm.threadListLock.
1063 */
1064static void unlinkThread(Thread* thread)
1065{
1066 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1067 if (thread == gDvm.threadList) {
1068 assert(thread->prev == NULL);
1069 gDvm.threadList = thread->next;
1070 } else {
1071 assert(thread->prev != NULL);
1072 thread->prev->next = thread->next;
1073 }
1074 if (thread->next != NULL)
1075 thread->next->prev = thread->prev;
1076 thread->prev = thread->next = NULL;
1077}
1078
1079/*
1080 * Free a Thread struct, and all the stuff allocated within.
1081 */
1082static void freeThread(Thread* thread)
1083{
1084 if (thread == NULL)
1085 return;
1086
1087 /* thread->threadId is zero at this point */
1088 LOGVV("threadid=%d: freeing\n", thread->threadId);
1089
1090 if (thread->interpStackStart != NULL) {
1091 u1* interpStackBottom;
1092
1093 interpStackBottom = thread->interpStackStart;
1094 interpStackBottom -= thread->interpStackSize;
1095#ifdef MALLOC_INTERP_STACK
1096 free(interpStackBottom);
1097#else
1098 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1099 LOGW("munmap(thread stack) failed\n");
1100#endif
1101 }
1102
Andy McFaddend5ab7262009-08-25 07:19:34 -07001103#ifdef USE_INDIRECT_REF
1104 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1105#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001106 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001107#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001108 dvmClearReferenceTable(&thread->internalLocalRefTable);
1109 if (&thread->jniMonitorRefTable.table != NULL)
1110 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1111
Jeff Hao97319a82009-08-12 16:57:15 -07001112#if defined(WITH_SELF_VERIFICATION)
1113 dvmSelfVerificationShadowSpaceFree(thread);
1114#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001115 free(thread);
1116}
1117
1118/*
1119 * Like pthread_self(), but on a Thread*.
1120 */
1121Thread* dvmThreadSelf(void)
1122{
1123 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1124}
1125
1126/*
1127 * Explore our sense of self. Stuffs the thread pointer into TLS.
1128 */
1129static void setThreadSelf(Thread* thread)
1130{
1131 int cc;
1132
1133 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1134 if (cc != 0) {
1135 /*
1136 * Sometimes this fails under Bionic with EINVAL during shutdown.
1137 * This can happen if the timing is just right, e.g. a thread
1138 * fails to attach during shutdown, but the "fail" path calls
1139 * here to ensure we clean up after ourselves.
1140 */
1141 if (thread != NULL) {
1142 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1143 dvmAbort(); /* the world is fundamentally hosed */
1144 }
1145 }
1146}
1147
1148/*
1149 * This is associated with the pthreadKeySelf key. It's called by the
1150 * pthread library when a thread is exiting and the "self" pointer in TLS
1151 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001152 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001153 *
1154 * This is mainly of use to ensure that we don't leak resources if, for
1155 * example, a thread attaches itself to us with AttachCurrentThread and
1156 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001157 *
1158 * We could do the detach here instead of aborting, but this will lead to
1159 * portability problems. Other implementations do not do this check and
1160 * will simply be unaware that the thread has exited, leading to resource
1161 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1162 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001163 *
1164 * Because some implementations may want to use the pthread destructor
1165 * to initiate the detach, and the ordering of destructors is not defined,
1166 * 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 -08001167 */
1168static void threadExitCheck(void* arg)
1169{
Andy McFadden909ce242009-12-10 16:38:30 -08001170 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001171
Andy McFadden909ce242009-12-10 16:38:30 -08001172 Thread* self = (Thread*) arg;
1173 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001174
Andy McFadden909ce242009-12-10 16:38:30 -08001175 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1176 self->threadId, arg, self->threadExitCheckCount);
1177
1178 if (self->status == THREAD_ZOMBIE) {
1179 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1180 self->threadId);
1181 return;
1182 }
1183
1184 if (self->threadExitCheckCount < kMaxCount) {
1185 /*
1186 * Spin a couple of times to let other destructors fire.
1187 */
1188 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1189 self->threadId, self->threadExitCheckCount);
1190 self->threadExitCheckCount++;
1191 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1192 if (cc != 0) {
1193 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1194 self->threadId);
1195 dvmAbort();
1196 }
1197 } else {
1198 LOGE("threadid=%d: native thread exited without detaching\n",
1199 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001200 dvmAbort();
1201 }
1202}
1203
1204
1205/*
1206 * Assign the threadId. This needs to be a small integer so that our
1207 * "thin" locks fit in a small number of bits.
1208 *
1209 * We reserve zero for use as an invalid ID.
1210 *
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001211 * This must be called with threadListLock held.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001212 */
1213static void assignThreadId(Thread* thread)
1214{
Carl Shapiro59a93122010-01-26 17:12:51 -08001215 /*
1216 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001217 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1218 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001219 */
1220 int num = dvmAllocBit(gDvm.threadIdMap);
1221 if (num < 0) {
1222 LOGE("Ran out of thread IDs\n");
1223 dvmAbort(); // TODO: make this a non-fatal error result
1224 }
1225
Carl Shapiro59a93122010-01-26 17:12:51 -08001226 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001227
1228 assert(thread->threadId != 0);
1229 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1230}
1231
1232/*
1233 * Give back the thread ID.
1234 */
1235static void releaseThreadId(Thread* thread)
1236{
1237 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001238 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001239 thread->threadId = 0;
1240}
1241
1242
1243/*
1244 * Add a stack frame that makes it look like the native code in the main
1245 * thread was originally invoked from interpreted code. This gives us a
1246 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1247 * VM begins by executing "main" in a class, so in a way this brings us
1248 * closer to the spec.
1249 */
1250static bool createFakeEntryFrame(Thread* thread)
1251{
1252 assert(thread->threadId == kMainThreadId); // main thread only
1253
1254 /* find the method on first use */
1255 if (gDvm.methFakeNativeEntry == NULL) {
1256 ClassObject* nativeStart;
1257 Method* mainMeth;
1258
1259 nativeStart = dvmFindSystemClassNoInit(
1260 "Ldalvik/system/NativeStart;");
1261 if (nativeStart == NULL) {
1262 LOGE("Unable to find dalvik.system.NativeStart class\n");
1263 return false;
1264 }
1265
1266 /*
1267 * Because we are creating a frame that represents application code, we
1268 * want to stuff the application class loader into the method's class
1269 * loader field, even though we're using the system class loader to
1270 * load it. This makes life easier over in JNI FindClass (though it
1271 * could bite us in other ways).
1272 *
1273 * Unfortunately this is occurring too early in the initialization,
1274 * of necessity coming before JNI is initialized, and we're not quite
1275 * ready to set up the application class loader.
1276 *
1277 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1278 * and check it in FindClass. The method is private so nobody else
1279 * can call it.
1280 */
1281 //nativeStart->classLoader = dvmGetSystemClassLoader();
1282
1283 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1284 "main", "([Ljava/lang/String;)V");
1285 if (mainMeth == NULL) {
1286 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1287 return false;
1288 }
1289
1290 gDvm.methFakeNativeEntry = mainMeth;
1291 }
1292
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001293 if (!dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry))
1294 return false;
1295
1296 /*
1297 * Null out the "String[] args" argument.
1298 */
1299 assert(gDvm.methFakeNativeEntry->registersSize == 1);
1300 u4* framePtr = (u4*) thread->curFrame;
1301 framePtr[0] = 0;
1302
1303 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001304}
1305
1306
1307/*
1308 * Add a stack frame that makes it look like the native thread has been
1309 * executing interpreted code. This gives us a place to hang JNI local
1310 * references.
1311 */
1312static bool createFakeRunFrame(Thread* thread)
1313{
1314 ClassObject* nativeStart;
1315 Method* runMeth;
1316
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001317 /*
1318 * TODO: cache this result so we don't have to dig for it every time
1319 * somebody attaches a thread to the VM. Also consider changing this
1320 * to a static method so we don't have a null "this" pointer in the
1321 * "ins" on the stack. (Does it really need to look like a Runnable?)
1322 */
1323 nativeStart = dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001324 if (nativeStart == NULL) {
1325 LOGE("Unable to find dalvik.system.NativeStart class\n");
1326 return false;
1327 }
1328
1329 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1330 if (runMeth == NULL) {
1331 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1332 return false;
1333 }
1334
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001335 if (!dvmPushJNIFrame(thread, runMeth))
1336 return false;
1337
1338 /*
1339 * Provide a NULL 'this' argument. The method we've put at the top of
1340 * the stack looks like a virtual call to run() in a Runnable class.
1341 * (If we declared the method static, it wouldn't take any arguments
1342 * and we wouldn't have to do this.)
1343 */
1344 assert(runMeth->registersSize == 1);
1345 u4* framePtr = (u4*) thread->curFrame;
1346 framePtr[0] = 0;
1347
1348 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001349}
1350
1351/*
1352 * Helper function to set the name of the current thread
1353 */
1354static void setThreadName(const char *threadName)
1355{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001356 int hasAt = 0;
1357 int hasDot = 0;
1358 const char *s = threadName;
1359 while (*s) {
1360 if (*s == '.') hasDot = 1;
1361 else if (*s == '@') hasAt = 1;
1362 s++;
1363 }
1364 int len = s - threadName;
1365 if (len < 15 || hasAt || !hasDot) {
1366 s = threadName;
1367 } else {
1368 s = threadName + len - 15;
1369 }
Andy McFadden22ec6092010-07-01 11:23:15 -07001370#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001371 /* pthread_setname_np fails rather than truncating long strings */
1372 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1373 strncpy(buf, s, sizeof(buf)-1);
1374 buf[sizeof(buf)-1] = '\0';
1375 int err = pthread_setname_np(pthread_self(), buf);
1376 if (err != 0) {
1377 LOGW("Unable to set the name of current thread to '%s': %s\n",
1378 buf, strerror(err));
1379 }
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001380#elif defined(HAVE_PRCTL)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001381 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
André Goddard Rosabcd88cc2010-06-09 20:32:14 -03001382#else
Andy McFaddenb122c8b2010-07-08 15:43:19 -07001383 LOGD("No way to set current thread's name (%s)\n", s);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001384#endif
1385}
1386
1387/*
1388 * Create a thread as a result of java.lang.Thread.start().
1389 *
1390 * We do have to worry about some concurrency problems, e.g. programs
1391 * that try to call Thread.start() on the same object from multiple threads.
1392 * (This will fail for all but one, but we have to make sure that it succeeds
1393 * for exactly one.)
1394 *
1395 * Some of the complexity here arises from our desire to mimic the
1396 * Thread vs. VMThread class decomposition we inherited. We've been given
1397 * a Thread, and now we need to create a VMThread and then populate both
1398 * objects. We also need to create one of our internal Thread objects.
1399 *
1400 * Pass in a stack size of 0 to get the default.
Andy McFaddene3346d82010-06-02 15:37:21 -07001401 *
1402 * The "threadObj" reference must be pinned by the caller to prevent the GC
1403 * from moving it around (e.g. added to the tracked allocation list).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001404 */
1405bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1406{
1407 pthread_attr_t threadAttr;
1408 pthread_t threadHandle;
1409 Thread* self;
1410 Thread* newThread = NULL;
1411 Object* vmThreadObj = NULL;
1412 int stackSize;
1413
1414 assert(threadObj != NULL);
1415
1416 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001417 // Allow the sampling profiler thread. We shut it down before forking.
1418 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1419 gDvm.offJavaLangThread_name);
1420 char* threadName = dvmCreateCstrFromString(nameStr);
1421 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1422 free(threadName);
1423 if (!profilerThread) {
1424 dvmThrowException("Ljava/lang/IllegalStateException;",
1425 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001426
Bob Lee9dc72a32009-09-04 18:28:16 -07001427 goto fail;
1428 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001429 }
1430
1431 self = dvmThreadSelf();
1432 if (reqStackSize == 0)
1433 stackSize = gDvm.stackSize;
1434 else if (reqStackSize < kMinStackSize)
1435 stackSize = kMinStackSize;
1436 else if (reqStackSize > kMaxStackSize)
1437 stackSize = kMaxStackSize;
1438 else
1439 stackSize = reqStackSize;
1440
1441 pthread_attr_init(&threadAttr);
1442 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1443
1444 /*
1445 * To minimize the time spent in the critical section, we allocate the
1446 * vmThread object here.
1447 */
1448 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1449 if (vmThreadObj == NULL)
1450 goto fail;
1451
1452 newThread = allocThread(stackSize);
1453 if (newThread == NULL)
1454 goto fail;
1455 newThread->threadObj = threadObj;
1456
1457 assert(newThread->status == THREAD_INITIALIZING);
1458
1459 /*
1460 * We need to lock out other threads while we test and set the
1461 * "vmThread" field in java.lang.Thread, because we use that to determine
1462 * if this thread has been started before. We use the thread list lock
1463 * because it's handy and we're going to need to grab it again soon
1464 * anyway.
1465 */
1466 dvmLockThreadList(self);
1467
1468 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1469 dvmUnlockThreadList();
1470 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1471 "thread has already been started");
1472 goto fail;
1473 }
1474
1475 /*
1476 * There are actually three data structures: Thread (object), VMThread
1477 * (object), and Thread (C struct). All of them point to at least one
1478 * other.
1479 *
1480 * As soon as "VMThread.vmData" is assigned, other threads can start
1481 * making calls into us (e.g. setPriority).
1482 */
1483 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1484 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1485
1486 /*
1487 * Thread creation might take a while, so release the lock.
1488 */
1489 dvmUnlockThreadList();
1490
Carl Shapiro5617ad32010-07-02 10:50:57 -07001491 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1492 int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
Andy McFadden2aa43612009-06-17 16:29:30 -07001493 newThread);
1494 oldStatus = dvmChangeStatus(self, oldStatus);
1495
1496 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001497 /*
1498 * Failure generally indicates that we have exceeded system
1499 * resource limits. VirtualMachineError is probably too severe,
1500 * so use OutOfMemoryError.
1501 */
1502 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1503
1504 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1505
1506 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1507 "thread creation failed");
1508 goto fail;
1509 }
1510
1511 /*
1512 * We need to wait for the thread to start. Otherwise, depending on
1513 * the whims of the OS scheduler, we could return and the code in our
1514 * thread could try to do operations on the new thread before it had
1515 * finished starting.
1516 *
1517 * The new thread will lock the thread list, change its state to
1518 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1519 * on gDvm.threadStartCond (which uses the thread list lock). This
1520 * thread (the parent) will either see that the thread is already ready
1521 * after we grab the thread list lock, or will be awakened from the
1522 * condition variable on the broadcast.
1523 *
1524 * We don't want to stall the rest of the VM while the new thread
1525 * starts, which can happen if the GC wakes up at the wrong moment.
1526 * So, we change our own status to VMWAIT, and self-suspend if
1527 * necessary after we finish adding the new thread.
1528 *
1529 *
1530 * We have to deal with an odd race with the GC/debugger suspension
1531 * mechanism when creating a new thread. The information about whether
1532 * or not a thread should be suspended is contained entirely within
1533 * the Thread struct; this is usually cleaner to deal with than having
1534 * one or more globally-visible suspension flags. The trouble is that
1535 * we could create the thread while the VM is trying to suspend all
1536 * threads. The suspend-count won't be nonzero for the new thread,
1537 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1538 *
1539 * The easiest way to deal with this is to prevent the new thread from
1540 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001541 * following (correct) sequence of events for a "badly timed" GC
1542 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001543 *
1544 * - call pthread_create()
1545 * - lock thread list
1546 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1547 * - sleep on condition var (mutex = thread list lock) until child starts
1548 * + GC triggered by another thread
1549 * + thread list locked; suspend counts updated; thread list unlocked
1550 * + loop waiting for all runnable threads to suspend
1551 * + success, start GC
1552 * o child thread wakes, signals condition var to wake parent
1553 * o child waits for parent ack on condition variable
1554 * - we wake up, locking thread list
1555 * - add child to thread list
1556 * - unlock thread list
1557 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1558 * + GC finishes; all threads in thread list are resumed
1559 * - lock thread list
1560 * - set child to THREAD_VMWAIT, and signal it to start
1561 * - unlock thread list
1562 * o child resumes
1563 * o child changes state to THREAD_RUNNING
1564 *
1565 * The above shows the GC starting up during thread creation, but if
1566 * it starts anywhere after VMThread.create() is called it will
1567 * produce the same series of events.
1568 *
1569 * Once the child is in the thread list, it will be suspended and
1570 * resumed like any other thread. In the above scenario the resume-all
1571 * code will try to resume the new thread, which was never actually
1572 * suspended, and try to decrement the child's thread suspend count to -1.
1573 * We can catch this in the resume-all code.
1574 *
1575 * Bouncing back and forth between threads like this adds a small amount
1576 * of scheduler overhead to thread startup.
1577 *
1578 * One alternative to having the child wait for the parent would be
1579 * to have the child inherit the parents' suspension count. This
1580 * would work for a GC, since we can safely assume that the parent
1581 * thread didn't cause it, but we must only do so if the parent suspension
1582 * was caused by a suspend-all. If the parent was being asked to
1583 * suspend singly by the debugger, the child should not inherit the value.
1584 *
1585 * We could also have a global "new thread suspend count" that gets
1586 * picked up by new threads before changing state to THREAD_RUNNING.
1587 * This would be protected by the thread list lock and set by a
1588 * suspend-all.
1589 */
1590 dvmLockThreadList(self);
1591 assert(self->status == THREAD_RUNNING);
1592 self->status = THREAD_VMWAIT;
1593 while (newThread->status != THREAD_STARTING)
1594 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1595
1596 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1597 newThread->next = gDvm.threadList->next;
1598 if (newThread->next != NULL)
1599 newThread->next->prev = newThread;
1600 newThread->prev = gDvm.threadList;
1601 gDvm.threadList->next = newThread;
1602
1603 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1604 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1605
1606 dvmUnlockThreadList();
1607
1608 /* change status back to RUNNING, self-suspending if necessary */
1609 dvmChangeStatus(self, THREAD_RUNNING);
1610
1611 /*
1612 * Tell the new thread to start.
1613 *
1614 * We must hold the thread list lock before messing with another thread.
1615 * In the general case we would also need to verify that newThread was
1616 * still in the thread list, but in our case the thread has not started
1617 * executing user code and therefore has not had a chance to exit.
1618 *
1619 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1620 * comes with a suspend-pending check.
1621 */
1622 dvmLockThreadList(self);
1623
1624 assert(newThread->status == THREAD_STARTING);
1625 newThread->status = THREAD_VMWAIT;
1626 pthread_cond_broadcast(&gDvm.threadStartCond);
1627
1628 dvmUnlockThreadList();
1629
1630 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1631 return true;
1632
1633fail:
1634 freeThread(newThread);
1635 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1636 return false;
1637}
1638
1639/*
1640 * pthread entry function for threads started from interpreted code.
1641 */
1642static void* interpThreadStart(void* arg)
1643{
1644 Thread* self = (Thread*) arg;
1645
1646 char *threadName = dvmGetThreadName(self);
1647 setThreadName(threadName);
1648 free(threadName);
1649
1650 /*
1651 * Finish initializing the Thread struct.
1652 */
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07001653 dvmLockThreadList(self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001654 prepareThread(self);
1655
1656 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1657
1658 /*
1659 * Change our status and wake our parent, who will add us to the
1660 * thread list and advance our state to VMWAIT.
1661 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001662 self->status = THREAD_STARTING;
1663 pthread_cond_broadcast(&gDvm.threadStartCond);
1664
1665 /*
1666 * Wait until the parent says we can go. Assuming there wasn't a
1667 * suspend pending, this will happen immediately. When it completes,
1668 * we're full-fledged citizens of the VM.
1669 *
1670 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1671 * because the pthread_cond_wait below needs to reacquire a lock that
1672 * suspend-all is also interested in. If we get unlucky, the parent could
1673 * change us to THREAD_RUNNING, then a GC could start before we get
1674 * signaled, and suspend-all will grab the thread list lock and then
1675 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1676 * trying to get the lock.
1677 */
1678 while (self->status != THREAD_VMWAIT)
1679 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1680
1681 dvmUnlockThreadList();
1682
1683 /*
1684 * Add a JNI context.
1685 */
1686 self->jniEnv = dvmCreateJNIEnv(self);
1687
1688 /*
1689 * Change our state so the GC will wait for us from now on. If a GC is
1690 * in progress this call will suspend us.
1691 */
1692 dvmChangeStatus(self, THREAD_RUNNING);
1693
1694 /*
1695 * Notify the debugger & DDM. The debugger notification may cause
Andy McFadden2150b0d2010-10-15 13:54:28 -07001696 * us to suspend ourselves (and others). The thread state may change
1697 * to VMWAIT briefly if network packets are sent.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001698 */
1699 if (gDvm.debuggerConnected)
1700 dvmDbgPostThreadStart(self);
1701
1702 /*
1703 * Set the system thread priority according to the Thread object's
1704 * priority level. We don't usually need to do this, because both the
1705 * Thread object and system thread priorities inherit from parents. The
1706 * tricky case is when somebody creates a Thread object, calls
1707 * setPriority(), and then starts the thread. We could manage this with
1708 * a "needs priority update" flag to avoid the redundant call.
1709 */
Andy McFadden4879df92009-08-07 14:49:40 -07001710 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001711 gDvm.offJavaLangThread_priority);
1712 dvmChangeThreadPriority(self, priority);
1713
1714 /*
1715 * Execute the "run" method.
1716 *
1717 * At this point our stack is empty, so somebody who comes looking for
1718 * stack traces right now won't have much to look at. This is normal.
1719 */
1720 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1721 JValue unused;
1722
1723 LOGV("threadid=%d: calling run()\n", self->threadId);
1724 assert(strcmp(run->name, "run") == 0);
1725 dvmCallMethod(self, run, self->threadObj, &unused);
1726 LOGV("threadid=%d: exiting\n", self->threadId);
1727
1728 /*
1729 * Remove the thread from various lists, report its death, and free
1730 * its resources.
1731 */
1732 dvmDetachCurrentThread();
1733
1734 return NULL;
1735}
1736
1737/*
1738 * The current thread is exiting with an uncaught exception. The
1739 * Java programming language allows the application to provide a
1740 * thread-exit-uncaught-exception handler for the VM, for a specific
1741 * Thread, and for all threads in a ThreadGroup.
1742 *
1743 * Version 1.5 added the per-thread handler. We need to call
1744 * "uncaughtException" in the handler object, which is either the
1745 * ThreadGroup object or the Thread-specific handler.
1746 */
1747static void threadExitUncaughtException(Thread* self, Object* group)
1748{
1749 Object* exception;
1750 Object* handlerObj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001751 Method* uncaughtHandler = NULL;
1752 InstField* threadHandler;
1753
1754 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1755 self->threadId, group);
1756 assert(group != NULL);
1757
1758 /*
1759 * Get a pointer to the exception, then clear out the one in the
1760 * thread. We don't want to have it set when executing interpreted code.
1761 */
1762 exception = dvmGetException(self);
1763 dvmAddTrackedAlloc(exception, self);
1764 dvmClearException(self);
1765
1766 /*
1767 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1768 * else use "group" (which is an instance of UncaughtExceptionHandler).
1769 */
1770 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1771 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1772 if (threadHandler == NULL) {
1773 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1774 goto bail;
1775 }
1776 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1777 if (handlerObj == NULL)
1778 handlerObj = group;
1779
1780 /*
1781 * Find the "uncaughtHandler" field in this object.
1782 */
1783 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1784 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1785
1786 if (uncaughtHandler != NULL) {
1787 //LOGI("+++ calling %s.uncaughtException\n",
1788 // handlerObj->clazz->descriptor);
1789 JValue unused;
1790 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1791 self->threadObj, exception);
1792 } else {
1793 /* restore it and dump a stack trace */
1794 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1795 handlerObj->clazz->descriptor);
1796 dvmSetException(self, exception);
1797 dvmLogExceptionStackTrace();
1798 }
1799
1800bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001801#if defined(WITH_JIT)
1802 /* Remove this thread's suspendCount from global suspendCount sum */
1803 lockThreadSuspendCount();
1804 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1805 unlockThreadSuspendCount();
1806#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001807 dvmReleaseTrackedAlloc(exception, self);
1808}
1809
1810
1811/*
1812 * Create an internal VM thread, for things like JDWP and finalizers.
1813 *
1814 * The easiest way to do this is create a new thread and then use the
1815 * JNI AttachCurrentThread implementation.
1816 *
1817 * This does not return until after the new thread has begun executing.
1818 */
1819bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1820 InternalThreadStart func, void* funcArg)
1821{
1822 InternalStartArgs* pArgs;
1823 Object* systemGroup;
1824 pthread_attr_t threadAttr;
1825 volatile Thread* newThread = NULL;
1826 volatile int createStatus = 0;
1827
1828 systemGroup = dvmGetSystemThreadGroup();
1829 if (systemGroup == NULL)
1830 return false;
1831
1832 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1833 pArgs->func = func;
1834 pArgs->funcArg = funcArg;
1835 pArgs->name = strdup(name); // storage will be owned by new thread
1836 pArgs->group = systemGroup;
1837 pArgs->isDaemon = true;
1838 pArgs->pThread = &newThread;
1839 pArgs->pCreateStatus = &createStatus;
1840
1841 pthread_attr_init(&threadAttr);
1842 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1843
1844 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1845 pArgs) != 0)
1846 {
1847 LOGE("internal thread creation failed\n");
1848 free(pArgs->name);
1849 free(pArgs);
1850 return false;
1851 }
1852
1853 /*
1854 * Wait for the child to start. This gives us an opportunity to make
1855 * sure that the thread started correctly, and allows our caller to
1856 * assume that the thread has started running.
1857 *
1858 * Because we aren't holding a lock across the thread creation, it's
1859 * possible that the child will already have completed its
1860 * initialization. Because the child only adjusts "createStatus" while
1861 * holding the thread list lock, the initial condition on the "while"
1862 * loop will correctly avoid the wait if this occurs.
1863 *
1864 * It's also possible that we'll have to wait for the thread to finish
1865 * being created, and as part of allocating a Thread object it might
1866 * need to initiate a GC. We switch to VMWAIT while we pause.
1867 */
1868 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -07001869 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001870 dvmLockThreadList(self);
1871 while (createStatus == 0)
1872 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1873
1874 if (newThread == NULL) {
1875 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1876 assert(createStatus < 0);
1877 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1878 dvmUnlockThreadList();
1879 dvmChangeStatus(self, oldStatus);
1880 return false;
1881 }
1882
1883 /* thread could be in any state now (except early init states) */
1884 //assert(newThread->status == THREAD_RUNNING);
1885
1886 dvmUnlockThreadList();
1887 dvmChangeStatus(self, oldStatus);
1888
1889 return true;
1890}
1891
1892/*
1893 * pthread entry function for internally-created threads.
1894 *
1895 * We are expected to free "arg" and its contents. If we're a daemon
1896 * thread, and we get cancelled abruptly when the VM shuts down, the
1897 * storage won't be freed. If this becomes a concern we can make a copy
1898 * on the stack.
1899 */
1900static void* internalThreadStart(void* arg)
1901{
1902 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1903 JavaVMAttachArgs jniArgs;
1904
1905 jniArgs.version = JNI_VERSION_1_2;
1906 jniArgs.name = pArgs->name;
1907 jniArgs.group = pArgs->group;
1908
1909 setThreadName(pArgs->name);
1910
1911 /* use local jniArgs as stack top */
1912 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1913 /*
1914 * Tell the parent of our success.
1915 *
1916 * threadListLock is the mutex for threadStartCond.
1917 */
1918 dvmLockThreadList(dvmThreadSelf());
1919 *pArgs->pCreateStatus = 1;
1920 *pArgs->pThread = dvmThreadSelf();
1921 pthread_cond_broadcast(&gDvm.threadStartCond);
1922 dvmUnlockThreadList();
1923
1924 LOG_THREAD("threadid=%d: internal '%s'\n",
1925 dvmThreadSelf()->threadId, pArgs->name);
1926
1927 /* execute */
1928 (*pArgs->func)(pArgs->funcArg);
1929
1930 /* detach ourselves */
1931 dvmDetachCurrentThread();
1932 } else {
1933 /*
1934 * Tell the parent of our failure. We don't have a Thread struct,
1935 * so we can't be suspended, so we don't need to enter a critical
1936 * section.
1937 */
1938 dvmLockThreadList(dvmThreadSelf());
1939 *pArgs->pCreateStatus = -1;
1940 assert(*pArgs->pThread == NULL);
1941 pthread_cond_broadcast(&gDvm.threadStartCond);
1942 dvmUnlockThreadList();
1943
1944 assert(*pArgs->pThread == NULL);
1945 }
1946
1947 free(pArgs->name);
1948 free(pArgs);
1949 return NULL;
1950}
1951
1952/*
1953 * Attach the current thread to the VM.
1954 *
1955 * Used for internally-created threads and JNI's AttachCurrentThread.
1956 */
1957bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1958{
1959 Thread* self = NULL;
1960 Object* threadObj = NULL;
1961 Object* vmThreadObj = NULL;
1962 StringObject* threadNameStr = NULL;
1963 Method* init;
1964 bool ok, ret;
1965
Andy McFaddene3346d82010-06-02 15:37:21 -07001966 /* allocate thread struct, and establish a basic sense of self */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001967 self = allocThread(gDvm.stackSize);
1968 if (self == NULL)
1969 goto fail;
1970 setThreadSelf(self);
1971
1972 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001973 * Finish our thread prep. We need to do this before adding ourselves
1974 * to the thread list or invoking any interpreted code. prepareThread()
1975 * requires that we hold the thread list lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001976 */
1977 dvmLockThreadList(self);
1978 ok = prepareThread(self);
1979 dvmUnlockThreadList();
1980 if (!ok)
1981 goto fail;
1982
1983 self->jniEnv = dvmCreateJNIEnv(self);
1984 if (self->jniEnv == NULL)
1985 goto fail;
1986
1987 /*
1988 * Create a "fake" JNI frame at the top of the main thread interp stack.
1989 * It isn't really necessary for the internal threads, but it gives
1990 * the debugger something to show. It is essential for the JNI-attached
1991 * threads.
1992 */
1993 if (!createFakeRunFrame(self))
1994 goto fail;
1995
1996 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07001997 * The native side of the thread is ready; add it to the list. Once
1998 * 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 -08001999 */
2000 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
2001
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002002 dvmLockThreadList(self);
2003
2004 self->next = gDvm.threadList->next;
2005 if (self->next != NULL)
2006 self->next->prev = self;
2007 self->prev = gDvm.threadList;
2008 gDvm.threadList->next = self;
2009 if (!isDaemon)
2010 gDvm.nonDaemonThreadCount++;
2011
2012 dvmUnlockThreadList();
2013
2014 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002015 * Switch state from initializing to running.
2016 *
2017 * It's possible that a GC began right before we added ourselves
2018 * to the thread list, and is still going. That means our thread
2019 * suspend count won't reflect the fact that we should be suspended.
2020 * To deal with this, we transition to VMWAIT, pulse the heap lock,
2021 * and then advance to RUNNING. That will ensure that we stall until
2022 * the GC completes.
2023 *
2024 * Once we're in RUNNING, we're like any other thread in the VM (except
2025 * for the lack of an initialized threadObj). We're then free to
2026 * allocate and initialize objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002027 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002028 assert(self->status == THREAD_INITIALIZING);
2029 dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002030 dvmLockMutex(&gDvm.gcHeapLock);
2031 dvmUnlockMutex(&gDvm.gcHeapLock);
Andy McFaddene3346d82010-06-02 15:37:21 -07002032 dvmChangeStatus(self, THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002033
2034 /*
Andy McFaddene3346d82010-06-02 15:37:21 -07002035 * Create Thread and VMThread objects.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002036 */
Andy McFaddene3346d82010-06-02 15:37:21 -07002037 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
2038 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
2039 if (threadObj == NULL || vmThreadObj == NULL)
2040 goto fail_unlink;
2041
2042 /*
2043 * This makes threadObj visible to the GC. We still have it in the
2044 * tracked allocation table, so it can't move around on us.
2045 */
2046 self->threadObj = threadObj;
2047 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
2048
2049 /*
2050 * Create a string for the thread name.
2051 */
2052 if (pArgs->name != NULL) {
Barry Hayes81f3ebe2010-06-15 16:17:37 -07002053 threadNameStr = dvmCreateStringFromCstr(pArgs->name);
Andy McFaddene3346d82010-06-02 15:37:21 -07002054 if (threadNameStr == NULL) {
2055 assert(dvmCheckException(dvmThreadSelf()));
2056 goto fail_unlink;
2057 }
2058 }
2059
2060 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
2061 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
2062 if (init == NULL) {
2063 assert(dvmCheckException(self));
2064 goto fail_unlink;
2065 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002066
2067 /*
2068 * Now we're ready to run some interpreted code.
2069 *
2070 * We need to construct the Thread object and set the VMThread field.
2071 * Setting VMThread tells interpreted code that we're alive.
2072 *
2073 * Call the (group, name, priority, daemon) constructor on the Thread.
2074 * This sets the thread's name and adds it to the specified group, and
2075 * provides values for priority and daemon (which are normally inherited
2076 * from the current thread).
2077 */
2078 JValue unused;
2079 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2080 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2081 if (dvmCheckException(self)) {
2082 LOGE("exception thrown while constructing attached thread object\n");
2083 goto fail_unlink;
2084 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002085
2086 /*
2087 * Set the VMThread field, which tells interpreted code that we're alive.
2088 *
2089 * The risk of a thread start collision here is very low; somebody
2090 * would have to be deliberately polling the ThreadGroup list and
2091 * trying to start threads against anything it sees, which would
2092 * generally cause problems for all thread creation. However, for
2093 * correctness we test "vmThread" before setting it.
Andy McFaddene3346d82010-06-02 15:37:21 -07002094 *
2095 * TODO: this still has a race, it's just smaller. Not sure this is
2096 * worth putting effort into fixing. Need to hold a lock while
2097 * fiddling with the field, or maybe initialize the Thread object in a
2098 * way that ensures another thread can't call start() on it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002099 */
2100 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07002101 LOGW("WOW: thread start hijack\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002102 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2103 "thread has already been started");
2104 /* We don't want to free anything associated with the thread
2105 * because someone is obviously interested in it. Just let
2106 * it go and hope it will clean itself up when its finished.
2107 * This case should never happen anyway.
2108 *
2109 * Since we're letting it live, we need to finish setting it up.
2110 * We just have to let the caller know that the intended operation
2111 * has failed.
2112 *
2113 * [ This seems strange -- stepping on the vmThread object that's
2114 * already present seems like a bad idea. TODO: figure this out. ]
2115 */
2116 ret = false;
Andy McFaddene3346d82010-06-02 15:37:21 -07002117 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002118 ret = true;
Andy McFaddene3346d82010-06-02 15:37:21 -07002119 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002120 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2121
Andy McFaddene3346d82010-06-02 15:37:21 -07002122 /* we can now safely un-pin these */
2123 dvmReleaseTrackedAlloc(threadObj, self);
2124 dvmReleaseTrackedAlloc(vmThreadObj, self);
2125 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002126
2127 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2128 self->threadId, pArgs->name);
2129
2130 /* tell the debugger & DDM */
2131 if (gDvm.debuggerConnected)
2132 dvmDbgPostThreadStart(self);
2133
2134 return ret;
2135
2136fail_unlink:
2137 dvmLockThreadList(self);
2138 unlinkThread(self);
2139 if (!isDaemon)
2140 gDvm.nonDaemonThreadCount--;
2141 dvmUnlockThreadList();
2142 /* fall through to "fail" */
2143fail:
Andy McFaddene3346d82010-06-02 15:37:21 -07002144 dvmReleaseTrackedAlloc(threadObj, self);
2145 dvmReleaseTrackedAlloc(vmThreadObj, self);
2146 dvmReleaseTrackedAlloc((Object*)threadNameStr, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002147 if (self != NULL) {
2148 if (self->jniEnv != NULL) {
2149 dvmDestroyJNIEnv(self->jniEnv);
2150 self->jniEnv = NULL;
2151 }
2152 freeThread(self);
2153 }
2154 setThreadSelf(NULL);
2155 return false;
2156}
2157
2158/*
2159 * Detach the thread from the various data structures, notify other threads
2160 * that are waiting to "join" it, and free up all heap-allocated storage.
2161 *
2162 * Used for all threads.
2163 *
2164 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2165 * requires us to enforce this for the DetachCurrentThread call, probably
2166 * because it also says that DetachCurrentThread causes all monitors
2167 * associated with the thread to be released. (Because the stack is empty,
2168 * we only have to worry about explicit JNI calls to MonitorEnter.)
2169 *
2170 * THOUGHT:
2171 * We might want to avoid freeing our internal Thread structure until the
2172 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2173 * get to once the thread shuts down, but there is a small possibility of
2174 * an operation starting in another thread before this thread halts, and
2175 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2176 * We don't want something like Thread.isInterrupted() crawling through
2177 * freed storage. Can do with a Thread finalizer, or by creating a
2178 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2179 * state into that.
2180 */
2181void dvmDetachCurrentThread(void)
2182{
2183 Thread* self = dvmThreadSelf();
2184 Object* vmThread;
2185 Object* group;
2186
2187 /*
2188 * Make sure we're not detaching a thread that's still running. (This
2189 * could happen with an explicit JNI detach call.)
2190 *
2191 * A thread created by interpreted code will finish with a depth of
2192 * zero, while a JNI-attached thread will have the synthetic "stack
2193 * starter" native method at the top.
2194 */
2195 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2196 if (curDepth != 0) {
2197 bool topIsNative = false;
2198
2199 if (curDepth == 1) {
2200 /* not expecting a lingering break frame; just look at curFrame */
2201 assert(!dvmIsBreakFrame(self->curFrame));
2202 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2203 if (dvmIsNativeMethod(ssa->method))
2204 topIsNative = true;
2205 }
2206
2207 if (!topIsNative) {
2208 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2209 curDepth);
2210 dvmDumpThread(self, false);
2211 dvmAbort();
2212 }
2213 }
2214
2215 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2216 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2217
2218 /*
2219 * Release any held monitors. Since there are no interpreted stack
2220 * frames, the only thing left are the monitors held by JNI MonitorEnter
2221 * calls.
2222 */
2223 dvmReleaseJniMonitors(self);
2224
2225 /*
2226 * Do some thread-exit uncaught exception processing if necessary.
2227 */
2228 if (dvmCheckException(self))
2229 threadExitUncaughtException(self, group);
2230
2231 /*
2232 * Remove the thread from the thread group.
2233 */
2234 if (group != NULL) {
2235 Method* removeThread =
2236 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2237 JValue unused;
2238 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2239 }
2240
2241 /*
2242 * Clear the vmThread reference in the Thread object. Interpreted code
2243 * will now see that this Thread is not running. As this may be the
2244 * only reference to the VMThread object that the VM knows about, we
2245 * have to create an internal reference to it first.
2246 */
2247 vmThread = dvmGetFieldObject(self->threadObj,
2248 gDvm.offJavaLangThread_vmThread);
2249 dvmAddTrackedAlloc(vmThread, self);
2250 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2251
2252 /* clear out our struct Thread pointer, since it's going away */
2253 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2254
2255 /*
2256 * Tell the debugger & DDM. This may cause the current thread or all
2257 * threads to suspend.
2258 *
2259 * The JDWP spec is somewhat vague about when this happens, other than
2260 * that it's issued by the dying thread, which may still appear in
2261 * an "all threads" listing.
2262 */
2263 if (gDvm.debuggerConnected)
2264 dvmDbgPostThreadDeath(self);
2265
2266 /*
2267 * Thread.join() is implemented as an Object.wait() on the VMThread
2268 * object. Signal anyone who is waiting.
2269 */
2270 dvmLockObject(self, vmThread);
2271 dvmObjectNotifyAll(self, vmThread);
2272 dvmUnlockObject(self, vmThread);
2273
2274 dvmReleaseTrackedAlloc(vmThread, self);
2275 vmThread = NULL;
2276
2277 /*
2278 * We're done manipulating objects, so it's okay if the GC runs in
2279 * parallel with us from here out. It's important to do this if
2280 * profiling is enabled, since we can wait indefinitely.
2281 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002282 android_atomic_release_store(THREAD_VMWAIT, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002283
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002284 /*
2285 * If we're doing method trace profiling, we don't want threads to exit,
2286 * because if they do we'll end up reusing thread IDs. This complicates
2287 * analysis and makes it impossible to have reasonable output in the
2288 * "threads" section of the "key" file.
2289 *
2290 * We need to do this after Thread.join() completes, or other threads
2291 * could get wedged. Since self->threadObj is still valid, the Thread
2292 * object will not get GCed even though we're no longer in the ThreadGroup
2293 * list (which is important since the profiling thread needs to get
2294 * the thread's name).
2295 */
2296 MethodTraceState* traceState = &gDvm.methodTrace;
2297
2298 dvmLockMutex(&traceState->startStopLock);
2299 if (traceState->traceEnabled) {
2300 LOGI("threadid=%d: waiting for method trace to finish\n",
2301 self->threadId);
2302 while (traceState->traceEnabled) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002303 dvmWaitCond(&traceState->threadExitCond,
2304 &traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002305 }
2306 }
2307 dvmUnlockMutex(&traceState->startStopLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002308
2309 dvmLockThreadList(self);
2310
2311 /*
2312 * Lose the JNI context.
2313 */
2314 dvmDestroyJNIEnv(self->jniEnv);
2315 self->jniEnv = NULL;
2316
2317 self->status = THREAD_ZOMBIE;
2318
2319 /*
2320 * Remove ourselves from the internal thread list.
2321 */
2322 unlinkThread(self);
2323
2324 /*
2325 * If we're the last one standing, signal anybody waiting in
2326 * DestroyJavaVM that it's okay to exit.
2327 */
2328 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2329 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2330
2331 if (gDvm.nonDaemonThreadCount == 0) {
2332 int cc;
2333
2334 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2335 //dvmDumpAllThreads(false);
2336 // cond var guarded by threadListLock, which we already hold
2337 cc = pthread_cond_signal(&gDvm.vmExitCond);
2338 assert(cc == 0);
2339 }
2340 }
2341
2342 LOGV("threadid=%d: bye!\n", self->threadId);
2343 releaseThreadId(self);
2344 dvmUnlockThreadList();
2345
2346 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002347
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002348 freeThread(self);
2349}
2350
2351
2352/*
2353 * Suspend a single thread. Do not use to suspend yourself.
2354 *
2355 * This is used primarily for debugger/DDMS activity. Does not return
2356 * until the thread has suspended or is in a "safe" state (e.g. executing
2357 * native code outside the VM).
2358 *
2359 * The thread list lock should be held before calling here -- it's not
2360 * entirely safe to hang on to a Thread* from another thread otherwise.
2361 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2362 */
2363void dvmSuspendThread(Thread* thread)
2364{
2365 assert(thread != NULL);
2366 assert(thread != dvmThreadSelf());
2367 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2368
2369 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002370 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002371 thread->dbgSuspendCount++;
2372
2373 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2374 thread->threadId, thread->suspendCount);
2375 unlockThreadSuspendCount();
2376
2377 waitForThreadSuspend(dvmThreadSelf(), thread);
2378}
2379
2380/*
2381 * Reduce the suspend count of a thread. If it hits zero, tell it to
2382 * resume.
2383 *
2384 * Used primarily for debugger/DDMS activity. The thread in question
2385 * might have been suspended singly or as part of a suspend-all operation.
2386 *
2387 * The thread list lock should be held before calling here -- it's not
2388 * entirely safe to hang on to a Thread* from another thread otherwise.
2389 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2390 */
2391void dvmResumeThread(Thread* thread)
2392{
2393 assert(thread != NULL);
2394 assert(thread != dvmThreadSelf());
2395 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2396
2397 lockThreadSuspendCount();
2398 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002399 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002400 thread->dbgSuspendCount--;
2401 } else {
2402 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2403 thread->threadId);
2404 }
2405
2406 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2407 thread->threadId, thread->suspendCount);
2408
2409 if (thread->suspendCount == 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002410 dvmBroadcastCond(&gDvm.threadSuspendCountCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002411 }
2412
2413 unlockThreadSuspendCount();
2414}
2415
2416/*
2417 * Suspend yourself, as a result of debugger activity.
2418 */
2419void dvmSuspendSelf(bool jdwpActivity)
2420{
2421 Thread* self = dvmThreadSelf();
2422
Andy McFadden6dce9962010-08-23 16:45:24 -07002423 /* debugger thread must not suspend itself due to debugger activity! */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002424 assert(gDvm.jdwpState != NULL);
2425 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2426 assert(false);
2427 return;
2428 }
2429
2430 /*
2431 * Collisions with other suspends aren't really interesting. We want
2432 * to ensure that we're the only one fiddling with the suspend count
2433 * though.
2434 */
2435 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002436 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002437 self->dbgSuspendCount++;
2438
2439 /*
2440 * Suspend ourselves.
2441 */
2442 assert(self->suspendCount > 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002443 self->status = THREAD_SUSPENDED;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002444 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2445
2446 /*
2447 * Tell JDWP that we've completed suspension. The JDWP thread can't
2448 * tell us to resume before we're fully asleep because we hold the
2449 * suspend count lock.
2450 *
2451 * If we got here via waitForDebugger(), don't do this part.
2452 */
2453 if (jdwpActivity) {
2454 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2455 // self->threadId, (int) self->handle);
2456 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2457 }
2458
2459 while (self->suspendCount != 0) {
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07002460 dvmWaitCond(&gDvm.threadSuspendCountCond,
2461 &gDvm.threadSuspendCountLock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002462 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002463 /*
2464 * The condition was signaled but we're still suspended. This
2465 * can happen if the debugger lets go while a SIGQUIT thread
2466 * dump event is pending (assuming SignalCatcher was resumed for
2467 * just long enough to try to grab the thread-suspend lock).
2468 */
Andy McFadden6dce9962010-08-23 16:45:24 -07002469 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d)\n",
2470 self->threadId, self->suspendCount, self->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002471 }
2472 }
2473 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07002474 self->status = THREAD_RUNNING;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002475 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2476 self->threadId, self->status);
2477
2478 unlockThreadSuspendCount();
2479}
2480
2481
2482#ifdef HAVE_GLIBC
2483# define NUM_FRAMES 20
2484# include <execinfo.h>
2485/*
2486 * glibc-only stack dump function. Requires link with "--export-dynamic".
2487 *
2488 * TODO: move this into libs/cutils and make it work for all platforms.
2489 */
2490static void printBackTrace(void)
2491{
2492 void* array[NUM_FRAMES];
2493 size_t size;
2494 char** strings;
2495 size_t i;
2496
2497 size = backtrace(array, NUM_FRAMES);
2498 strings = backtrace_symbols(array, size);
2499
2500 LOGW("Obtained %zd stack frames.\n", size);
2501
2502 for (i = 0; i < size; i++)
2503 LOGW("%s\n", strings[i]);
2504
2505 free(strings);
2506}
2507#else
2508static void printBackTrace(void) {}
2509#endif
2510
2511/*
2512 * Dump the state of the current thread and that of another thread that
2513 * we think is wedged.
2514 */
2515static void dumpWedgedThread(Thread* thread)
2516{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002517 dvmDumpThread(dvmThreadSelf(), false);
2518 printBackTrace();
2519
2520 // dumping a running thread is risky, but could be useful
2521 dvmDumpThread(thread, true);
2522
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002523 // stop now and get a core dump
2524 //abort();
2525}
2526
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002527/*
2528 * If the thread is running at below-normal priority, temporarily elevate
2529 * it to "normal".
2530 *
2531 * Returns zero if no changes were made. Otherwise, returns bit flags
2532 * indicating what was changed, storing the previous values in the
2533 * provided locations.
2534 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002535int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002536 SchedPolicy* pSavedThreadPolicy)
2537{
2538 errno = 0;
2539 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2540 if (errno != 0) {
2541 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2542 thread->threadId, thread->systemTid);
2543 return 0;
2544 }
2545 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2546 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2547 thread->threadId, thread->systemTid);
2548 return 0;
2549 }
2550
2551 int changeFlags = 0;
2552
2553 /*
2554 * Change the priority if we're in the background group.
2555 */
2556 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2557 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2558 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2559 } else {
2560 changeFlags |= kChangedPolicy;
2561 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2562 thread->systemTid, *pSavedThreadPolicy);
2563 }
2564 }
2565
2566 /*
2567 * getpriority() returns the "nice" value, so larger numbers indicate
2568 * lower priority, with 0 being normal.
2569 */
2570 if (*pSavedThreadPrio > 0) {
2571 const int kHigher = 0;
2572 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2573 LOGW("Couldn't raise priority on tid %d to %d\n",
2574 thread->systemTid, kHigher);
2575 } else {
2576 changeFlags |= kChangedPriority;
2577 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2578 thread->systemTid, *pSavedThreadPrio, kHigher);
2579 }
2580 }
2581
2582 return changeFlags;
2583}
2584
2585/*
2586 * Reset the priority values for the thread in question.
2587 */
Andy McFadden2b94b302010-03-09 16:38:36 -08002588void dvmResetThreadPriority(Thread* thread, int changeFlags,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002589 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2590{
2591 if ((changeFlags & kChangedPolicy) != 0) {
2592 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2593 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2594 thread->systemTid, savedThreadPolicy);
2595 } else {
2596 LOGD("Restored policy of %d to %d\n",
2597 thread->systemTid, savedThreadPolicy);
2598 }
2599 }
2600
2601 if ((changeFlags & kChangedPriority) != 0) {
2602 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2603 {
2604 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2605 thread->systemTid, savedThreadPrio);
2606 } else {
2607 LOGD("Restored priority on %d to %d\n",
2608 thread->systemTid, savedThreadPrio);
2609 }
2610 }
2611}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002612
2613/*
2614 * Wait for another thread to see the pending suspension and stop running.
2615 * It can either suspend itself or go into a non-running state such as
2616 * VMWAIT or NATIVE in which it cannot interact with the GC.
2617 *
2618 * If we're running at a higher priority, sched_yield() may not do anything,
2619 * so we need to sleep for "long enough" to guarantee that the other
2620 * thread has a chance to finish what it's doing. Sleeping for too short
2621 * a period (e.g. less than the resolution of the sleep clock) might cause
2622 * the scheduler to return immediately, so we want to start with a
2623 * "reasonable" value and expand.
2624 *
2625 * This does not return until the other thread has stopped running.
2626 * Eventually we time out and the VM aborts.
2627 *
2628 * This does not try to detect the situation where two threads are
2629 * waiting for each other to suspend. In normal use this is part of a
2630 * suspend-all, which implies that the suspend-all lock is held, or as
2631 * part of a debugger action in which the JDWP thread is always the one
2632 * doing the suspending. (We may need to re-evaluate this now that
2633 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2634 *
2635 * TODO: track basic stats about time required to suspend VM.
2636 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002637#define FIRST_SLEEP (250*1000) /* 0.25s */
2638#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002639static void waitForThreadSuspend(Thread* self, Thread* thread)
2640{
2641 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002642 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002643 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002644 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002645 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002646 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002647
2648 int sleepIter = 0;
2649 int retryCount = 0;
2650 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002651 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002652
Andy McFadden6dce9962010-08-23 16:45:24 -07002653 while (thread->status == THREAD_RUNNING) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002654 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002655 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002656 if (firstStartWhen == 0) // first iteration of first attempt
2657 firstStartWhen = startWhen;
2658
2659 /*
2660 * After waiting for a bit, check to see if the target thread is
2661 * running at a reduced priority. If so, bump it up temporarily
2662 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002663 */
2664 if (retryCount == 2) {
2665 assert(thread->systemTid != 0);
Andy McFadden2b94b302010-03-09 16:38:36 -08002666 priChangeFlags = dvmRaiseThreadPriorityIfNeeded(thread,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002667 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002668 }
2669 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002670
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002671#if defined (WITH_JIT)
2672 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002673 * If we're still waiting after the first timeout, unchain all
2674 * translations iff:
2675 * 1) There are new chains formed since the last unchain
2676 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002677 */
Ben Cheng6999d842010-01-26 16:46:15 -08002678 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2679 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002680 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002681 dvmJitUnchainAll();
2682 }
2683#endif
2684
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002685 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002686 * Sleep briefly. The iterative sleep call returns false if we've
2687 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002688 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002689 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002690 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002691 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002692 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002693 thread->threadId, priChangeFlags);
2694 if (retryCount > 1) {
2695 /* stack trace logging is slow; skip on first iter */
2696 dumpWedgedThread(thread);
2697 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002698 complained = true;
2699 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002700
2701 // keep going; could be slow due to valgrind
2702 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002703 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002704
2705 if (retryCount++ == kMaxRetries) {
Andy McFadden384ef6b2010-03-15 17:24:55 -07002706 LOGE("Fatal spin-on-suspend, dumping threads\n");
2707 dvmDumpAllThreads(false);
2708
2709 /* log this after -- long traces will scroll off log */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002710 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2711 self->threadId, thread->threadId);
Andy McFadden384ef6b2010-03-15 17:24:55 -07002712
2713 /* try to get a debuggerd dump from the spinning thread */
2714 dvmNukeThread(thread);
2715 /* abort the VM */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002716 dvmAbort();
2717 }
2718 }
2719 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002720
2721 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002722 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2723 self->threadId,
2724 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002725 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2726 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002727 if (priChangeFlags != 0) {
Andy McFadden2b94b302010-03-09 16:38:36 -08002728 dvmResetThreadPriority(thread, priChangeFlags, savedThreadPrio,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002729 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002730 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002731}
2732
2733/*
2734 * Suspend all threads except the current one. This is used by the GC,
2735 * the debugger, and by any thread that hits a "suspend all threads"
2736 * debugger event (e.g. breakpoint or exception).
2737 *
2738 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2739 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2740 * create objects and even execute arbitrary code. The "why" argument
2741 * allows the caller to say why the suspension is taking place.
2742 *
2743 * This can be called when a global suspend has already happened, due to
2744 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2745 * doesn't work.
2746 *
2747 * DO NOT grab any locks before calling here. We grab & release the thread
2748 * lock and suspend lock here (and we're not using recursive threads), and
2749 * we might have to self-suspend if somebody else beats us here.
2750 *
Andy McFaddenc650d2b2010-08-16 16:14:06 -07002751 * We know the current thread is in the thread list, because we attach the
2752 * thread before doing anything that could cause VM suspension (like object
2753 * allocation).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002754 */
2755void dvmSuspendAllThreads(SuspendCause why)
2756{
2757 Thread* self = dvmThreadSelf();
2758 Thread* thread;
2759
2760 assert(why != 0);
2761
2762 /*
2763 * Start by grabbing the thread suspend lock. If we can't get it, most
2764 * likely somebody else is in the process of performing a suspend or
2765 * resume, so lockThreadSuspend() will cause us to self-suspend.
2766 *
2767 * We keep the lock until all other threads are suspended.
2768 */
2769 lockThreadSuspend("susp-all", why);
2770
2771 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2772
2773 /*
2774 * This is possible if the current thread was in VMWAIT mode when a
2775 * suspend-all happened, and then decided to do its own suspend-all.
2776 * This can happen when a couple of threads have simultaneous events
2777 * of interest to the debugger.
2778 */
2779 //assert(self->suspendCount == 0);
2780
2781 /*
2782 * Increment everybody's suspend count (except our own).
2783 */
2784 dvmLockThreadList(self);
2785
2786 lockThreadSuspendCount();
2787 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2788 if (thread == self)
2789 continue;
2790
2791 /* debugger events don't suspend JDWP thread */
2792 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2793 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2794 continue;
2795
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002796 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002797 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2798 thread->dbgSuspendCount++;
2799 }
2800 unlockThreadSuspendCount();
2801
2802 /*
2803 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2804 * indicate the code is either running natively or sleeping quietly.
2805 * Any attempt to transition back to THREAD_RUNNING will cause a check
2806 * for suspension, so it should be impossible for anything to execute
2807 * interpreted code or modify objects (assuming native code plays nicely).
2808 *
2809 * It's also okay if the thread transitions to a non-RUNNING state.
2810 *
2811 * Note we released the threadSuspendCountLock before getting here,
2812 * so if another thread is fiddling with its suspend count (perhaps
2813 * self-suspending for the debugger) it won't block while we're waiting
2814 * in here.
2815 */
2816 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2817 if (thread == self)
2818 continue;
2819
2820 /* debugger events don't suspend JDWP thread */
2821 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2822 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2823 continue;
2824
2825 /* wait for the other thread to see the pending suspend */
2826 waitForThreadSuspend(self, thread);
2827
Andy McFadden6dce9962010-08-23 16:45:24 -07002828 LOG_THREAD("threadid=%d: threadid=%d status=%d sc=%d dc=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002829 self->threadId,
2830 thread->threadId, thread->status, thread->suspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07002831 thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002832 }
2833
2834 dvmUnlockThreadList();
2835 unlockThreadSuspend();
2836
2837 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2838}
2839
2840/*
2841 * Resume all threads that are currently suspended.
2842 *
2843 * The "why" must match with the previous suspend.
2844 */
2845void dvmResumeAllThreads(SuspendCause why)
2846{
2847 Thread* self = dvmThreadSelf();
2848 Thread* thread;
2849 int cc;
2850
2851 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2852 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2853
2854 /*
2855 * Decrement the suspend counts for all threads. No need for atomic
2856 * writes, since nobody should be moving until we decrement the count.
2857 * We do need to hold the thread list because of JNI attaches.
2858 */
2859 dvmLockThreadList(self);
2860 lockThreadSuspendCount();
2861 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2862 if (thread == self)
2863 continue;
2864
2865 /* debugger events don't suspend JDWP thread */
2866 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2867 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002868 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002869 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002870 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002871
2872 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002873 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002874 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2875 thread->dbgSuspendCount--;
2876 } else {
2877 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2878 thread->threadId);
2879 }
2880 }
2881 unlockThreadSuspendCount();
2882 dvmUnlockThreadList();
2883
2884 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002885 * In some ways it makes sense to continue to hold the thread-suspend
2886 * lock while we issue the wakeup broadcast. It allows us to complete
2887 * one operation before moving on to the next, which simplifies the
2888 * thread activity debug traces.
2889 *
2890 * This approach caused us some difficulty under Linux, because the
2891 * condition variable broadcast not only made the threads runnable,
2892 * but actually caused them to execute, and it was a while before
2893 * the thread performing the wakeup had an opportunity to release the
2894 * thread-suspend lock.
2895 *
2896 * This is a problem because, when a thread tries to acquire that
2897 * lock, it times out after 3 seconds. If at some point the thread
2898 * is told to suspend, the clock resets; but since the VM is still
2899 * theoretically mid-resume, there's no suspend pending. If, for
2900 * example, the GC was waking threads up while the SIGQUIT handler
2901 * was trying to acquire the lock, we would occasionally time out on
2902 * a busy system and SignalCatcher would abort.
2903 *
2904 * We now perform the unlock before the wakeup broadcast. The next
2905 * suspend can't actually start until the broadcast completes and
2906 * returns, because we're holding the thread-suspend-count lock, but the
2907 * suspending thread is now able to make progress and we avoid the abort.
2908 *
2909 * (Technically there is a narrow window between when we release
2910 * the thread-suspend lock and grab the thread-suspend-count lock.
2911 * This could cause us to send a broadcast to threads with nonzero
2912 * suspend counts, but this is expected and they'll all just fall
2913 * right back to sleep. It's probably safe to grab the suspend-count
2914 * lock before releasing thread-suspend, since we're still following
2915 * the correct order of acquisition, but it feels weird.)
2916 */
2917
2918 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2919 unlockThreadSuspend();
2920
2921 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002922 * Broadcast a notification to all suspended threads, some or all of
2923 * which may choose to wake up. No need to wait for them.
2924 */
2925 lockThreadSuspendCount();
2926 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2927 assert(cc == 0);
2928 unlockThreadSuspendCount();
2929
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002930 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2931}
2932
2933/*
2934 * Undo any debugger suspensions. This is called when the debugger
2935 * disconnects.
2936 */
2937void dvmUndoDebuggerSuspensions(void)
2938{
2939 Thread* self = dvmThreadSelf();
2940 Thread* thread;
2941 int cc;
2942
2943 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2944 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2945
2946 /*
2947 * Decrement the suspend counts for all threads. No need for atomic
2948 * writes, since nobody should be moving until we decrement the count.
2949 * We do need to hold the thread list because of JNI attaches.
2950 */
2951 dvmLockThreadList(self);
2952 lockThreadSuspendCount();
2953 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2954 if (thread == self)
2955 continue;
2956
2957 /* debugger events don't suspend JDWP thread */
2958 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2959 assert(thread->dbgSuspendCount == 0);
2960 continue;
2961 }
2962
2963 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002964 dvmAddToThreadSuspendCount(&thread->suspendCount,
2965 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002966 thread->dbgSuspendCount = 0;
2967 }
2968 unlockThreadSuspendCount();
2969 dvmUnlockThreadList();
2970
2971 /*
2972 * Broadcast a notification to all suspended threads, some or all of
2973 * which may choose to wake up. No need to wait for them.
2974 */
2975 lockThreadSuspendCount();
2976 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2977 assert(cc == 0);
2978 unlockThreadSuspendCount();
2979
2980 unlockThreadSuspend();
2981
2982 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2983}
2984
2985/*
2986 * Determine if a thread is suspended.
2987 *
2988 * As with all operations on foreign threads, the caller should hold
2989 * the thread list lock before calling.
Andy McFadden3469a7e2010-08-04 16:09:10 -07002990 *
2991 * If the thread is suspending or waking, these fields could be changing
2992 * out from under us (or the thread could change state right after we
2993 * examine it), making this generally unreliable. This is chiefly
2994 * intended for use by the debugger.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002995 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07002996bool dvmIsSuspended(const Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002997{
2998 /*
2999 * The thread could be:
Andy McFadden6dce9962010-08-23 16:45:24 -07003000 * (1) Running happily. status is RUNNING, suspendCount is zero.
3001 * Return "false".
3002 * (2) Pending suspend. status is RUNNING, suspendCount is nonzero.
3003 * Return "false".
3004 * (3) Suspended. suspendCount is nonzero, and status is !RUNNING.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003005 * Return "true".
Andy McFadden6dce9962010-08-23 16:45:24 -07003006 * (4) Waking up. suspendCount is zero, status is SUSPENDED
3007 * Return "false" (since it could change out from under us, unless
3008 * we hold suspendCountLock).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003009 */
3010
Andy McFadden6dce9962010-08-23 16:45:24 -07003011 return (thread->suspendCount != 0 && thread->status != THREAD_RUNNING);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003012}
3013
3014/*
3015 * Wait until another thread self-suspends. This is specifically for
3016 * synchronization between the JDWP thread and a thread that has decided
3017 * to suspend itself after sending an event to the debugger.
3018 *
3019 * Threads that encounter "suspend all" events work as well -- the thread
3020 * in question suspends everybody else and then itself.
3021 *
3022 * We can't hold a thread lock here or in the caller, because we could
3023 * get here just before the to-be-waited-for-thread issues a "suspend all".
3024 * There's an opportunity for badness if the thread we're waiting for exits
3025 * and gets cleaned up, but since the thread in question is processing a
3026 * debugger event, that's not really a possibility. (To avoid deadlock,
3027 * it's important that we not be in THREAD_RUNNING while we wait.)
3028 */
3029void dvmWaitForSuspend(Thread* thread)
3030{
3031 Thread* self = dvmThreadSelf();
3032
3033 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
3034 self->threadId, thread->threadId);
3035
3036 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
3037 assert(thread != self);
3038 assert(self->status != THREAD_RUNNING);
3039
3040 waitForThreadSuspend(self, thread);
3041
3042 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3043 self->threadId, thread->threadId);
3044}
3045
3046/*
3047 * Check to see if we need to suspend ourselves. If so, go to sleep on
3048 * a condition variable.
3049 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003050 * Returns "true" if we suspended ourselves.
3051 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003052static bool fullSuspendCheck(Thread* self)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003053{
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003054 assert(self != NULL);
3055 assert(self->suspendCount >= 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003056
Andy McFadden6dce9962010-08-23 16:45:24 -07003057 /*
3058 * Grab gDvm.threadSuspendCountLock. This gives us exclusive write
3059 * access to self->suspendCount.
3060 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003061 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3062
Andy McFadden6dce9962010-08-23 16:45:24 -07003063 bool needSuspend = (self->suspendCount != 0);
3064 if (needSuspend) {
Andy McFadden3469a7e2010-08-04 16:09:10 -07003065 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
Andy McFadden6dce9962010-08-23 16:45:24 -07003066 ThreadStatus oldStatus = self->status; /* should be RUNNING */
3067 self->status = THREAD_SUSPENDED;
3068
Andy McFadden3469a7e2010-08-04 16:09:10 -07003069 while (self->suspendCount != 0) {
Andy McFadden6dce9962010-08-23 16:45:24 -07003070 /*
3071 * Wait for wakeup signal, releasing lock. The act of releasing
3072 * and re-acquiring the lock provides the memory barriers we
3073 * need for correct behavior on SMP.
3074 */
Andy McFadden3469a7e2010-08-04 16:09:10 -07003075 dvmWaitCond(&gDvm.threadSuspendCountCond,
3076 &gDvm.threadSuspendCountLock);
3077 }
3078 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
Andy McFadden6dce9962010-08-23 16:45:24 -07003079 self->status = oldStatus;
Andy McFadden3469a7e2010-08-04 16:09:10 -07003080 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3081 self->threadId, self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003082 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003083
3084 unlockThreadSuspendCount();
3085
Andy McFadden6dce9962010-08-23 16:45:24 -07003086 return needSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003087}
3088
3089/*
Andy McFadden6dce9962010-08-23 16:45:24 -07003090 * Check to see if a suspend is pending. If so, suspend the current
3091 * thread, and return "true" after we have been resumed.
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003092 */
3093bool dvmCheckSuspendPending(Thread* self)
3094{
Andy McFadden6dce9962010-08-23 16:45:24 -07003095 assert(self != NULL);
3096 if (self->suspendCount == 0) {
3097 return false;
3098 } else {
3099 return fullSuspendCheck(self);
3100 }
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003101}
3102
3103/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003104 * Update our status.
3105 *
3106 * The "self" argument, which may be NULL, is accepted as an optimization.
3107 *
3108 * Returns the old status.
3109 */
3110ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3111{
3112 ThreadStatus oldStatus;
3113
3114 if (self == NULL)
3115 self = dvmThreadSelf();
3116
3117 LOGVV("threadid=%d: (status %d -> %d)\n",
3118 self->threadId, self->status, newStatus);
3119
3120 oldStatus = self->status;
Andy McFadden8552f442010-09-16 15:32:43 -07003121 if (oldStatus == newStatus)
3122 return oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003123
3124 if (newStatus == THREAD_RUNNING) {
3125 /*
3126 * Change our status to THREAD_RUNNING. The transition requires
3127 * that we check for pending suspension, because the VM considers
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003128 * us to be "asleep" in all other states, and another thread could
3129 * be performing a GC now.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003130 *
Andy McFadden6dce9962010-08-23 16:45:24 -07003131 * The order of operations is very significant here. One way to
3132 * do this wrong is:
3133 *
3134 * GCing thread Our thread (in NATIVE)
3135 * ------------ ----------------------
3136 * check suspend count (== 0)
3137 * dvmSuspendAllThreads()
3138 * grab suspend-count lock
3139 * increment all suspend counts
3140 * release suspend-count lock
3141 * check thread state (== NATIVE)
3142 * all are suspended, begin GC
3143 * set state to RUNNING
3144 * (continue executing)
3145 *
3146 * We can correct this by grabbing the suspend-count lock and
3147 * performing both of our operations (check suspend count, set
3148 * state) while holding it, now we need to grab a mutex on every
3149 * transition to RUNNING.
3150 *
3151 * What we do instead is change the order of operations so that
3152 * the transition to RUNNING happens first. If we then detect
3153 * that the suspend count is nonzero, we switch to SUSPENDED.
3154 *
3155 * Appropriate compiler and memory barriers are required to ensure
3156 * that the operations are observed in the expected order.
3157 *
3158 * This does create a small window of opportunity where a GC in
3159 * progress could observe what appears to be a running thread (if
3160 * it happens to look between when we set to RUNNING and when we
3161 * switch to SUSPENDED). At worst this only affects assertions
3162 * and thread logging. (We could work around it with some sort
3163 * of intermediate "pre-running" state that is generally treated
3164 * as equivalent to running, but that doesn't seem worthwhile.)
3165 *
3166 * We can also solve this by combining the "status" and "suspend
3167 * count" fields into a single 32-bit value. This trades the
3168 * store/load barrier on transition to RUNNING for an atomic RMW
3169 * op on all transitions and all suspend count updates (also, all
3170 * accesses to status or the thread count require bit-fiddling).
3171 * It also eliminates the brief transition through RUNNING when
3172 * the thread is supposed to be suspended. This is possibly faster
3173 * on SMP and slightly more correct, but less convenient.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003174 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003175 android_atomic_acquire_store(newStatus, &self->status);
3176 if (self->suspendCount != 0) {
3177 fullSuspendCheck(self);
3178 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003179 } else {
3180 /*
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003181 * Not changing to THREAD_RUNNING. No additional work required.
Andy McFadden3469a7e2010-08-04 16:09:10 -07003182 *
3183 * We use a releasing store to ensure that, if we were RUNNING,
3184 * any updates we previously made to objects on the managed heap
3185 * will be observed before the state change.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003186 */
Andy McFadden6dce9962010-08-23 16:45:24 -07003187 assert(newStatus != THREAD_SUSPENDED);
Andy McFadden3469a7e2010-08-04 16:09:10 -07003188 android_atomic_release_store(newStatus, &self->status);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003189 }
3190
3191 return oldStatus;
3192}
3193
3194/*
3195 * Get a statically defined thread group from a field in the ThreadGroup
3196 * Class object. Expected arguments are "mMain" and "mSystem".
3197 */
3198static Object* getStaticThreadGroup(const char* fieldName)
3199{
3200 StaticField* groupField;
3201 Object* groupObj;
3202
3203 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3204 fieldName, "Ljava/lang/ThreadGroup;");
3205 if (groupField == NULL) {
3206 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3207 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3208 return NULL;
3209 }
3210 groupObj = dvmGetStaticFieldObject(groupField);
3211 if (groupObj == NULL) {
3212 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3213 dvmThrowException("Ljava/lang/InternalError;", NULL);
3214 return NULL;
3215 }
3216
3217 return groupObj;
3218}
3219Object* dvmGetSystemThreadGroup(void)
3220{
3221 return getStaticThreadGroup("mSystem");
3222}
3223Object* dvmGetMainThreadGroup(void)
3224{
3225 return getStaticThreadGroup("mMain");
3226}
3227
3228/*
3229 * Given a VMThread object, return the associated Thread*.
3230 *
3231 * NOTE: if the thread detaches, the struct Thread will disappear, and
3232 * we will be touching invalid data. For safety, lock the thread list
3233 * before calling this.
3234 */
3235Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3236{
3237 int vmData;
3238
3239 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003240
3241 if (false) {
3242 Thread* thread = gDvm.threadList;
3243 while (thread != NULL) {
3244 if ((Thread*)vmData == thread)
3245 break;
3246
3247 thread = thread->next;
3248 }
3249
3250 if (thread == NULL) {
3251 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3252 vmThreadObj, (Thread*)vmData);
3253 vmData = 0;
3254 }
3255 }
3256
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003257 return (Thread*) vmData;
3258}
3259
Andy McFadden2b94b302010-03-09 16:38:36 -08003260/*
3261 * Given a pthread handle, return the associated Thread*.
Andy McFadden0a24ef92010-03-12 13:39:59 -08003262 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -08003263 *
3264 * Returns NULL if the thread was not found.
3265 */
3266Thread* dvmGetThreadByHandle(pthread_t handle)
3267{
Andy McFadden0a24ef92010-03-12 13:39:59 -08003268 Thread* thread;
3269 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Andy McFadden2b94b302010-03-09 16:38:36 -08003270 if (thread->handle == handle)
3271 break;
Andy McFadden2b94b302010-03-09 16:38:36 -08003272 }
Andy McFadden0a24ef92010-03-12 13:39:59 -08003273 return thread;
3274}
Andy McFadden2b94b302010-03-09 16:38:36 -08003275
Andy McFadden0a24ef92010-03-12 13:39:59 -08003276/*
3277 * Given a threadId, return the associated Thread*.
3278 * Caller must hold the thread list lock.
3279 *
3280 * Returns NULL if the thread was not found.
3281 */
3282Thread* dvmGetThreadByThreadId(u4 threadId)
3283{
3284 Thread* thread;
3285 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
3286 if (thread->threadId == threadId)
3287 break;
3288 }
Andy McFadden2b94b302010-03-09 16:38:36 -08003289 return thread;
3290}
3291
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003292
3293/*
3294 * Conversion map for "nice" values.
3295 *
3296 * We use Android thread priority constants to be consistent with the rest
3297 * of the system. In some cases adjacent entries may overlap.
3298 */
3299static const int kNiceValues[10] = {
3300 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3301 ANDROID_PRIORITY_BACKGROUND + 6,
3302 ANDROID_PRIORITY_BACKGROUND + 3,
3303 ANDROID_PRIORITY_BACKGROUND,
3304 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3305 ANDROID_PRIORITY_NORMAL - 2,
3306 ANDROID_PRIORITY_NORMAL - 4,
3307 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3308 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3309 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3310};
3311
3312/*
3313 * Change the priority of a system thread to match that of the Thread object.
3314 *
3315 * We map a priority value from 1-10 to Linux "nice" values, where lower
3316 * numbers indicate higher priority.
3317 */
3318void dvmChangeThreadPriority(Thread* thread, int newPriority)
3319{
3320 pid_t pid = thread->systemTid;
3321 int newNice;
3322
3323 if (newPriority < 1 || newPriority > 10) {
3324 LOGW("bad priority %d\n", newPriority);
3325 newPriority = 5;
3326 }
3327 newNice = kNiceValues[newPriority-1];
3328
Andy McFaddend62c0b52009-08-04 15:02:12 -07003329 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003330 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003331 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003332 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003333 }
3334
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003335 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3336 char* str = dvmGetThreadName(thread);
3337 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3338 pid, str, newPriority, newNice, strerror(errno));
3339 free(str);
3340 } else {
3341 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3342 pid, newPriority, newNice);
3343 }
3344}
3345
3346/*
3347 * Get the thread priority for the current thread by querying the system.
3348 * This is useful when attaching a thread through JNI.
3349 *
3350 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3351 */
3352static int getThreadPriorityFromSystem(void)
3353{
3354 int i, sysprio, jprio;
3355
3356 errno = 0;
3357 sysprio = getpriority(PRIO_PROCESS, 0);
3358 if (sysprio == -1 && errno != 0) {
3359 LOGW("getpriority() failed: %s\n", strerror(errno));
3360 return THREAD_NORM_PRIORITY;
3361 }
3362
3363 jprio = THREAD_MIN_PRIORITY;
3364 for (i = 0; i < NELEM(kNiceValues); i++) {
3365 if (sysprio >= kNiceValues[i])
3366 break;
3367 jprio++;
3368 }
3369 if (jprio > THREAD_MAX_PRIORITY)
3370 jprio = THREAD_MAX_PRIORITY;
3371
3372 return jprio;
3373}
3374
3375
3376/*
3377 * Return true if the thread is on gDvm.threadList.
3378 * Caller should not hold gDvm.threadListLock.
3379 */
3380bool dvmIsOnThreadList(const Thread* thread)
3381{
3382 bool ret = false;
3383
3384 dvmLockThreadList(NULL);
3385 if (thread == gDvm.threadList) {
3386 ret = true;
3387 } else {
3388 ret = thread->prev != NULL || thread->next != NULL;
3389 }
3390 dvmUnlockThreadList();
3391
3392 return ret;
3393}
3394
3395/*
3396 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3397 * output target.
3398 */
3399void dvmDumpThread(Thread* thread, bool isRunning)
3400{
3401 DebugOutputTarget target;
3402
3403 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3404 dvmDumpThreadEx(&target, thread, isRunning);
3405}
3406
3407/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003408 * Try to get the scheduler group.
3409 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003410 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003411 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003412 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003413 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003414 * We return the part on the "cpu" line after the '/', which will be an
3415 * empty string for the default cgroup. If the string is longer than
3416 * "bufLen", the string will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003417 *
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003418 * On error, -1 is returned, and an error description will be stored in
3419 * the buffer.
Andy McFaddend62c0b52009-08-04 15:02:12 -07003420 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003421static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003422{
3423#ifdef HAVE_ANDROID_OS
3424 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003425 char lineBuf[256];
3426 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003427
Andy McFadden7f64ede2010-03-03 15:37:10 -08003428 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003429 if ((fp = fopen(pathBuf, "r")) == NULL) {
3430 snprintf(buf, bufLen, "[fopen-error:%d]", errno);
Andy McFadden7f64ede2010-03-03 15:37:10 -08003431 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003432 }
3433
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003434 while (fgets(lineBuf, sizeof(lineBuf) -1, fp) != NULL) {
3435 char* subsys;
3436 char* grp;
Andy McFadden7f64ede2010-03-03 15:37:10 -08003437 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003438
Andy McFadden7f64ede2010-03-03 15:37:10 -08003439 /* Junk the first field */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003440 subsys = strchr(lineBuf, ':');
3441 if (subsys == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003442 goto out_bad_data;
3443 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003444
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003445 if (strncmp(subsys, ":cpu:", 5) != 0) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003446 /* Not the subsys we're looking for */
3447 continue;
3448 }
3449
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003450 grp = strchr(subsys, '/');
3451 if (grp == NULL) {
Andy McFadden7f64ede2010-03-03 15:37:10 -08003452 goto out_bad_data;
3453 }
3454 grp++; /* Drop the leading '/' */
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003455
Andy McFadden7f64ede2010-03-03 15:37:10 -08003456 len = strlen(grp);
3457 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3458
3459 if (bufLen <= len) {
3460 len = bufLen - 1;
3461 }
3462 strncpy(buf, grp, len);
3463 buf[len] = '\0';
3464 fclose(fp);
3465 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003466 }
3467
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003468 snprintf(buf, bufLen, "[no-cpu-subsys]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003469 fclose(fp);
3470 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003471
3472out_bad_data:
Andy McFadden7f64ede2010-03-03 15:37:10 -08003473 LOGE("Bad cgroup data {%s}", lineBuf);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003474 snprintf(buf, bufLen, "[data-parse-failed]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003475 fclose(fp);
3476 return -1;
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003477
Andy McFaddend62c0b52009-08-04 15:02:12 -07003478#else
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003479 snprintf(buf, bufLen, "[n/a]");
Andy McFadden7f64ede2010-03-03 15:37:10 -08003480 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003481#endif
3482}
3483
3484/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003485 * Convert ThreadStatus to a string.
3486 */
3487const char* dvmGetThreadStatusStr(ThreadStatus status)
3488{
3489 switch (status) {
3490 case THREAD_ZOMBIE: return "ZOMBIE";
3491 case THREAD_RUNNING: return "RUNNABLE";
3492 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3493 case THREAD_MONITOR: return "MONITOR";
3494 case THREAD_WAIT: return "WAIT";
3495 case THREAD_INITIALIZING: return "INITIALIZING";
3496 case THREAD_STARTING: return "STARTING";
3497 case THREAD_NATIVE: return "NATIVE";
3498 case THREAD_VMWAIT: return "VMWAIT";
Andy McFadden6dce9962010-08-23 16:45:24 -07003499 case THREAD_SUSPENDED: return "SUSPENDED";
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003500 default: return "UNKNOWN";
3501 }
3502}
3503
3504/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003505 * Print information about the specified thread.
3506 *
3507 * Works best when the thread in question is "self" or has been suspended.
3508 * When dumping a separate thread that's still running, set "isRunning" to
3509 * use a more cautious thread dump function.
3510 */
3511void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3512 bool isRunning)
3513{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003514 Object* threadObj;
3515 Object* groupObj;
3516 StringObject* nameStr;
3517 char* threadName = NULL;
3518 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003519 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003520 bool isDaemon;
3521 int priority; // java.lang.Thread priority
3522 int policy; // pthread policy
3523 struct sched_param sp; // pthread scheduling parameters
Christopher Tate962f8962010-06-02 16:17:46 -07003524 char schedstatBuf[64]; // contents of /proc/[pid]/task/[tid]/schedstat
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003525
Andy McFaddene3346d82010-06-02 15:37:21 -07003526 /*
3527 * Get the java.lang.Thread object. This function gets called from
3528 * some weird debug contexts, so it's possible that there's a GC in
3529 * progress on some other thread. To decrease the chances of the
3530 * thread object being moved out from under us, we add the reference
3531 * to the tracked allocation list, which pins it in place.
3532 *
3533 * If threadObj is NULL, the thread is still in the process of being
3534 * attached to the VM, and there's really nothing interesting to
3535 * say about it yet.
3536 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003537 threadObj = thread->threadObj;
3538 if (threadObj == NULL) {
Andy McFaddene3346d82010-06-02 15:37:21 -07003539 LOGI("Can't dump thread %d: threadObj not set\n", thread->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003540 return;
3541 }
Andy McFaddene3346d82010-06-02 15:37:21 -07003542 dvmAddTrackedAlloc(threadObj, NULL);
3543
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003544 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3545 gDvm.offJavaLangThread_name);
3546 threadName = dvmCreateCstrFromString(nameStr);
3547
3548 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3549 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3550
3551 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3552 LOGW("Warning: pthread_getschedparam failed\n");
3553 policy = -1;
3554 sp.sched_priority = -1;
3555 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003556 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003557 sizeof(schedulerGroupBuf)) == 0 &&
3558 schedulerGroupBuf[0] == '\0') {
Andy McFaddend62c0b52009-08-04 15:02:12 -07003559 strcpy(schedulerGroupBuf, "default");
3560 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003561
3562 /* a null value for group is not expected, but deal with it anyway */
3563 groupObj = (Object*) dvmGetFieldObject(threadObj,
3564 gDvm.offJavaLangThread_group);
3565 if (groupObj != NULL) {
3566 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3567 "name", "Ljava/lang/String;");
3568 if (offset < 0) {
3569 LOGW("Unable to find 'name' field in ThreadGroup\n");
3570 } else {
3571 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3572 groupName = dvmCreateCstrFromString(nameStr);
3573 }
3574 }
3575 if (groupName == NULL)
Andy McFadden40607dd2010-06-28 16:57:24 -07003576 groupName = strdup("(null; initializing?)");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003577
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003578 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003579 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003580 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003581 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3582#if defined(WITH_JIT)
3583 thread->inJitCodeCache ? " JIT" : ""
3584#else
3585 ""
3586#endif
3587 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003588 dvmPrintDebugMessage(target,
Andy McFadden6dce9962010-08-23 16:45:24 -07003589 " | group=\"%s\" sCount=%d dsCount=%d obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003590 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden6dce9962010-08-23 16:45:24 -07003591 thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003592 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003593 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003594 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003595 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003596
Andy McFadden0a3f6982010-08-31 13:50:08 -07003597 /* get some bits from /proc/self/stat */
3598 ProcStatData procStatData;
3599 if (!dvmGetThreadStats(&procStatData, thread->systemTid)) {
3600 /* failed, use zeroed values */
3601 memset(&procStatData, 0, sizeof(procStatData));
3602 }
3603
3604 /* grab the scheduler stats for this thread */
3605 snprintf(schedstatBuf, sizeof(schedstatBuf), "/proc/self/task/%d/schedstat",
3606 thread->systemTid);
3607 int schedstatFd = open(schedstatBuf, O_RDONLY);
3608 strcpy(schedstatBuf, "0 0 0"); /* show this if open/read fails */
Christopher Tate962f8962010-06-02 16:17:46 -07003609 if (schedstatFd >= 0) {
Andy McFadden0a3f6982010-08-31 13:50:08 -07003610 ssize_t bytes;
Christopher Tate962f8962010-06-02 16:17:46 -07003611 bytes = read(schedstatFd, schedstatBuf, sizeof(schedstatBuf) - 1);
3612 close(schedstatFd);
Andy McFadden0a3f6982010-08-31 13:50:08 -07003613 if (bytes >= 1) {
3614 schedstatBuf[bytes-1] = '\0'; /* remove trailing newline */
Christopher Tate962f8962010-06-02 16:17:46 -07003615 }
3616 }
3617
Andy McFadden0a3f6982010-08-31 13:50:08 -07003618 /* show what we got */
3619 dvmPrintDebugMessage(target,
3620 " | schedstat=( %s ) utm=%lu stm=%lu core=%d\n",
3621 schedstatBuf, procStatData.utime, procStatData.stime,
3622 procStatData.processor);
3623
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003624#ifdef WITH_MONITOR_TRACKING
3625 if (!isRunning) {
3626 LockedObjectData* lod = thread->pLockedObjects;
3627 if (lod != NULL)
3628 dvmPrintDebugMessage(target, " | monitors held:\n");
3629 else
3630 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3631 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003632 Object* obj = lod->obj;
3633 if (obj->clazz == gDvm.classJavaLangClass) {
3634 ClassObject* clazz = (ClassObject*) obj;
3635 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3636 obj, lod->recursionCount, obj->clazz->descriptor,
3637 clazz->descriptor);
3638 } else {
3639 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3640 obj, lod->recursionCount, obj->clazz->descriptor);
3641 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003642 lod = lod->next;
3643 }
3644 }
3645#endif
3646
3647 if (isRunning)
3648 dvmDumpRunningThreadStack(target, thread);
3649 else
3650 dvmDumpThreadStack(target, thread);
3651
Andy McFaddene3346d82010-06-02 15:37:21 -07003652 dvmReleaseTrackedAlloc(threadObj, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003653 free(threadName);
3654 free(groupName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003655}
3656
3657/*
3658 * Get the name of a thread.
3659 *
3660 * For correctness, the caller should hold the thread list lock to ensure
3661 * that the thread doesn't go away mid-call.
3662 *
3663 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3664 */
3665char* dvmGetThreadName(Thread* thread)
3666{
3667 StringObject* nameObj;
3668
3669 if (thread->threadObj == NULL) {
3670 LOGW("threadObj is NULL, name not available\n");
3671 return strdup("-unknown-");
3672 }
3673
3674 nameObj = (StringObject*)
3675 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3676 return dvmCreateCstrFromString(nameObj);
3677}
3678
3679/*
3680 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3681 * an output target.
3682 */
3683void dvmDumpAllThreads(bool grabLock)
3684{
3685 DebugOutputTarget target;
3686
3687 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3688 dvmDumpAllThreadsEx(&target, grabLock);
3689}
3690
3691/*
3692 * Print information about all known threads. Assumes they have been
3693 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3694 *
3695 * If "grabLock" is true, we grab the thread lock list. This is important
3696 * to do unless the caller already holds the lock.
3697 */
3698void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3699{
3700 Thread* thread;
3701
3702 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3703
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003704#ifdef HAVE_ANDROID_OS
3705 dvmPrintDebugMessage(target,
3706 "(mutexes: tll=%x tsl=%x tscl=%x ghl=%x hwl=%x hwll=%x)\n",
3707 gDvm.threadListLock.value,
3708 gDvm._threadSuspendLock.value,
3709 gDvm.threadSuspendCountLock.value,
3710 gDvm.gcHeapLock.value,
3711 gDvm.heapWorkerLock.value,
3712 gDvm.heapWorkerListLock.value);
3713#endif
3714
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003715 if (grabLock)
3716 dvmLockThreadList(dvmThreadSelf());
3717
3718 thread = gDvm.threadList;
3719 while (thread != NULL) {
3720 dvmDumpThreadEx(target, thread, false);
3721
3722 /* verify link */
3723 assert(thread->next == NULL || thread->next->prev == thread);
3724
3725 thread = thread->next;
3726 }
3727
3728 if (grabLock)
3729 dvmUnlockThreadList();
3730}
3731
Andy McFadden384ef6b2010-03-15 17:24:55 -07003732/*
3733 * Nuke the target thread from orbit.
3734 *
3735 * The idea is to send a "crash" signal to the target thread so that
3736 * debuggerd will take notice and dump an appropriate stack trace.
3737 * Because of the way debuggerd works, we have to throw the same signal
3738 * at it twice.
3739 *
3740 * This does not necessarily cause the entire process to stop, but once a
3741 * thread has been nuked the rest of the system is likely to be unstable.
3742 * This returns so that some limited set of additional operations may be
Andy McFaddend4e09522010-03-23 12:34:43 -07003743 * performed, but it's advisable (and expected) to call dvmAbort soon.
3744 * (This is NOT a way to simply cancel a thread.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003745 */
3746void dvmNukeThread(Thread* thread)
3747{
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003748 int killResult;
3749
Andy McFaddena388a162010-03-18 16:27:14 -07003750 /* suppress the heapworker watchdog to assist anyone using a debugger */
3751 gDvm.nativeDebuggerActive = true;
3752
Andy McFadden384ef6b2010-03-15 17:24:55 -07003753 /*
Andy McFaddend4e09522010-03-23 12:34:43 -07003754 * Send the signals, separated by a brief interval to allow debuggerd
3755 * to work its magic. An uncommon signal like SIGFPE or SIGSTKFLT
3756 * can be used instead of SIGSEGV to avoid making it look like the
3757 * code actually crashed at the current point of execution.
3758 *
3759 * (Observed behavior: with SIGFPE, debuggerd will dump the target
3760 * thread and then the thread that calls dvmAbort. With SIGSEGV,
3761 * you don't get the second stack trace; possibly something in the
3762 * kernel decides that a signal has already been sent and it's time
3763 * to just kill the process. The position in the current thread is
3764 * generally known, so the second dump is not useful.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003765 *
Andy McFaddena388a162010-03-18 16:27:14 -07003766 * The target thread can continue to execute between the two signals.
3767 * (The first just causes debuggerd to attach to it.)
Andy McFadden384ef6b2010-03-15 17:24:55 -07003768 */
Andy McFaddend4e09522010-03-23 12:34:43 -07003769 LOGD("threadid=%d: sending two SIGSTKFLTs to threadid=%d (tid=%d) to"
3770 " cause debuggerd dump\n",
3771 dvmThreadSelf()->threadId, thread->threadId, thread->systemTid);
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003772 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3773 if (killResult != 0) {
3774 LOGD("NOTE: pthread_kill #1 failed: %s\n", strerror(killResult));
3775 }
Andy McFaddena388a162010-03-18 16:27:14 -07003776 usleep(2 * 1000 * 1000); // TODO: timed-wait until debuggerd attaches
Andy McFaddenddd9d0b2010-09-24 14:18:03 -07003777 killResult = pthread_kill(thread->handle, SIGSTKFLT);
3778 if (killResult != 0) {
3779 LOGD("NOTE: pthread_kill #2 failed: %s\n", strerror(killResult));
3780 }
Andy McFadden7122d862010-03-19 15:18:57 -07003781 LOGD("Sent, pausing to let debuggerd run\n");
Andy McFaddena388a162010-03-18 16:27:14 -07003782 usleep(8 * 1000 * 1000); // TODO: timed-wait until debuggerd finishes
Andy McFaddend4e09522010-03-23 12:34:43 -07003783
3784 /* ignore SIGSEGV so the eventual dmvAbort() doesn't notify debuggerd */
3785 signal(SIGSEGV, SIG_IGN);
Andy McFadden384ef6b2010-03-15 17:24:55 -07003786 LOGD("Continuing\n");
3787}
3788
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003789#ifdef WITH_MONITOR_TRACKING
3790/*
3791 * Count up the #of locked objects in the current thread.
3792 */
3793static int getThreadObjectCount(const Thread* self)
3794{
3795 LockedObjectData* lod;
3796 int count = 0;
3797
3798 lod = self->pLockedObjects;
3799 while (lod != NULL) {
3800 count++;
3801 lod = lod->next;
3802 }
3803 return count;
3804}
3805
3806/*
3807 * Add the object to the thread's locked object list if it doesn't already
3808 * exist. The most recently added object is the most likely to be released
3809 * next, so we insert at the head of the list.
3810 *
3811 * If it already exists, we increase the recursive lock count.
3812 *
3813 * The object's lock may be thin or fat.
3814 */
3815void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3816{
3817 LockedObjectData* newLod;
3818 LockedObjectData* lod;
3819 int* trace;
3820 int depth;
3821
3822 lod = self->pLockedObjects;
3823 while (lod != NULL) {
3824 if (lod->obj == obj) {
3825 lod->recursionCount++;
3826 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3827 return;
3828 }
3829 lod = lod->next;
3830 }
3831
3832 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3833 if (newLod == NULL) {
3834 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3835 return;
3836 }
3837 newLod->obj = obj;
3838 newLod->recursionCount = 0;
3839
3840 if (withTrace) {
3841 trace = dvmFillInStackTraceRaw(self, &depth);
3842 newLod->rawStackTrace = trace;
3843 newLod->stackDepth = depth;
3844 }
3845
3846 newLod->next = self->pLockedObjects;
3847 self->pLockedObjects = newLod;
3848
3849 LOGV("+++ threadid=%d: added %p, now %d\n",
3850 self->threadId, newLod, getThreadObjectCount(self));
3851}
3852
3853/*
3854 * Remove the object from the thread's locked object list. If the entry
3855 * has a nonzero recursion count, we just decrement the count instead.
3856 */
3857void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3858{
3859 LockedObjectData* lod;
3860 LockedObjectData* prevLod;
3861
3862 lod = self->pLockedObjects;
3863 prevLod = NULL;
3864 while (lod != NULL) {
3865 if (lod->obj == obj) {
3866 if (lod->recursionCount > 0) {
3867 lod->recursionCount--;
3868 LOGV("+++ -recursive lock %p -> %d\n",
3869 obj, lod->recursionCount);
3870 return;
3871 } else {
3872 break;
3873 }
3874 }
3875 prevLod = lod;
3876 lod = lod->next;
3877 }
3878
3879 if (lod == NULL) {
3880 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3881 return;
3882 }
3883 if (prevLod == NULL) {
3884 /* first item in list */
3885 assert(self->pLockedObjects == lod);
3886 self->pLockedObjects = lod->next;
3887 } else {
3888 /* middle/end of list */
3889 prevLod->next = lod->next;
3890 }
3891
3892 LOGV("+++ threadid=%d: removed %p, now %d\n",
3893 self->threadId, lod, getThreadObjectCount(self));
3894 free(lod->rawStackTrace);
3895 free(lod);
3896}
3897
3898/*
3899 * If the specified object is already in the thread's locked object list,
3900 * return the LockedObjectData struct. Otherwise return NULL.
3901 */
3902LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3903{
3904 LockedObjectData* lod;
3905
3906 lod = self->pLockedObjects;
3907 while (lod != NULL) {
3908 if (lod->obj == obj)
3909 return lod;
3910 lod = lod->next;
3911 }
3912 return NULL;
3913}
3914#endif /*WITH_MONITOR_TRACKING*/
3915
3916
3917/*
3918 * GC helper functions
3919 */
3920
The Android Open Source Project99409882009-03-18 22:20:24 -07003921/*
3922 * Add the contents of the registers from the interpreted call stack.
3923 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003924static void gcScanInterpStackReferences(Thread *thread)
3925{
3926 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003927#if WITH_EXTRA_GC_CHECKS > 1
3928 bool first = true;
3929#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003930
3931 framePtr = (const u4 *)thread->curFrame;
3932 while (framePtr != NULL) {
3933 const StackSaveArea *saveArea;
3934 const Method *method;
3935
3936 saveArea = SAVEAREA_FROM_FP(framePtr);
3937 method = saveArea->method;
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07003938 if (method != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003939#ifdef COUNT_PRECISE_METHODS
3940 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003941 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3942 LOGI("PGC: added %s.%s %p\n",
3943 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003944#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003945#if WITH_EXTRA_GC_CHECKS > 1
3946 /*
3947 * May also want to enable the memset() in the "invokeMethod"
3948 * goto target in the portable interpreter. That sets the stack
3949 * to a pattern that makes referring to uninitialized data
3950 * very obvious.
3951 */
3952
3953 if (first) {
3954 /*
3955 * First frame, isn't native, check the "alternate" saved PC
3956 * as a sanity check.
3957 *
3958 * It seems like we could check the second frame if the first
3959 * is native, since the PCs should be the same. It turns out
3960 * this doesn't always work. The problem is that we could
3961 * have calls in the sequence:
3962 * interp method #2
3963 * native method
3964 * interp method #1
3965 *
3966 * and then GC while in the native method after returning
3967 * from interp method #2. The currentPc on the stack is
3968 * for interp method #1, but thread->currentPc2 is still
3969 * set for the last thing interp method #2 did.
3970 *
3971 * This can also happen in normal execution:
3972 * - sget-object on not-yet-loaded class
3973 * - class init updates currentPc2
3974 * - static field init is handled by parsing annotations;
3975 * static String init requires creation of a String object,
3976 * which can cause a GC
3977 *
3978 * Essentially, any pattern that involves executing
3979 * interpreted code and then causes an allocation without
3980 * executing instructions in the original method will hit
3981 * this. These are rare enough that the test still has
3982 * some value.
3983 */
3984 if (saveArea->xtra.currentPc != thread->currentPc2) {
3985 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3986 saveArea->xtra.currentPc, thread->currentPc2,
3987 method->clazz->descriptor, method->name, method->insns);
3988 if (saveArea->xtra.currentPc != NULL)
3989 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3990 if (thread->currentPc2 != NULL)
3991 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3992 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003993 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003994 } else {
3995 /*
3996 * It's unusual, but not impossible, for a non-first frame
3997 * to be at something other than a method invocation. For
3998 * example, if we do a new-instance on a nonexistent class,
3999 * we'll have a lot of class loader activity on the stack
4000 * above the frame with the "new" operation. Could also
4001 * happen while we initialize a Throwable when an instruction
4002 * fails.
4003 *
4004 * So there's not much we can do here to verify the PC,
4005 * except to verify that it's a GC point.
4006 */
4007 }
4008 assert(saveArea->xtra.currentPc != NULL);
4009#endif
4010
4011 const RegisterMap* pMap;
4012 const u1* regVector;
4013 int i;
4014
Andy McFaddencf8b55c2009-04-13 15:26:03 -07004015 Method* nonConstMethod = (Method*) method; // quiet gcc
4016 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07004017 if (pMap != NULL) {
4018 /* found map, get registers for this address */
4019 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07004020 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07004021 if (regVector == NULL) {
4022 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
4023 method->clazz->descriptor, method->name, addr);
4024 } else {
4025 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
4026 method->clazz->descriptor, method->name, addr,
4027 thread->threadId);
4028 }
4029 } else {
4030 /*
4031 * No map found. If precise GC is disabled this is
4032 * expected -- we don't create pointers to the map data even
4033 * if it's present -- but if it's enabled it means we're
4034 * unexpectedly falling back on a conservative scan, so it's
4035 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07004036 */
4037 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07004038 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07004039 method->clazz->descriptor, method->name);
4040 }
4041 regVector = NULL;
4042 }
4043
4044 if (regVector == NULL) {
4045 /* conservative scan */
4046 for (i = method->registersSize - 1; i >= 0; i--) {
4047 u4 rval = *framePtr++;
4048 if (rval != 0 && (rval & 0x3) == 0) {
4049 dvmMarkIfObject((Object *)rval);
4050 }
4051 }
4052 } else {
4053 /*
4054 * Precise scan. v0 is at the lowest address on the
4055 * interpreted stack, and is the first bit in the register
4056 * vector, so we can walk through the register map and
4057 * memory in the same direction.
4058 *
4059 * A '1' bit indicates a live reference.
4060 */
4061 u2 bits = 1 << 1;
4062 for (i = method->registersSize - 1; i >= 0; i--) {
4063 u4 rval = *framePtr++;
4064
4065 bits >>= 1;
4066 if (bits == 1) {
4067 /* set bit 9 so we can tell when we're empty */
4068 bits = *regVector++ | 0x0100;
4069 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
4070 }
4071
4072 if (rval != 0 && (bits & 0x01) != 0) {
4073 /*
4074 * Non-null, register marked as live reference. This
4075 * should always be a valid object.
4076 */
4077#if WITH_EXTRA_GC_CHECKS > 0
4078 if ((rval & 0x3) != 0 ||
4079 !dvmIsValidObject((Object*) rval))
4080 {
4081 /* this is very bad */
4082 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
4083 method->registersSize-1 - i, rval);
Andy McFaddenbe420e72010-10-18 13:28:31 -07004084 LOGE("PGC: %s.%s addr 0x%04x\n",
4085 method->clazz->descriptor, method->name,
4086 saveArea->xtra.currentPc - method->insns);
The Android Open Source Project99409882009-03-18 22:20:24 -07004087 } else
4088#endif
4089 {
4090 dvmMarkObjectNonNull((Object *)rval);
4091 }
4092 } else {
4093 /*
4094 * Null or non-reference, do nothing at all.
4095 */
4096#if WITH_EXTRA_GC_CHECKS > 1
4097 if (dvmIsValidObject((Object*) rval)) {
4098 /* this is normal, but we feel chatty */
4099 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
4100 method->registersSize-1 - i, rval);
4101 }
4102#endif
4103 }
4104 }
4105 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004106 }
4107 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004108
The Android Open Source Project99409882009-03-18 22:20:24 -07004109#if WITH_EXTRA_GC_CHECKS > 1
4110 first = false;
4111#endif
4112
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004113 /* Don't fall into an infinite loop if things get corrupted.
4114 */
4115 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
4116 saveArea->prevFrame == NULL);
4117 framePtr = saveArea->prevFrame;
4118 }
4119}
4120
4121static void gcScanReferenceTable(ReferenceTable *refTable)
4122{
4123 Object **op;
4124
4125 //TODO: these asserts are overkill; turn them off when things stablize.
4126 assert(refTable != NULL);
4127 assert(refTable->table != NULL);
4128 assert(refTable->nextEntry != NULL);
4129 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
4130 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
4131
4132 op = refTable->table;
4133 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
4134 dvmMarkObjectNonNull(*(op++));
4135 }
4136}
4137
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004138#ifdef USE_INDIRECT_REF
Andy McFaddend5ab7262009-08-25 07:19:34 -07004139static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
4140{
4141 Object** op = pRefTable->table;
4142 int numEntries = dvmIndirectRefTableEntries(pRefTable);
4143 int i;
4144
4145 for (i = 0; i < numEntries; i++) {
4146 Object* obj = *op;
4147 if (obj != NULL)
4148 dvmMarkObjectNonNull(obj);
4149 op++;
4150 }
4151}
Brian Carlstromfbdcfb92010-05-28 15:42:12 -07004152#endif
Andy McFaddend5ab7262009-08-25 07:19:34 -07004153
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004154/*
4155 * Scan a Thread and mark any objects it references.
4156 */
4157static void gcScanThread(Thread *thread)
4158{
4159 assert(thread != NULL);
4160
4161 /*
4162 * The target thread must be suspended or in a state where it can't do
4163 * any harm (e.g. in Object.wait()). The only exception is the current
4164 * thread, which will still be active and in the "running" state.
4165 *
Andy McFadden6dce9962010-08-23 16:45:24 -07004166 * It's possible to encounter a false-positive here because a thread
4167 * transitioning to running from (say) vmwait or native will briefly
4168 * set their status to running before switching to suspended. This
4169 * is highly unlikely, but does mean that we don't want to abort if
4170 * the situation arises.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004171 */
Andy McFadden6dce9962010-08-23 16:45:24 -07004172 if (thread->status == THREAD_RUNNING && thread != dvmThreadSelf()) {
Andy McFaddend40223e2009-12-07 15:35:51 -08004173 Thread* self = dvmThreadSelf();
Andy McFadden6dce9962010-08-23 16:45:24 -07004174 LOGW("threadid=%d: Warning: GC scanning a running thread (%d)\n",
Andy McFaddend40223e2009-12-07 15:35:51 -08004175 self->threadId, thread->threadId);
4176 dvmDumpThread(thread, true);
4177 LOGW("Found by:\n");
4178 dvmDumpThread(self, false);
4179
Andy McFadden6dce9962010-08-23 16:45:24 -07004180 /* continue anyway */
Andy McFaddend40223e2009-12-07 15:35:51 -08004181 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004182
4183 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
4184
4185 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
4186
4187 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
4188
4189 dvmMarkObject(thread->exception); // usually NULL
4190 gcScanReferenceTable(&thread->internalLocalRefTable);
4191
4192 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
4193
Andy McFaddend5ab7262009-08-25 07:19:34 -07004194#ifdef USE_INDIRECT_REF
4195 gcScanIndirectRefTable(&thread->jniLocalRefTable);
4196#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004197 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07004198#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004199
4200 if (thread->jniMonitorRefTable.table != NULL) {
4201 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
4202
4203 gcScanReferenceTable(&thread->jniMonitorRefTable);
4204 }
4205
4206 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
4207
4208 gcScanInterpStackReferences(thread);
4209
4210 HPROF_CLEAR_GC_SCAN_STATE();
4211}
4212
4213static void gcScanAllThreads()
4214{
4215 Thread *thread;
4216
4217 /* Lock the thread list so we can safely use the
4218 * next/prev pointers.
4219 */
4220 dvmLockThreadList(dvmThreadSelf());
4221
4222 for (thread = gDvm.threadList; thread != NULL;
4223 thread = thread->next)
4224 {
4225 /* We need to scan our own stack, so don't special-case
4226 * the current thread.
4227 */
4228 gcScanThread(thread);
4229 }
4230
4231 dvmUnlockThreadList();
4232}
4233
4234void dvmGcScanRootThreadGroups()
4235{
4236 /* We scan the VM's list of threads instead of going
4237 * through the actual ThreadGroups, but it should be
4238 * equivalent.
4239 *
Jeff Hao97319a82009-08-12 16:57:15 -07004240 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004241 * the root set, which should always be true; it's
4242 * loaded by the built-in class loader, which is part
4243 * of the root set.
4244 */
4245 gcScanAllThreads();
4246}