blob: b2d57764bf120dc555eeb280f241f8663bbf4223 [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"
Bob Lee2fe146a2009-09-10 00:36:29 +020021#include "native/SystemThread.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080022
23#include "utils/threads.h" // need Android thread priorities
24
25#include <stdlib.h>
26#include <unistd.h>
27#include <sys/time.h>
28#include <sys/resource.h>
29#include <sys/mman.h>
30#include <errno.h>
Andy McFaddend62c0b52009-08-04 15:02:12 -070031#include <fcntl.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080032
San Mehat5a2056c2009-09-12 10:10:13 -070033#include <cutils/sched_policy.h>
34
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080035#if defined(HAVE_PRCTL)
36#include <sys/prctl.h>
37#endif
38
Ben Chengfe1be872009-08-21 16:18:46 -070039#if defined(WITH_SELF_VERIFICATION)
40#include "interp/Jit.h" // need for self verification
41#endif
42
43
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080044/* desktop Linux needs a little help with gettid() */
45#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
46#define __KERNEL__
47# include <linux/unistd.h>
48#ifdef _syscall0
49_syscall0(pid_t,gettid)
50#else
51pid_t gettid() { return syscall(__NR_gettid);}
52#endif
53#undef __KERNEL__
54#endif
55
San Mehat256fc152009-04-21 14:03:06 -070056// Change this to enable logging on cgroup errors
57#define ENABLE_CGROUP_ERR_LOGGING 0
58
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080059// change this to LOGV/LOGD to debug thread activity
60#define LOG_THREAD LOGVV
61
62/*
63Notes on Threading
64
65All threads are native pthreads. All threads, except the JDWP debugger
66thread, are visible to code running in the VM and to the debugger. (We
67don't want the debugger to try to manipulate the thread that listens for
68instructions from the debugger.) Internal VM threads are in the "system"
69ThreadGroup, all others are in the "main" ThreadGroup, per convention.
70
71The GC only runs when all threads have been suspended. Threads are
72expected to suspend themselves, using a "safe point" mechanism. We check
73for a suspend request at certain points in the main interpreter loop,
74and on requests coming in from native code (e.g. all JNI functions).
75Certain debugger events may inspire threads to self-suspend.
76
77Native methods must use JNI calls to modify object references to avoid
78clashes with the GC. JNI doesn't provide a way for native code to access
79arrays of objects as such -- code must always get/set individual entries --
80so it should be possible to fully control access through JNI.
81
82Internal native VM threads, such as the finalizer thread, must explicitly
83check for suspension periodically. In most cases they will be sound
84asleep on a condition variable, and won't notice the suspension anyway.
85
86Threads may be suspended by the GC, debugger, or the SIGQUIT listener
87thread. The debugger may suspend or resume individual threads, while the
88GC always suspends all threads. Each thread has a "suspend count" that
89is incremented on suspend requests and decremented on resume requests.
90When the count is zero, the thread is runnable. This allows us to fulfill
91a debugger requirement: if the debugger suspends a thread, the thread is
92not allowed to run again until the debugger resumes it (or disconnects,
93in which case we must resume all debugger-suspended threads).
94
95Paused threads sleep on a condition variable, and are awoken en masse.
96Certain "slow" VM operations, such as starting up a new thread, will be
97done in a separate "VMWAIT" state, so that the rest of the VM doesn't
98freeze up waiting for the operation to finish. Threads must check for
99pending suspension when leaving VMWAIT.
100
101Because threads suspend themselves while interpreting code or when native
102code makes JNI calls, there is no risk of suspending while holding internal
103VM locks. All threads can enter a suspended (or native-code-only) state.
104Also, we don't have to worry about object references existing solely
105in hardware registers.
106
107We do, however, have to worry about objects that were allocated internally
108and aren't yet visible to anything else in the VM. If we allocate an
109object, and then go to sleep on a mutex after changing to a non-RUNNING
110state (e.g. while trying to allocate a second object), the first object
111could be garbage-collected out from under us while we sleep. To manage
112this, we automatically add all allocated objects to an internal object
113tracking list, and only remove them when we know we won't be suspended
114before the object appears in the GC root set.
115
116The debugger may choose to suspend or resume a single thread, which can
117lead to application-level deadlocks; this is expected behavior. The VM
118will only check for suspension of single threads when the debugger is
119active (the java.lang.Thread calls for this are deprecated and hence are
120not supported). Resumption of a single thread is handled by decrementing
121the thread's suspend count and sending a broadcast signal to the condition
122variable. (This will cause all threads to wake up and immediately go back
123to sleep, which isn't tremendously efficient, but neither is having the
124debugger attached.)
125
126The debugger is not allowed to resume threads suspended by the GC. This
127is trivially enforced by ignoring debugger requests while the GC is running
128(the JDWP thread is suspended during GC).
129
130The VM maintains a Thread struct for every pthread known to the VM. There
131is a java/lang/Thread object associated with every Thread. At present,
132there is no safe way to go from a Thread object to a Thread struct except by
133locking and scanning the list; this is necessary because the lifetimes of
134the two are not closely coupled. We may want to change this behavior,
135though at present the only performance impact is on the debugger (see
136threadObjToThread()). See also notes about dvmDetachCurrentThread().
137*/
138/*
139Alternate implementation (signal-based):
140
141Threads run without safe points -- zero overhead. The VM uses a signal
142(e.g. pthread_kill(SIGUSR1)) to notify threads of suspension or resumption.
143
144The trouble with using signals to suspend threads is that it means a thread
145can be in the middle of an operation when garbage collection starts.
146To prevent some sticky situations, we have to introduce critical sections
147to the VM code.
148
149Critical sections temporarily block suspension for a given thread.
150The thread must move to a non-blocked state (and self-suspend) after
151finishing its current task. If the thread blocks on a resource held
152by a suspended thread, we're hosed.
153
154One approach is to require that no blocking operations, notably
155acquisition of mutexes, can be performed within a critical section.
156This is too limiting. For example, if thread A gets suspended while
157holding the thread list lock, it will prevent the GC or debugger from
158being able to safely access the thread list. We need to wrap the critical
159section around the entire operation (enter critical, get lock, do stuff,
160release lock, exit critical).
161
162A better approach is to declare that certain resources can only be held
163within critical sections. A thread that enters a critical section and
164then gets blocked on the thread list lock knows that the thread it is
165waiting for is also in a critical section, and will release the lock
166before suspending itself. Eventually all threads will complete their
167operations and self-suspend. For this to work, the VM must:
168
169 (1) Determine the set of resources that may be accessed from the GC or
170 debugger threads. The mutexes guarding those go into the "critical
171 resource set" (CRS).
172 (2) Ensure that no resource in the CRS can be acquired outside of a
173 critical section. This can be verified with an assert().
174 (3) Ensure that only resources in the CRS can be held while in a critical
175 section. This is harder to enforce.
176
177If any of these conditions are not met, deadlock can ensue when grabbing
178resources in the GC or debugger (#1) or waiting for threads to suspend
179(#2,#3). (You won't actually deadlock in the GC, because if the semantics
180above are followed you don't need to lock anything in the GC. The risk is
181rather that the GC will access data structures in an intermediate state.)
182
183This approach requires more care and awareness in the VM than
184safe-pointing. Because the GC and debugger are fairly intrusive, there
185really aren't any internal VM resources that aren't shared. Thus, the
186enter/exit critical calls can be added to internal mutex wrappers, which
187makes it easy to get #1 and #2 right.
188
189An ordering should be established for all locks to avoid deadlocks.
190
191Monitor locks, which are also implemented with pthread calls, should not
192cause any problems here. Threads fighting over such locks will not be in
193critical sections and can be suspended freely.
194
195This can get tricky if we ever need exclusive access to VM and non-VM
196resources at the same time. It's not clear if this is a real concern.
197
198There are (at least) two ways to handle the incoming signals:
199
200 (a) Always accept signals. If we're in a critical section, the signal
201 handler just returns without doing anything (the "suspend level"
202 should have been incremented before the signal was sent). Otherwise,
203 if the "suspend level" is nonzero, we go to sleep.
204 (b) Block signals in critical sections. This ensures that we can't be
205 interrupted in a critical section, but requires pthread_sigmask()
206 calls on entry and exit.
207
208This is a choice between blocking the message and blocking the messenger.
209Because UNIX signals are unreliable (you can only know that you have been
210signaled, not whether you were signaled once or 10 times), the choice is
211not significant for correctness. The choice depends on the efficiency
212of pthread_sigmask() and the desire to actually block signals. Either way,
213it is best to ensure that there is only one indication of "blocked";
214having two (i.e. block signals and set a flag, then only send a signal
215if the flag isn't set) can lead to race conditions.
216
217The signal handler must take care to copy registers onto the stack (via
218setjmp), so that stack scans find all references. Because we have to scan
219native stacks, "exact" GC is not possible with this approach.
220
221Some other concerns with flinging signals around:
222 - Odd interactions with some debuggers (e.g. gdb on the Mac)
223 - Restrictions on some standard library calls during GC (e.g. don't
224 use printf on stdout to print GC debug messages)
225*/
226
Carl Shapiro59a93122010-01-26 17:12:51 -0800227#define kMaxThreadId ((1 << 16) - 1)
228#define kMainThreadId 1
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800229
230
231static Thread* allocThread(int interpStackSize);
232static bool prepareThread(Thread* thread);
233static void setThreadSelf(Thread* thread);
234static void unlinkThread(Thread* thread);
235static void freeThread(Thread* thread);
236static void assignThreadId(Thread* thread);
237static bool createFakeEntryFrame(Thread* thread);
238static bool createFakeRunFrame(Thread* thread);
239static void* interpThreadStart(void* arg);
240static void* internalThreadStart(void* arg);
241static void threadExitUncaughtException(Thread* thread, Object* group);
242static void threadExitCheck(void* arg);
243static void waitForThreadSuspend(Thread* self, Thread* thread);
244static int getThreadPriorityFromSystem(void);
245
Bill Buzbee46cd5b62009-06-05 15:36:06 -0700246/*
247 * The JIT needs to know if any thread is suspended. We do this by
248 * maintaining a global sum of all threads' suspend counts. All suspendCount
249 * updates should go through this after aquiring threadSuspendCountLock.
250 */
251static inline void dvmAddToThreadSuspendCount(int *pSuspendCount, int delta)
252{
253 *pSuspendCount += delta;
254 gDvm.sumThreadSuspendCount += delta;
255}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800256
257/*
258 * Initialize thread list and main thread's environment. We need to set
259 * up some basic stuff so that dvmThreadSelf() will work when we start
260 * loading classes (e.g. to check for exceptions).
261 */
262bool dvmThreadStartup(void)
263{
264 Thread* thread;
265
266 /* allocate a TLS slot */
267 if (pthread_key_create(&gDvm.pthreadKeySelf, threadExitCheck) != 0) {
268 LOGE("ERROR: pthread_key_create failed\n");
269 return false;
270 }
271
272 /* test our pthread lib */
273 if (pthread_getspecific(gDvm.pthreadKeySelf) != NULL)
274 LOGW("WARNING: newly-created pthread TLS slot is not NULL\n");
275
276 /* prep thread-related locks and conditions */
277 dvmInitMutex(&gDvm.threadListLock);
278 pthread_cond_init(&gDvm.threadStartCond, NULL);
279 //dvmInitMutex(&gDvm.vmExitLock);
280 pthread_cond_init(&gDvm.vmExitCond, NULL);
281 dvmInitMutex(&gDvm._threadSuspendLock);
282 dvmInitMutex(&gDvm.threadSuspendCountLock);
283 pthread_cond_init(&gDvm.threadSuspendCountCond, NULL);
284#ifdef WITH_DEADLOCK_PREDICTION
285 dvmInitMutex(&gDvm.deadlockHistoryLock);
286#endif
287
288 /*
289 * Dedicated monitor for Thread.sleep().
290 * TODO: change this to an Object* so we don't have to expose this
291 * call, and we interact better with JDWP monitor calls. Requires
292 * deferring the object creation to much later (e.g. final "main"
293 * thread prep) or until first use.
294 */
295 gDvm.threadSleepMon = dvmCreateMonitor(NULL);
296
297 gDvm.threadIdMap = dvmAllocBitVector(kMaxThreadId, false);
298
299 thread = allocThread(gDvm.stackSize);
300 if (thread == NULL)
301 return false;
302
303 /* switch mode for when we run initializers */
304 thread->status = THREAD_RUNNING;
305
306 /*
307 * We need to assign the threadId early so we can lock/notify
308 * object monitors. We'll set the "threadObj" field later.
309 */
310 prepareThread(thread);
311 gDvm.threadList = thread;
312
313#ifdef COUNT_PRECISE_METHODS
314 gDvm.preciseMethods = dvmPointerSetAlloc(200);
315#endif
316
317 return true;
318}
319
320/*
321 * We're a little farther up now, and can load some basic classes.
322 *
323 * We're far enough along that we can poke at java.lang.Thread and friends,
324 * but should not assume that static initializers have run (or cause them
325 * to do so). That means no object allocations yet.
326 */
327bool dvmThreadObjStartup(void)
328{
329 /*
330 * Cache the locations of these classes. It's likely that we're the
331 * first to reference them, so they're being loaded now.
332 */
333 gDvm.classJavaLangThread =
334 dvmFindSystemClassNoInit("Ljava/lang/Thread;");
335 gDvm.classJavaLangVMThread =
336 dvmFindSystemClassNoInit("Ljava/lang/VMThread;");
337 gDvm.classJavaLangThreadGroup =
338 dvmFindSystemClassNoInit("Ljava/lang/ThreadGroup;");
339 if (gDvm.classJavaLangThread == NULL ||
340 gDvm.classJavaLangThreadGroup == NULL ||
341 gDvm.classJavaLangThreadGroup == NULL)
342 {
343 LOGE("Could not find one or more essential thread classes\n");
344 return false;
345 }
346
347 /*
348 * Cache field offsets. This makes things a little faster, at the
349 * expense of hard-coding non-public field names into the VM.
350 */
351 gDvm.offJavaLangThread_vmThread =
352 dvmFindFieldOffset(gDvm.classJavaLangThread,
353 "vmThread", "Ljava/lang/VMThread;");
354 gDvm.offJavaLangThread_group =
355 dvmFindFieldOffset(gDvm.classJavaLangThread,
356 "group", "Ljava/lang/ThreadGroup;");
357 gDvm.offJavaLangThread_daemon =
358 dvmFindFieldOffset(gDvm.classJavaLangThread, "daemon", "Z");
359 gDvm.offJavaLangThread_name =
360 dvmFindFieldOffset(gDvm.classJavaLangThread,
361 "name", "Ljava/lang/String;");
362 gDvm.offJavaLangThread_priority =
363 dvmFindFieldOffset(gDvm.classJavaLangThread, "priority", "I");
364
365 if (gDvm.offJavaLangThread_vmThread < 0 ||
366 gDvm.offJavaLangThread_group < 0 ||
367 gDvm.offJavaLangThread_daemon < 0 ||
368 gDvm.offJavaLangThread_name < 0 ||
369 gDvm.offJavaLangThread_priority < 0)
370 {
371 LOGE("Unable to find all fields in java.lang.Thread\n");
372 return false;
373 }
374
375 gDvm.offJavaLangVMThread_thread =
376 dvmFindFieldOffset(gDvm.classJavaLangVMThread,
377 "thread", "Ljava/lang/Thread;");
378 gDvm.offJavaLangVMThread_vmData =
379 dvmFindFieldOffset(gDvm.classJavaLangVMThread, "vmData", "I");
380 if (gDvm.offJavaLangVMThread_thread < 0 ||
381 gDvm.offJavaLangVMThread_vmData < 0)
382 {
383 LOGE("Unable to find all fields in java.lang.VMThread\n");
384 return false;
385 }
386
387 /*
388 * Cache the vtable offset for "run()".
389 *
390 * We don't want to keep the Method* because then we won't find see
391 * methods defined in subclasses.
392 */
393 Method* meth;
394 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThread, "run", "()V");
395 if (meth == NULL) {
396 LOGE("Unable to find run() in java.lang.Thread\n");
397 return false;
398 }
399 gDvm.voffJavaLangThread_run = meth->methodIndex;
400
401 /*
402 * Cache vtable offsets for ThreadGroup methods.
403 */
404 meth = dvmFindVirtualMethodByDescriptor(gDvm.classJavaLangThreadGroup,
405 "removeThread", "(Ljava/lang/Thread;)V");
406 if (meth == NULL) {
407 LOGE("Unable to find removeThread(Thread) in java.lang.ThreadGroup\n");
408 return false;
409 }
410 gDvm.voffJavaLangThreadGroup_removeThread = meth->methodIndex;
411
412 return true;
413}
414
415/*
416 * All threads should be stopped by now. Clean up some thread globals.
417 */
418void dvmThreadShutdown(void)
419{
420 if (gDvm.threadList != NULL) {
Andy McFaddenf17638e2009-08-04 16:38:40 -0700421 /*
422 * If we walk through the thread list and try to free the
423 * lingering thread structures (which should only be for daemon
424 * threads), the daemon threads may crash if they execute before
425 * the process dies. Let them leak.
426 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800427 freeThread(gDvm.threadList);
428 gDvm.threadList = NULL;
429 }
430
431 dvmFreeBitVector(gDvm.threadIdMap);
432
433 dvmFreeMonitorList();
434
435 pthread_key_delete(gDvm.pthreadKeySelf);
436}
437
438
439/*
440 * Grab the suspend count global lock.
441 */
442static inline void lockThreadSuspendCount(void)
443{
444 /*
445 * Don't try to change to VMWAIT here. When we change back to RUNNING
446 * we have to check for a pending suspend, which results in grabbing
447 * this lock recursively. Doesn't work with "fast" pthread mutexes.
448 *
449 * This lock is always held for very brief periods, so as long as
450 * mutex ordering is respected we shouldn't stall.
451 */
452 int cc = pthread_mutex_lock(&gDvm.threadSuspendCountLock);
453 assert(cc == 0);
454}
455
456/*
457 * Release the suspend count global lock.
458 */
459static inline void unlockThreadSuspendCount(void)
460{
461 dvmUnlockMutex(&gDvm.threadSuspendCountLock);
462}
463
464/*
465 * Grab the thread list global lock.
466 *
467 * This is held while "suspend all" is trying to make everybody stop. If
468 * the shutdown is in progress, and somebody tries to grab the lock, they'll
469 * have to wait for the GC to finish. Therefore it's important that the
470 * thread not be in RUNNING mode.
471 *
472 * We don't have to check to see if we should be suspended once we have
473 * the lock. Nobody can suspend all threads without holding the thread list
474 * lock while they do it, so by definition there isn't a GC in progress.
Andy McFadden44860362009-08-06 17:56:14 -0700475 *
476 * TODO: consider checking for suspend after acquiring the lock, and
477 * backing off if set. As stated above, it can't happen during normal
478 * execution, but it *can* happen during shutdown when daemon threads
479 * are being suspended.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800480 */
481void dvmLockThreadList(Thread* self)
482{
483 ThreadStatus oldStatus;
484
485 if (self == NULL) /* try to get it from TLS */
486 self = dvmThreadSelf();
487
488 if (self != NULL) {
489 oldStatus = self->status;
490 self->status = THREAD_VMWAIT;
491 } else {
Andy McFadden44860362009-08-06 17:56:14 -0700492 /* happens during VM shutdown */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800493 //LOGW("NULL self in dvmLockThreadList\n");
494 oldStatus = -1; // shut up gcc
495 }
496
497 int cc = pthread_mutex_lock(&gDvm.threadListLock);
498 assert(cc == 0);
499
500 if (self != NULL)
501 self->status = oldStatus;
502}
503
504/*
505 * Release the thread list global lock.
506 */
507void dvmUnlockThreadList(void)
508{
509 int cc = pthread_mutex_unlock(&gDvm.threadListLock);
510 assert(cc == 0);
511}
512
The Android Open Source Project99409882009-03-18 22:20:24 -0700513/*
514 * Convert SuspendCause to a string.
515 */
516static const char* getSuspendCauseStr(SuspendCause why)
517{
518 switch (why) {
519 case SUSPEND_NOT: return "NOT?";
520 case SUSPEND_FOR_GC: return "gc";
521 case SUSPEND_FOR_DEBUG: return "debug";
522 case SUSPEND_FOR_DEBUG_EVENT: return "debug-event";
523 case SUSPEND_FOR_STACK_DUMP: return "stack-dump";
Ben Chenga8e64a72009-10-20 13:01:36 -0700524#if defined(WITH_JIT)
525 case SUSPEND_FOR_TBL_RESIZE: return "table-resize";
526 case SUSPEND_FOR_IC_PATCH: return "inline-cache-patch";
Ben Cheng60c24f42010-01-04 12:29:56 -0800527 case SUSPEND_FOR_CC_RESET: return "reset-code-cache";
Bill Buzbee964a7b02010-01-28 12:54:19 -0800528 case SUSPEND_FOR_REFRESH: return "refresh jit status";
Ben Chenga8e64a72009-10-20 13:01:36 -0700529#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700530 default: return "UNKNOWN";
531 }
532}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800533
534/*
535 * Grab the "thread suspend" lock. This is required to prevent the
536 * GC and the debugger from simultaneously suspending all threads.
537 *
538 * If we fail to get the lock, somebody else is trying to suspend all
539 * threads -- including us. If we go to sleep on the lock we'll deadlock
540 * the VM. Loop until we get it or somebody puts us to sleep.
541 */
542static void lockThreadSuspend(const char* who, SuspendCause why)
543{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800544 const int kSpinSleepTime = 3*1000*1000; /* 3s */
545 u8 startWhen = 0; // init req'd to placate gcc
546 int sleepIter = 0;
547 int cc;
Jeff Hao97319a82009-08-12 16:57:15 -0700548
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800549 do {
550 cc = pthread_mutex_trylock(&gDvm._threadSuspendLock);
551 if (cc != 0) {
552 if (!dvmCheckSuspendPending(NULL)) {
553 /*
Andy McFadden2aa43612009-06-17 16:29:30 -0700554 * Could be that a resume-all is in progress, and something
555 * grabbed the CPU when the wakeup was broadcast. The thread
556 * performing the resume hasn't had a chance to release the
Andy McFaddene8059be2009-06-04 14:34:14 -0700557 * thread suspend lock. (We release before the broadcast,
558 * so this should be a narrow window.)
Andy McFadden2aa43612009-06-17 16:29:30 -0700559 *
560 * Could be we hit the window as a suspend was started,
561 * and the lock has been grabbed but the suspend counts
562 * haven't been incremented yet.
The Android Open Source Project99409882009-03-18 22:20:24 -0700563 *
564 * Could be an unusual JNI thread-attach thing.
565 *
566 * Could be the debugger telling us to resume at roughly
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800567 * the same time we're posting an event.
Ben Chenga8e64a72009-10-20 13:01:36 -0700568 *
569 * Could be two app threads both want to patch predicted
570 * chaining cells around the same time.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800571 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700572 LOGI("threadid=%d ODD: want thread-suspend lock (%s:%s),"
573 " it's held, no suspend pending\n",
574 dvmThreadSelf()->threadId, who, getSuspendCauseStr(why));
575 } else {
576 /* we suspended; reset timeout */
577 sleepIter = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800578 }
579
580 /* give the lock-holder a chance to do some work */
581 if (sleepIter == 0)
582 startWhen = dvmGetRelativeTimeUsec();
583 if (!dvmIterativeSleep(sleepIter++, kSpinSleepTime, startWhen)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700584 LOGE("threadid=%d: couldn't get thread-suspend lock (%s:%s),"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800585 " bailing\n",
The Android Open Source Project99409882009-03-18 22:20:24 -0700586 dvmThreadSelf()->threadId, who, getSuspendCauseStr(why));
Andy McFadden2aa43612009-06-17 16:29:30 -0700587 /* threads are not suspended, thread dump could crash */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800588 dvmDumpAllThreads(false);
589 dvmAbort();
590 }
591 }
592 } while (cc != 0);
593 assert(cc == 0);
594}
595
596/*
597 * Release the "thread suspend" lock.
598 */
599static inline void unlockThreadSuspend(void)
600{
601 int cc = pthread_mutex_unlock(&gDvm._threadSuspendLock);
602 assert(cc == 0);
603}
604
605
606/*
607 * Kill any daemon threads that still exist. All of ours should be
608 * stopped, so these should be Thread objects or JNI-attached threads
609 * started by the application. Actively-running threads are likely
610 * to crash the process if they continue to execute while the VM
611 * shuts down, so we really need to kill or suspend them. (If we want
612 * the VM to restart within this process, we need to kill them, but that
613 * leaves open the possibility of orphaned resources.)
614 *
615 * Waiting for the thread to suspend may be unwise at this point, but
616 * if one of these is wedged in a critical section then we probably
617 * would've locked up on the last GC attempt.
618 *
619 * It's possible for this function to get called after a failed
620 * initialization, so be careful with assumptions about the environment.
Andy McFadden44860362009-08-06 17:56:14 -0700621 *
622 * This will be called from whatever thread calls DestroyJavaVM, usually
623 * but not necessarily the main thread. It's likely, but not guaranteed,
624 * that the current thread has already been cleaned up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800625 */
626void dvmSlayDaemons(void)
627{
Andy McFadden44860362009-08-06 17:56:14 -0700628 Thread* self = dvmThreadSelf(); // may be null
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800629 Thread* target;
Andy McFadden44860362009-08-06 17:56:14 -0700630 int threadId = 0;
631 bool doWait = false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800632
633 //dvmEnterCritical(self);
634 dvmLockThreadList(self);
635
Andy McFadden44860362009-08-06 17:56:14 -0700636 if (self != NULL)
637 threadId = self->threadId;
638
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800639 target = gDvm.threadList;
640 while (target != NULL) {
641 if (target == self) {
642 target = target->next;
643 continue;
644 }
645
646 if (!dvmGetFieldBoolean(target->threadObj,
647 gDvm.offJavaLangThread_daemon))
648 {
Andy McFadden44860362009-08-06 17:56:14 -0700649 /* should never happen; suspend it with the rest */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800650 LOGW("threadid=%d: non-daemon id=%d still running at shutdown?!\n",
Andy McFadden44860362009-08-06 17:56:14 -0700651 threadId, target->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800652 }
653
Andy McFadden44860362009-08-06 17:56:14 -0700654 char* threadName = dvmGetThreadName(target);
655 LOGD("threadid=%d: suspending daemon id=%d name='%s'\n",
656 threadId, target->threadId, threadName);
657 free(threadName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800658
Andy McFadden44860362009-08-06 17:56:14 -0700659 /* mark as suspended */
660 lockThreadSuspendCount();
661 dvmAddToThreadSuspendCount(&target->suspendCount, 1);
662 unlockThreadSuspendCount();
663 doWait = true;
664
665 target = target->next;
666 }
667
668 //dvmDumpAllThreads(false);
669
670 /*
671 * Unlock the thread list, relocking it later if necessary. It's
672 * possible a thread is in VMWAIT after calling dvmLockThreadList,
673 * and that function *doesn't* check for pending suspend after
674 * acquiring the lock. We want to let them finish their business
675 * and see the pending suspend before we continue here.
676 *
677 * There's no guarantee of mutex fairness, so this might not work.
678 * (The alternative is to have dvmLockThreadList check for suspend
679 * after acquiring the lock and back off, something we should consider.)
680 */
681 dvmUnlockThreadList();
682
683 if (doWait) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800684 bool complained = false;
685
Andy McFadden44860362009-08-06 17:56:14 -0700686 usleep(200 * 1000);
687
688 dvmLockThreadList(self);
689
690 /*
691 * Sleep for a bit until the threads have suspended. We're trying
692 * to exit, so don't wait for too long.
693 */
694 int i;
695 for (i = 0; i < 10; i++) {
696 bool allSuspended = true;
697
698 target = gDvm.threadList;
699 while (target != NULL) {
700 if (target == self) {
701 target = target->next;
702 continue;
703 }
704
705 if (target->status == THREAD_RUNNING && !target->isSuspended) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800706 if (!complained)
707 LOGD("threadid=%d not ready yet\n", target->threadId);
Andy McFadden44860362009-08-06 17:56:14 -0700708 allSuspended = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800709 /* keep going so we log each running daemon once */
Andy McFadden44860362009-08-06 17:56:14 -0700710 }
711
712 target = target->next;
713 }
714
715 if (allSuspended) {
716 LOGD("threadid=%d: all daemons have suspended\n", threadId);
717 break;
718 } else {
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800719 if (!complained) {
720 complained = true;
721 LOGD("threadid=%d: waiting briefly for daemon suspension\n",
722 threadId);
Andy McFaddend2afbcf2010-03-02 14:23:04 -0800723 }
Andy McFadden44860362009-08-06 17:56:14 -0700724 }
725
726 usleep(200 * 1000);
727 }
728 dvmUnlockThreadList();
729 }
730
731#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
732 /*
733 * Abandon the threads and recover their resources.
734 */
735 target = gDvm.threadList;
736 while (target != NULL) {
737 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800738 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800739 freeThread(target);
740 target = nextTarget;
741 }
Andy McFadden44860362009-08-06 17:56:14 -0700742#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800743
Andy McFadden44860362009-08-06 17:56:14 -0700744 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800745}
746
747
748/*
749 * Finish preparing the parts of the Thread struct required to support
750 * JNI registration.
751 */
752bool dvmPrepMainForJni(JNIEnv* pEnv)
753{
754 Thread* self;
755
756 /* main thread is always first in list at this point */
757 self = gDvm.threadList;
758 assert(self->threadId == kMainThreadId);
759
760 /* create a "fake" JNI frame at the top of the main thread interp stack */
761 if (!createFakeEntryFrame(self))
762 return false;
763
764 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
765 dvmSetJniEnvThreadId(pEnv, self);
766 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
767
768 return true;
769}
770
771
772/*
773 * Finish preparing the main thread, allocating some objects to represent
774 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700775 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800776 */
777bool dvmPrepMainThread(void)
778{
779 Thread* thread;
780 Object* groupObj;
781 Object* threadObj;
782 Object* vmThreadObj;
783 StringObject* threadNameStr;
784 Method* init;
785 JValue unused;
786
787 LOGV("+++ finishing prep on main VM thread\n");
788
789 /* main thread is always first in list at this point */
790 thread = gDvm.threadList;
791 assert(thread->threadId == kMainThreadId);
792
793 /*
794 * Make sure the classes are initialized. We have to do this before
795 * we create an instance of them.
796 */
797 if (!dvmInitClass(gDvm.classJavaLangClass)) {
798 LOGE("'Class' class failed to initialize\n");
799 return false;
800 }
801 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
802 !dvmInitClass(gDvm.classJavaLangThread) ||
803 !dvmInitClass(gDvm.classJavaLangVMThread))
804 {
805 LOGE("thread classes failed to initialize\n");
806 return false;
807 }
808
809 groupObj = dvmGetMainThreadGroup();
810 if (groupObj == NULL)
811 return false;
812
813 /*
814 * Allocate and construct a Thread with the internal-creation
815 * constructor.
816 */
817 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
818 if (threadObj == NULL) {
819 LOGE("unable to allocate main thread object\n");
820 return false;
821 }
822 dvmReleaseTrackedAlloc(threadObj, NULL);
823
824 threadNameStr = dvmCreateStringFromCstr("main", ALLOC_DEFAULT);
825 if (threadNameStr == NULL)
826 return false;
827 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
828
829 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
830 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
831 assert(init != NULL);
832 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
833 THREAD_NORM_PRIORITY, false);
834 if (dvmCheckException(thread)) {
835 LOGE("exception thrown while constructing main thread object\n");
836 return false;
837 }
838
839 /*
840 * Allocate and construct a VMThread.
841 */
842 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
843 if (vmThreadObj == NULL) {
844 LOGE("unable to allocate main vmthread object\n");
845 return false;
846 }
847 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
848
849 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
850 "(Ljava/lang/Thread;)V");
851 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
852 if (dvmCheckException(thread)) {
853 LOGE("exception thrown while constructing main vmthread object\n");
854 return false;
855 }
856
857 /* set the VMThread.vmData field to our Thread struct */
858 assert(gDvm.offJavaLangVMThread_vmData != 0);
859 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
860
861 /*
862 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700863 * Threads will see that this Thread is running (at least, they would,
864 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800865 */
866 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
867 vmThreadObj);
868
869 thread->threadObj = threadObj;
870
871 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700872 * Set the context class loader. This invokes a ClassLoader method,
873 * which could conceivably call Thread.currentThread(), so we want the
874 * Thread to be fully configured before we do this.
875 */
876 Object* systemLoader = dvmGetSystemClassLoader();
877 if (systemLoader == NULL) {
878 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
879 /* keep going */
880 }
881 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
882 "contextClassLoader", "Ljava/lang/ClassLoader;");
883 if (ctxtClassLoaderOffset < 0) {
884 LOGE("Unable to find contextClassLoader field in Thread\n");
885 return false;
886 }
887 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
888
889 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800890 * Finish our thread prep.
891 */
892
893 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
894 gDvm.nonDaemonThreadCount++;
895
896 return true;
897}
898
899
900/*
901 * Alloc and initialize a Thread struct.
902 *
903 * "threadObj" is the java.lang.Thread object. It will be NULL for the
904 * main VM thread, but non-NULL for everything else.
905 *
906 * Does not create any objects, just stuff on the system (malloc) heap. (If
907 * this changes, we need to use ALLOC_NO_GC. And also verify that we're
908 * ready to load classes at the time this is called.)
909 */
910static Thread* allocThread(int interpStackSize)
911{
912 Thread* thread;
913 u1* stackBottom;
914
915 thread = (Thread*) calloc(1, sizeof(Thread));
916 if (thread == NULL)
917 return NULL;
918
Jeff Hao97319a82009-08-12 16:57:15 -0700919#if defined(WITH_SELF_VERIFICATION)
920 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
921 return NULL;
922#endif
923
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800924 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
925
926 thread->status = THREAD_INITIALIZING;
927 thread->suspendCount = 0;
928
929#ifdef WITH_ALLOC_LIMITS
930 thread->allocLimit = -1;
931#endif
932
933 /*
934 * Allocate and initialize the interpreted code stack. We essentially
935 * "lose" the alloc pointer, which points at the bottom of the stack,
936 * but we can get it back later because we know how big the stack is.
937 *
938 * The stack must be aligned on a 4-byte boundary.
939 */
940#ifdef MALLOC_INTERP_STACK
941 stackBottom = (u1*) malloc(interpStackSize);
942 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700943#if defined(WITH_SELF_VERIFICATION)
944 dvmSelfVerificationShadowSpaceFree(thread);
945#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800946 free(thread);
947 return NULL;
948 }
949 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
950#else
951 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
952 MAP_PRIVATE | MAP_ANON, -1, 0);
953 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700954#if defined(WITH_SELF_VERIFICATION)
955 dvmSelfVerificationShadowSpaceFree(thread);
956#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800957 free(thread);
958 return NULL;
959 }
960#endif
961
962 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
963 thread->interpStackSize = interpStackSize;
964 thread->interpStackStart = stackBottom + interpStackSize;
965 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
966
967 /* give the thread code a chance to set things up */
968 dvmInitInterpStack(thread, interpStackSize);
969
970 return thread;
971}
972
973/*
974 * Get a meaningful thread ID. At present this only has meaning under Linux,
975 * where getpid() and gettid() sometimes agree and sometimes don't depending
976 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
977 */
978pid_t dvmGetSysThreadId(void)
979{
980#ifdef HAVE_GETTID
981 return gettid();
982#else
983 return getpid();
984#endif
985}
986
987/*
988 * Finish initialization of a Thread struct.
989 *
990 * This must be called while executing in the new thread, but before the
991 * thread is added to the thread list.
992 *
993 * *** NOTE: The threadListLock must be held by the caller (needed for
994 * assignThreadId()).
995 */
996static bool prepareThread(Thread* thread)
997{
998 assignThreadId(thread);
999 thread->handle = pthread_self();
1000 thread->systemTid = dvmGetSysThreadId();
1001
1002 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1003 // (int) getpid());
1004 setThreadSelf(thread);
1005
1006 LOGV("threadid=%d: interp stack at %p\n",
1007 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1008
1009 /*
1010 * Initialize invokeReq.
1011 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001012 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001013 pthread_cond_init(&thread->invokeReq.cv, NULL);
1014
1015 /*
1016 * Initialize our reference tracking tables.
1017 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001018 * Most threads won't use jniMonitorRefTable, so we clear out the
1019 * structure but don't call the init function (which allocs storage).
1020 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001021#ifdef USE_INDIRECT_REF
1022 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1023 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1024 return false;
1025#else
1026 /*
1027 * The JNI local ref table *must* be fixed-size because we keep pointers
1028 * into the table in our stack frames.
1029 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001030 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1031 kJniLocalRefMax, kJniLocalRefMax))
1032 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001033#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001034 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1035 kInternalRefDefault, kInternalRefMax))
1036 return false;
1037
1038 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1039
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001040 pthread_cond_init(&thread->waitCond, NULL);
1041 dvmInitMutex(&thread->waitMutex);
1042
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001043 return true;
1044}
1045
1046/*
1047 * Remove a thread from the internal list.
1048 * Clear out the links to make it obvious that the thread is
1049 * no longer on the list. Caller must hold gDvm.threadListLock.
1050 */
1051static void unlinkThread(Thread* thread)
1052{
1053 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1054 if (thread == gDvm.threadList) {
1055 assert(thread->prev == NULL);
1056 gDvm.threadList = thread->next;
1057 } else {
1058 assert(thread->prev != NULL);
1059 thread->prev->next = thread->next;
1060 }
1061 if (thread->next != NULL)
1062 thread->next->prev = thread->prev;
1063 thread->prev = thread->next = NULL;
1064}
1065
1066/*
1067 * Free a Thread struct, and all the stuff allocated within.
1068 */
1069static void freeThread(Thread* thread)
1070{
1071 if (thread == NULL)
1072 return;
1073
1074 /* thread->threadId is zero at this point */
1075 LOGVV("threadid=%d: freeing\n", thread->threadId);
1076
1077 if (thread->interpStackStart != NULL) {
1078 u1* interpStackBottom;
1079
1080 interpStackBottom = thread->interpStackStart;
1081 interpStackBottom -= thread->interpStackSize;
1082#ifdef MALLOC_INTERP_STACK
1083 free(interpStackBottom);
1084#else
1085 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1086 LOGW("munmap(thread stack) failed\n");
1087#endif
1088 }
1089
Andy McFaddend5ab7262009-08-25 07:19:34 -07001090#ifdef USE_INDIRECT_REF
1091 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1092#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001093 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001094#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001095 dvmClearReferenceTable(&thread->internalLocalRefTable);
1096 if (&thread->jniMonitorRefTable.table != NULL)
1097 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1098
Jeff Hao97319a82009-08-12 16:57:15 -07001099#if defined(WITH_SELF_VERIFICATION)
1100 dvmSelfVerificationShadowSpaceFree(thread);
1101#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001102 free(thread);
1103}
1104
1105/*
1106 * Like pthread_self(), but on a Thread*.
1107 */
1108Thread* dvmThreadSelf(void)
1109{
1110 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1111}
1112
1113/*
1114 * Explore our sense of self. Stuffs the thread pointer into TLS.
1115 */
1116static void setThreadSelf(Thread* thread)
1117{
1118 int cc;
1119
1120 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1121 if (cc != 0) {
1122 /*
1123 * Sometimes this fails under Bionic with EINVAL during shutdown.
1124 * This can happen if the timing is just right, e.g. a thread
1125 * fails to attach during shutdown, but the "fail" path calls
1126 * here to ensure we clean up after ourselves.
1127 */
1128 if (thread != NULL) {
1129 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1130 dvmAbort(); /* the world is fundamentally hosed */
1131 }
1132 }
1133}
1134
1135/*
1136 * This is associated with the pthreadKeySelf key. It's called by the
1137 * pthread library when a thread is exiting and the "self" pointer in TLS
1138 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001139 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001140 *
1141 * This is mainly of use to ensure that we don't leak resources if, for
1142 * example, a thread attaches itself to us with AttachCurrentThread and
1143 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001144 *
1145 * We could do the detach here instead of aborting, but this will lead to
1146 * portability problems. Other implementations do not do this check and
1147 * will simply be unaware that the thread has exited, leading to resource
1148 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1149 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001150 *
1151 * Because some implementations may want to use the pthread destructor
1152 * to initiate the detach, and the ordering of destructors is not defined,
1153 * 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 -08001154 */
1155static void threadExitCheck(void* arg)
1156{
Andy McFadden909ce242009-12-10 16:38:30 -08001157 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001158
Andy McFadden909ce242009-12-10 16:38:30 -08001159 Thread* self = (Thread*) arg;
1160 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001161
Andy McFadden909ce242009-12-10 16:38:30 -08001162 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1163 self->threadId, arg, self->threadExitCheckCount);
1164
1165 if (self->status == THREAD_ZOMBIE) {
1166 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1167 self->threadId);
1168 return;
1169 }
1170
1171 if (self->threadExitCheckCount < kMaxCount) {
1172 /*
1173 * Spin a couple of times to let other destructors fire.
1174 */
1175 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1176 self->threadId, self->threadExitCheckCount);
1177 self->threadExitCheckCount++;
1178 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1179 if (cc != 0) {
1180 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1181 self->threadId);
1182 dvmAbort();
1183 }
1184 } else {
1185 LOGE("threadid=%d: native thread exited without detaching\n",
1186 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001187 dvmAbort();
1188 }
1189}
1190
1191
1192/*
1193 * Assign the threadId. This needs to be a small integer so that our
1194 * "thin" locks fit in a small number of bits.
1195 *
1196 * We reserve zero for use as an invalid ID.
1197 *
1198 * This must be called with threadListLock held (unless we're still
1199 * initializing the system).
1200 */
1201static void assignThreadId(Thread* thread)
1202{
Carl Shapiro59a93122010-01-26 17:12:51 -08001203 /*
1204 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001205 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1206 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001207 */
1208 int num = dvmAllocBit(gDvm.threadIdMap);
1209 if (num < 0) {
1210 LOGE("Ran out of thread IDs\n");
1211 dvmAbort(); // TODO: make this a non-fatal error result
1212 }
1213
Carl Shapiro59a93122010-01-26 17:12:51 -08001214 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001215
1216 assert(thread->threadId != 0);
1217 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1218}
1219
1220/*
1221 * Give back the thread ID.
1222 */
1223static void releaseThreadId(Thread* thread)
1224{
1225 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001226 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001227 thread->threadId = 0;
1228}
1229
1230
1231/*
1232 * Add a stack frame that makes it look like the native code in the main
1233 * thread was originally invoked from interpreted code. This gives us a
1234 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1235 * VM begins by executing "main" in a class, so in a way this brings us
1236 * closer to the spec.
1237 */
1238static bool createFakeEntryFrame(Thread* thread)
1239{
1240 assert(thread->threadId == kMainThreadId); // main thread only
1241
1242 /* find the method on first use */
1243 if (gDvm.methFakeNativeEntry == NULL) {
1244 ClassObject* nativeStart;
1245 Method* mainMeth;
1246
1247 nativeStart = dvmFindSystemClassNoInit(
1248 "Ldalvik/system/NativeStart;");
1249 if (nativeStart == NULL) {
1250 LOGE("Unable to find dalvik.system.NativeStart class\n");
1251 return false;
1252 }
1253
1254 /*
1255 * Because we are creating a frame that represents application code, we
1256 * want to stuff the application class loader into the method's class
1257 * loader field, even though we're using the system class loader to
1258 * load it. This makes life easier over in JNI FindClass (though it
1259 * could bite us in other ways).
1260 *
1261 * Unfortunately this is occurring too early in the initialization,
1262 * of necessity coming before JNI is initialized, and we're not quite
1263 * ready to set up the application class loader.
1264 *
1265 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1266 * and check it in FindClass. The method is private so nobody else
1267 * can call it.
1268 */
1269 //nativeStart->classLoader = dvmGetSystemClassLoader();
1270
1271 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1272 "main", "([Ljava/lang/String;)V");
1273 if (mainMeth == NULL) {
1274 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1275 return false;
1276 }
1277
1278 gDvm.methFakeNativeEntry = mainMeth;
1279 }
1280
1281 return dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry);
1282}
1283
1284
1285/*
1286 * Add a stack frame that makes it look like the native thread has been
1287 * executing interpreted code. This gives us a place to hang JNI local
1288 * references.
1289 */
1290static bool createFakeRunFrame(Thread* thread)
1291{
1292 ClassObject* nativeStart;
1293 Method* runMeth;
1294
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001295 nativeStart =
1296 dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
1297 if (nativeStart == NULL) {
1298 LOGE("Unable to find dalvik.system.NativeStart class\n");
1299 return false;
1300 }
1301
1302 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1303 if (runMeth == NULL) {
1304 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1305 return false;
1306 }
1307
1308 return dvmPushJNIFrame(thread, runMeth);
1309}
1310
1311/*
1312 * Helper function to set the name of the current thread
1313 */
1314static void setThreadName(const char *threadName)
1315{
1316#if defined(HAVE_PRCTL)
1317 int hasAt = 0;
1318 int hasDot = 0;
1319 const char *s = threadName;
1320 while (*s) {
1321 if (*s == '.') hasDot = 1;
1322 else if (*s == '@') hasAt = 1;
1323 s++;
1324 }
1325 int len = s - threadName;
1326 if (len < 15 || hasAt || !hasDot) {
1327 s = threadName;
1328 } else {
1329 s = threadName + len - 15;
1330 }
1331 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
1332#endif
1333}
1334
1335/*
1336 * Create a thread as a result of java.lang.Thread.start().
1337 *
1338 * We do have to worry about some concurrency problems, e.g. programs
1339 * that try to call Thread.start() on the same object from multiple threads.
1340 * (This will fail for all but one, but we have to make sure that it succeeds
1341 * for exactly one.)
1342 *
1343 * Some of the complexity here arises from our desire to mimic the
1344 * Thread vs. VMThread class decomposition we inherited. We've been given
1345 * a Thread, and now we need to create a VMThread and then populate both
1346 * objects. We also need to create one of our internal Thread objects.
1347 *
1348 * Pass in a stack size of 0 to get the default.
1349 */
1350bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1351{
1352 pthread_attr_t threadAttr;
1353 pthread_t threadHandle;
1354 Thread* self;
1355 Thread* newThread = NULL;
1356 Object* vmThreadObj = NULL;
1357 int stackSize;
1358
1359 assert(threadObj != NULL);
1360
1361 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001362 // Allow the sampling profiler thread. We shut it down before forking.
1363 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1364 gDvm.offJavaLangThread_name);
1365 char* threadName = dvmCreateCstrFromString(nameStr);
1366 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1367 free(threadName);
1368 if (!profilerThread) {
1369 dvmThrowException("Ljava/lang/IllegalStateException;",
1370 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001371
Bob Lee9dc72a32009-09-04 18:28:16 -07001372 goto fail;
1373 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001374 }
1375
1376 self = dvmThreadSelf();
1377 if (reqStackSize == 0)
1378 stackSize = gDvm.stackSize;
1379 else if (reqStackSize < kMinStackSize)
1380 stackSize = kMinStackSize;
1381 else if (reqStackSize > kMaxStackSize)
1382 stackSize = kMaxStackSize;
1383 else
1384 stackSize = reqStackSize;
1385
1386 pthread_attr_init(&threadAttr);
1387 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1388
1389 /*
1390 * To minimize the time spent in the critical section, we allocate the
1391 * vmThread object here.
1392 */
1393 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1394 if (vmThreadObj == NULL)
1395 goto fail;
1396
1397 newThread = allocThread(stackSize);
1398 if (newThread == NULL)
1399 goto fail;
1400 newThread->threadObj = threadObj;
1401
1402 assert(newThread->status == THREAD_INITIALIZING);
1403
1404 /*
1405 * We need to lock out other threads while we test and set the
1406 * "vmThread" field in java.lang.Thread, because we use that to determine
1407 * if this thread has been started before. We use the thread list lock
1408 * because it's handy and we're going to need to grab it again soon
1409 * anyway.
1410 */
1411 dvmLockThreadList(self);
1412
1413 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1414 dvmUnlockThreadList();
1415 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1416 "thread has already been started");
1417 goto fail;
1418 }
1419
1420 /*
1421 * There are actually three data structures: Thread (object), VMThread
1422 * (object), and Thread (C struct). All of them point to at least one
1423 * other.
1424 *
1425 * As soon as "VMThread.vmData" is assigned, other threads can start
1426 * making calls into us (e.g. setPriority).
1427 */
1428 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1429 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1430
1431 /*
1432 * Thread creation might take a while, so release the lock.
1433 */
1434 dvmUnlockThreadList();
1435
Andy McFadden2aa43612009-06-17 16:29:30 -07001436 int cc, oldStatus;
1437 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1438 cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1439 newThread);
1440 oldStatus = dvmChangeStatus(self, oldStatus);
1441
1442 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001443 /*
1444 * Failure generally indicates that we have exceeded system
1445 * resource limits. VirtualMachineError is probably too severe,
1446 * so use OutOfMemoryError.
1447 */
1448 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1449
1450 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1451
1452 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1453 "thread creation failed");
1454 goto fail;
1455 }
1456
1457 /*
1458 * We need to wait for the thread to start. Otherwise, depending on
1459 * the whims of the OS scheduler, we could return and the code in our
1460 * thread could try to do operations on the new thread before it had
1461 * finished starting.
1462 *
1463 * The new thread will lock the thread list, change its state to
1464 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1465 * on gDvm.threadStartCond (which uses the thread list lock). This
1466 * thread (the parent) will either see that the thread is already ready
1467 * after we grab the thread list lock, or will be awakened from the
1468 * condition variable on the broadcast.
1469 *
1470 * We don't want to stall the rest of the VM while the new thread
1471 * starts, which can happen if the GC wakes up at the wrong moment.
1472 * So, we change our own status to VMWAIT, and self-suspend if
1473 * necessary after we finish adding the new thread.
1474 *
1475 *
1476 * We have to deal with an odd race with the GC/debugger suspension
1477 * mechanism when creating a new thread. The information about whether
1478 * or not a thread should be suspended is contained entirely within
1479 * the Thread struct; this is usually cleaner to deal with than having
1480 * one or more globally-visible suspension flags. The trouble is that
1481 * we could create the thread while the VM is trying to suspend all
1482 * threads. The suspend-count won't be nonzero for the new thread,
1483 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1484 *
1485 * The easiest way to deal with this is to prevent the new thread from
1486 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001487 * following (correct) sequence of events for a "badly timed" GC
1488 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001489 *
1490 * - call pthread_create()
1491 * - lock thread list
1492 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1493 * - sleep on condition var (mutex = thread list lock) until child starts
1494 * + GC triggered by another thread
1495 * + thread list locked; suspend counts updated; thread list unlocked
1496 * + loop waiting for all runnable threads to suspend
1497 * + success, start GC
1498 * o child thread wakes, signals condition var to wake parent
1499 * o child waits for parent ack on condition variable
1500 * - we wake up, locking thread list
1501 * - add child to thread list
1502 * - unlock thread list
1503 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1504 * + GC finishes; all threads in thread list are resumed
1505 * - lock thread list
1506 * - set child to THREAD_VMWAIT, and signal it to start
1507 * - unlock thread list
1508 * o child resumes
1509 * o child changes state to THREAD_RUNNING
1510 *
1511 * The above shows the GC starting up during thread creation, but if
1512 * it starts anywhere after VMThread.create() is called it will
1513 * produce the same series of events.
1514 *
1515 * Once the child is in the thread list, it will be suspended and
1516 * resumed like any other thread. In the above scenario the resume-all
1517 * code will try to resume the new thread, which was never actually
1518 * suspended, and try to decrement the child's thread suspend count to -1.
1519 * We can catch this in the resume-all code.
1520 *
1521 * Bouncing back and forth between threads like this adds a small amount
1522 * of scheduler overhead to thread startup.
1523 *
1524 * One alternative to having the child wait for the parent would be
1525 * to have the child inherit the parents' suspension count. This
1526 * would work for a GC, since we can safely assume that the parent
1527 * thread didn't cause it, but we must only do so if the parent suspension
1528 * was caused by a suspend-all. If the parent was being asked to
1529 * suspend singly by the debugger, the child should not inherit the value.
1530 *
1531 * We could also have a global "new thread suspend count" that gets
1532 * picked up by new threads before changing state to THREAD_RUNNING.
1533 * This would be protected by the thread list lock and set by a
1534 * suspend-all.
1535 */
1536 dvmLockThreadList(self);
1537 assert(self->status == THREAD_RUNNING);
1538 self->status = THREAD_VMWAIT;
1539 while (newThread->status != THREAD_STARTING)
1540 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1541
1542 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1543 newThread->next = gDvm.threadList->next;
1544 if (newThread->next != NULL)
1545 newThread->next->prev = newThread;
1546 newThread->prev = gDvm.threadList;
1547 gDvm.threadList->next = newThread;
1548
1549 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1550 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1551
1552 dvmUnlockThreadList();
1553
1554 /* change status back to RUNNING, self-suspending if necessary */
1555 dvmChangeStatus(self, THREAD_RUNNING);
1556
1557 /*
1558 * Tell the new thread to start.
1559 *
1560 * We must hold the thread list lock before messing with another thread.
1561 * In the general case we would also need to verify that newThread was
1562 * still in the thread list, but in our case the thread has not started
1563 * executing user code and therefore has not had a chance to exit.
1564 *
1565 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1566 * comes with a suspend-pending check.
1567 */
1568 dvmLockThreadList(self);
1569
1570 assert(newThread->status == THREAD_STARTING);
1571 newThread->status = THREAD_VMWAIT;
1572 pthread_cond_broadcast(&gDvm.threadStartCond);
1573
1574 dvmUnlockThreadList();
1575
1576 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1577 return true;
1578
1579fail:
1580 freeThread(newThread);
1581 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1582 return false;
1583}
1584
1585/*
1586 * pthread entry function for threads started from interpreted code.
1587 */
1588static void* interpThreadStart(void* arg)
1589{
1590 Thread* self = (Thread*) arg;
1591
1592 char *threadName = dvmGetThreadName(self);
1593 setThreadName(threadName);
1594 free(threadName);
1595
1596 /*
1597 * Finish initializing the Thread struct.
1598 */
1599 prepareThread(self);
1600
1601 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1602
1603 /*
1604 * Change our status and wake our parent, who will add us to the
1605 * thread list and advance our state to VMWAIT.
1606 */
1607 dvmLockThreadList(self);
1608 self->status = THREAD_STARTING;
1609 pthread_cond_broadcast(&gDvm.threadStartCond);
1610
1611 /*
1612 * Wait until the parent says we can go. Assuming there wasn't a
1613 * suspend pending, this will happen immediately. When it completes,
1614 * we're full-fledged citizens of the VM.
1615 *
1616 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1617 * because the pthread_cond_wait below needs to reacquire a lock that
1618 * suspend-all is also interested in. If we get unlucky, the parent could
1619 * change us to THREAD_RUNNING, then a GC could start before we get
1620 * signaled, and suspend-all will grab the thread list lock and then
1621 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1622 * trying to get the lock.
1623 */
1624 while (self->status != THREAD_VMWAIT)
1625 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1626
1627 dvmUnlockThreadList();
1628
1629 /*
1630 * Add a JNI context.
1631 */
1632 self->jniEnv = dvmCreateJNIEnv(self);
1633
1634 /*
1635 * Change our state so the GC will wait for us from now on. If a GC is
1636 * in progress this call will suspend us.
1637 */
1638 dvmChangeStatus(self, THREAD_RUNNING);
1639
1640 /*
1641 * Notify the debugger & DDM. The debugger notification may cause
1642 * us to suspend ourselves (and others).
1643 */
1644 if (gDvm.debuggerConnected)
1645 dvmDbgPostThreadStart(self);
1646
1647 /*
1648 * Set the system thread priority according to the Thread object's
1649 * priority level. We don't usually need to do this, because both the
1650 * Thread object and system thread priorities inherit from parents. The
1651 * tricky case is when somebody creates a Thread object, calls
1652 * setPriority(), and then starts the thread. We could manage this with
1653 * a "needs priority update" flag to avoid the redundant call.
1654 */
Andy McFadden4879df92009-08-07 14:49:40 -07001655 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001656 gDvm.offJavaLangThread_priority);
1657 dvmChangeThreadPriority(self, priority);
1658
1659 /*
1660 * Execute the "run" method.
1661 *
1662 * At this point our stack is empty, so somebody who comes looking for
1663 * stack traces right now won't have much to look at. This is normal.
1664 */
1665 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1666 JValue unused;
1667
1668 LOGV("threadid=%d: calling run()\n", self->threadId);
1669 assert(strcmp(run->name, "run") == 0);
1670 dvmCallMethod(self, run, self->threadObj, &unused);
1671 LOGV("threadid=%d: exiting\n", self->threadId);
1672
1673 /*
1674 * Remove the thread from various lists, report its death, and free
1675 * its resources.
1676 */
1677 dvmDetachCurrentThread();
1678
1679 return NULL;
1680}
1681
1682/*
1683 * The current thread is exiting with an uncaught exception. The
1684 * Java programming language allows the application to provide a
1685 * thread-exit-uncaught-exception handler for the VM, for a specific
1686 * Thread, and for all threads in a ThreadGroup.
1687 *
1688 * Version 1.5 added the per-thread handler. We need to call
1689 * "uncaughtException" in the handler object, which is either the
1690 * ThreadGroup object or the Thread-specific handler.
1691 */
1692static void threadExitUncaughtException(Thread* self, Object* group)
1693{
1694 Object* exception;
1695 Object* handlerObj;
1696 ClassObject* throwable;
1697 Method* uncaughtHandler = NULL;
1698 InstField* threadHandler;
1699
1700 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1701 self->threadId, group);
1702 assert(group != NULL);
1703
1704 /*
1705 * Get a pointer to the exception, then clear out the one in the
1706 * thread. We don't want to have it set when executing interpreted code.
1707 */
1708 exception = dvmGetException(self);
1709 dvmAddTrackedAlloc(exception, self);
1710 dvmClearException(self);
1711
1712 /*
1713 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1714 * else use "group" (which is an instance of UncaughtExceptionHandler).
1715 */
1716 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1717 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1718 if (threadHandler == NULL) {
1719 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1720 goto bail;
1721 }
1722 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1723 if (handlerObj == NULL)
1724 handlerObj = group;
1725
1726 /*
1727 * Find the "uncaughtHandler" field in this object.
1728 */
1729 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1730 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1731
1732 if (uncaughtHandler != NULL) {
1733 //LOGI("+++ calling %s.uncaughtException\n",
1734 // handlerObj->clazz->descriptor);
1735 JValue unused;
1736 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1737 self->threadObj, exception);
1738 } else {
1739 /* restore it and dump a stack trace */
1740 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1741 handlerObj->clazz->descriptor);
1742 dvmSetException(self, exception);
1743 dvmLogExceptionStackTrace();
1744 }
1745
1746bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001747#if defined(WITH_JIT)
1748 /* Remove this thread's suspendCount from global suspendCount sum */
1749 lockThreadSuspendCount();
1750 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1751 unlockThreadSuspendCount();
1752#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001753 dvmReleaseTrackedAlloc(exception, self);
1754}
1755
1756
1757/*
1758 * Create an internal VM thread, for things like JDWP and finalizers.
1759 *
1760 * The easiest way to do this is create a new thread and then use the
1761 * JNI AttachCurrentThread implementation.
1762 *
1763 * This does not return until after the new thread has begun executing.
1764 */
1765bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1766 InternalThreadStart func, void* funcArg)
1767{
1768 InternalStartArgs* pArgs;
1769 Object* systemGroup;
1770 pthread_attr_t threadAttr;
1771 volatile Thread* newThread = NULL;
1772 volatile int createStatus = 0;
1773
1774 systemGroup = dvmGetSystemThreadGroup();
1775 if (systemGroup == NULL)
1776 return false;
1777
1778 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1779 pArgs->func = func;
1780 pArgs->funcArg = funcArg;
1781 pArgs->name = strdup(name); // storage will be owned by new thread
1782 pArgs->group = systemGroup;
1783 pArgs->isDaemon = true;
1784 pArgs->pThread = &newThread;
1785 pArgs->pCreateStatus = &createStatus;
1786
1787 pthread_attr_init(&threadAttr);
1788 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1789
1790 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1791 pArgs) != 0)
1792 {
1793 LOGE("internal thread creation failed\n");
1794 free(pArgs->name);
1795 free(pArgs);
1796 return false;
1797 }
1798
1799 /*
1800 * Wait for the child to start. This gives us an opportunity to make
1801 * sure that the thread started correctly, and allows our caller to
1802 * assume that the thread has started running.
1803 *
1804 * Because we aren't holding a lock across the thread creation, it's
1805 * possible that the child will already have completed its
1806 * initialization. Because the child only adjusts "createStatus" while
1807 * holding the thread list lock, the initial condition on the "while"
1808 * loop will correctly avoid the wait if this occurs.
1809 *
1810 * It's also possible that we'll have to wait for the thread to finish
1811 * being created, and as part of allocating a Thread object it might
1812 * need to initiate a GC. We switch to VMWAIT while we pause.
1813 */
1814 Thread* self = dvmThreadSelf();
1815 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1816 dvmLockThreadList(self);
1817 while (createStatus == 0)
1818 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1819
1820 if (newThread == NULL) {
1821 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1822 assert(createStatus < 0);
1823 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1824 dvmUnlockThreadList();
1825 dvmChangeStatus(self, oldStatus);
1826 return false;
1827 }
1828
1829 /* thread could be in any state now (except early init states) */
1830 //assert(newThread->status == THREAD_RUNNING);
1831
1832 dvmUnlockThreadList();
1833 dvmChangeStatus(self, oldStatus);
1834
1835 return true;
1836}
1837
1838/*
1839 * pthread entry function for internally-created threads.
1840 *
1841 * We are expected to free "arg" and its contents. If we're a daemon
1842 * thread, and we get cancelled abruptly when the VM shuts down, the
1843 * storage won't be freed. If this becomes a concern we can make a copy
1844 * on the stack.
1845 */
1846static void* internalThreadStart(void* arg)
1847{
1848 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1849 JavaVMAttachArgs jniArgs;
1850
1851 jniArgs.version = JNI_VERSION_1_2;
1852 jniArgs.name = pArgs->name;
1853 jniArgs.group = pArgs->group;
1854
1855 setThreadName(pArgs->name);
1856
1857 /* use local jniArgs as stack top */
1858 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1859 /*
1860 * Tell the parent of our success.
1861 *
1862 * threadListLock is the mutex for threadStartCond.
1863 */
1864 dvmLockThreadList(dvmThreadSelf());
1865 *pArgs->pCreateStatus = 1;
1866 *pArgs->pThread = dvmThreadSelf();
1867 pthread_cond_broadcast(&gDvm.threadStartCond);
1868 dvmUnlockThreadList();
1869
1870 LOG_THREAD("threadid=%d: internal '%s'\n",
1871 dvmThreadSelf()->threadId, pArgs->name);
1872
1873 /* execute */
1874 (*pArgs->func)(pArgs->funcArg);
1875
1876 /* detach ourselves */
1877 dvmDetachCurrentThread();
1878 } else {
1879 /*
1880 * Tell the parent of our failure. We don't have a Thread struct,
1881 * so we can't be suspended, so we don't need to enter a critical
1882 * section.
1883 */
1884 dvmLockThreadList(dvmThreadSelf());
1885 *pArgs->pCreateStatus = -1;
1886 assert(*pArgs->pThread == NULL);
1887 pthread_cond_broadcast(&gDvm.threadStartCond);
1888 dvmUnlockThreadList();
1889
1890 assert(*pArgs->pThread == NULL);
1891 }
1892
1893 free(pArgs->name);
1894 free(pArgs);
1895 return NULL;
1896}
1897
1898/*
1899 * Attach the current thread to the VM.
1900 *
1901 * Used for internally-created threads and JNI's AttachCurrentThread.
1902 */
1903bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1904{
1905 Thread* self = NULL;
1906 Object* threadObj = NULL;
1907 Object* vmThreadObj = NULL;
1908 StringObject* threadNameStr = NULL;
1909 Method* init;
1910 bool ok, ret;
1911
1912 /* establish a basic sense of self */
1913 self = allocThread(gDvm.stackSize);
1914 if (self == NULL)
1915 goto fail;
1916 setThreadSelf(self);
1917
1918 /*
1919 * Create Thread and VMThread objects. We have to use ALLOC_NO_GC
1920 * because this thread is not yet visible to the VM. We could also
1921 * just grab the GC lock earlier, but that leaves us executing
1922 * interpreted code with the lock held, which is not prudent.
1923 *
1924 * The alloc calls will block if a GC is in progress, so we don't need
1925 * to check for global suspension here.
1926 *
1927 * It's also possible for the allocation calls to *cause* a GC.
1928 */
1929 //BUG: deadlock if a GC happens here during HeapWorker creation
1930 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_NO_GC);
1931 if (threadObj == NULL)
1932 goto fail;
1933 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_NO_GC);
1934 if (vmThreadObj == NULL)
1935 goto fail;
1936
1937 self->threadObj = threadObj;
1938 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1939
1940 /*
1941 * Do some java.lang.Thread constructor prep before we lock stuff down.
1942 */
1943 if (pArgs->name != NULL) {
1944 threadNameStr = dvmCreateStringFromCstr(pArgs->name, ALLOC_NO_GC);
1945 if (threadNameStr == NULL) {
1946 assert(dvmCheckException(dvmThreadSelf()));
1947 goto fail;
1948 }
1949 }
1950
1951 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1952 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1953 if (init == NULL) {
1954 assert(dvmCheckException(dvmThreadSelf()));
1955 goto fail;
1956 }
1957
1958 /*
1959 * Finish our thread prep. We need to do this before invoking any
1960 * interpreted code. prepareThread() requires that we hold the thread
1961 * list lock.
1962 */
1963 dvmLockThreadList(self);
1964 ok = prepareThread(self);
1965 dvmUnlockThreadList();
1966 if (!ok)
1967 goto fail;
1968
1969 self->jniEnv = dvmCreateJNIEnv(self);
1970 if (self->jniEnv == NULL)
1971 goto fail;
1972
1973 /*
1974 * Create a "fake" JNI frame at the top of the main thread interp stack.
1975 * It isn't really necessary for the internal threads, but it gives
1976 * the debugger something to show. It is essential for the JNI-attached
1977 * threads.
1978 */
1979 if (!createFakeRunFrame(self))
1980 goto fail;
1981
1982 /*
1983 * The native side of the thread is ready; add it to the list.
1984 */
1985 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1986
1987 /* Start off in VMWAIT, because we may be about to block
1988 * on the heap lock, and we don't want any suspensions
1989 * to wait for us.
1990 */
1991 self->status = THREAD_VMWAIT;
1992
1993 /*
1994 * Add ourselves to the thread list. Once we finish here we are
1995 * visible to the debugger and the GC.
1996 */
1997 dvmLockThreadList(self);
1998
1999 self->next = gDvm.threadList->next;
2000 if (self->next != NULL)
2001 self->next->prev = self;
2002 self->prev = gDvm.threadList;
2003 gDvm.threadList->next = self;
2004 if (!isDaemon)
2005 gDvm.nonDaemonThreadCount++;
2006
2007 dvmUnlockThreadList();
2008
2009 /*
2010 * It's possible that a GC is currently running. Our thread
2011 * wasn't in the list when the GC started, so it's not properly
2012 * suspended in that case. Synchronize on the heap lock (held
2013 * when a GC is happening) to guarantee that any GCs from here
2014 * on will see this thread in the list.
2015 */
2016 dvmLockMutex(&gDvm.gcHeapLock);
2017 dvmUnlockMutex(&gDvm.gcHeapLock);
2018
2019 /*
2020 * Switch to the running state now that we're ready for
2021 * suspensions. This call may suspend.
2022 */
2023 dvmChangeStatus(self, THREAD_RUNNING);
2024
2025 /*
2026 * Now we're ready to run some interpreted code.
2027 *
2028 * We need to construct the Thread object and set the VMThread field.
2029 * Setting VMThread tells interpreted code that we're alive.
2030 *
2031 * Call the (group, name, priority, daemon) constructor on the Thread.
2032 * This sets the thread's name and adds it to the specified group, and
2033 * provides values for priority and daemon (which are normally inherited
2034 * from the current thread).
2035 */
2036 JValue unused;
2037 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2038 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2039 if (dvmCheckException(self)) {
2040 LOGE("exception thrown while constructing attached thread object\n");
2041 goto fail_unlink;
2042 }
2043 //if (isDaemon)
2044 // dvmSetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon, true);
2045
2046 /*
2047 * Set the VMThread field, which tells interpreted code that we're alive.
2048 *
2049 * The risk of a thread start collision here is very low; somebody
2050 * would have to be deliberately polling the ThreadGroup list and
2051 * trying to start threads against anything it sees, which would
2052 * generally cause problems for all thread creation. However, for
2053 * correctness we test "vmThread" before setting it.
2054 */
2055 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
2056 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2057 "thread has already been started");
2058 /* We don't want to free anything associated with the thread
2059 * because someone is obviously interested in it. Just let
2060 * it go and hope it will clean itself up when its finished.
2061 * This case should never happen anyway.
2062 *
2063 * Since we're letting it live, we need to finish setting it up.
2064 * We just have to let the caller know that the intended operation
2065 * has failed.
2066 *
2067 * [ This seems strange -- stepping on the vmThread object that's
2068 * already present seems like a bad idea. TODO: figure this out. ]
2069 */
2070 ret = false;
2071 } else
2072 ret = true;
2073 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2074
2075 /* These are now reachable from the thread groups. */
2076 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
2077 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
2078
2079 /*
2080 * The thread is ready to go; let the debugger see it.
2081 */
2082 self->threadObj = threadObj;
2083
2084 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2085 self->threadId, pArgs->name);
2086
2087 /* tell the debugger & DDM */
2088 if (gDvm.debuggerConnected)
2089 dvmDbgPostThreadStart(self);
2090
2091 return ret;
2092
2093fail_unlink:
2094 dvmLockThreadList(self);
2095 unlinkThread(self);
2096 if (!isDaemon)
2097 gDvm.nonDaemonThreadCount--;
2098 dvmUnlockThreadList();
2099 /* fall through to "fail" */
2100fail:
2101 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
2102 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
2103 if (self != NULL) {
2104 if (self->jniEnv != NULL) {
2105 dvmDestroyJNIEnv(self->jniEnv);
2106 self->jniEnv = NULL;
2107 }
2108 freeThread(self);
2109 }
2110 setThreadSelf(NULL);
2111 return false;
2112}
2113
2114/*
2115 * Detach the thread from the various data structures, notify other threads
2116 * that are waiting to "join" it, and free up all heap-allocated storage.
2117 *
2118 * Used for all threads.
2119 *
2120 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2121 * requires us to enforce this for the DetachCurrentThread call, probably
2122 * because it also says that DetachCurrentThread causes all monitors
2123 * associated with the thread to be released. (Because the stack is empty,
2124 * we only have to worry about explicit JNI calls to MonitorEnter.)
2125 *
2126 * THOUGHT:
2127 * We might want to avoid freeing our internal Thread structure until the
2128 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2129 * get to once the thread shuts down, but there is a small possibility of
2130 * an operation starting in another thread before this thread halts, and
2131 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2132 * We don't want something like Thread.isInterrupted() crawling through
2133 * freed storage. Can do with a Thread finalizer, or by creating a
2134 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2135 * state into that.
2136 */
2137void dvmDetachCurrentThread(void)
2138{
2139 Thread* self = dvmThreadSelf();
2140 Object* vmThread;
2141 Object* group;
2142
2143 /*
2144 * Make sure we're not detaching a thread that's still running. (This
2145 * could happen with an explicit JNI detach call.)
2146 *
2147 * A thread created by interpreted code will finish with a depth of
2148 * zero, while a JNI-attached thread will have the synthetic "stack
2149 * starter" native method at the top.
2150 */
2151 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2152 if (curDepth != 0) {
2153 bool topIsNative = false;
2154
2155 if (curDepth == 1) {
2156 /* not expecting a lingering break frame; just look at curFrame */
2157 assert(!dvmIsBreakFrame(self->curFrame));
2158 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2159 if (dvmIsNativeMethod(ssa->method))
2160 topIsNative = true;
2161 }
2162
2163 if (!topIsNative) {
2164 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2165 curDepth);
2166 dvmDumpThread(self, false);
2167 dvmAbort();
2168 }
2169 }
2170
2171 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2172 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2173
2174 /*
2175 * Release any held monitors. Since there are no interpreted stack
2176 * frames, the only thing left are the monitors held by JNI MonitorEnter
2177 * calls.
2178 */
2179 dvmReleaseJniMonitors(self);
2180
2181 /*
2182 * Do some thread-exit uncaught exception processing if necessary.
2183 */
2184 if (dvmCheckException(self))
2185 threadExitUncaughtException(self, group);
2186
2187 /*
2188 * Remove the thread from the thread group.
2189 */
2190 if (group != NULL) {
2191 Method* removeThread =
2192 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2193 JValue unused;
2194 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2195 }
2196
2197 /*
2198 * Clear the vmThread reference in the Thread object. Interpreted code
2199 * will now see that this Thread is not running. As this may be the
2200 * only reference to the VMThread object that the VM knows about, we
2201 * have to create an internal reference to it first.
2202 */
2203 vmThread = dvmGetFieldObject(self->threadObj,
2204 gDvm.offJavaLangThread_vmThread);
2205 dvmAddTrackedAlloc(vmThread, self);
2206 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2207
2208 /* clear out our struct Thread pointer, since it's going away */
2209 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2210
2211 /*
2212 * Tell the debugger & DDM. This may cause the current thread or all
2213 * threads to suspend.
2214 *
2215 * The JDWP spec is somewhat vague about when this happens, other than
2216 * that it's issued by the dying thread, which may still appear in
2217 * an "all threads" listing.
2218 */
2219 if (gDvm.debuggerConnected)
2220 dvmDbgPostThreadDeath(self);
2221
2222 /*
2223 * Thread.join() is implemented as an Object.wait() on the VMThread
2224 * object. Signal anyone who is waiting.
2225 */
2226 dvmLockObject(self, vmThread);
2227 dvmObjectNotifyAll(self, vmThread);
2228 dvmUnlockObject(self, vmThread);
2229
2230 dvmReleaseTrackedAlloc(vmThread, self);
2231 vmThread = NULL;
2232
2233 /*
2234 * We're done manipulating objects, so it's okay if the GC runs in
2235 * parallel with us from here out. It's important to do this if
2236 * profiling is enabled, since we can wait indefinitely.
2237 */
2238 self->status = THREAD_VMWAIT;
2239
2240#ifdef WITH_PROFILER
2241 /*
2242 * If we're doing method trace profiling, we don't want threads to exit,
2243 * because if they do we'll end up reusing thread IDs. This complicates
2244 * analysis and makes it impossible to have reasonable output in the
2245 * "threads" section of the "key" file.
2246 *
2247 * We need to do this after Thread.join() completes, or other threads
2248 * could get wedged. Since self->threadObj is still valid, the Thread
2249 * object will not get GCed even though we're no longer in the ThreadGroup
2250 * list (which is important since the profiling thread needs to get
2251 * the thread's name).
2252 */
2253 MethodTraceState* traceState = &gDvm.methodTrace;
2254
2255 dvmLockMutex(&traceState->startStopLock);
2256 if (traceState->traceEnabled) {
2257 LOGI("threadid=%d: waiting for method trace to finish\n",
2258 self->threadId);
2259 while (traceState->traceEnabled) {
2260 int cc;
2261 cc = pthread_cond_wait(&traceState->threadExitCond,
2262 &traceState->startStopLock);
2263 assert(cc == 0);
2264 }
2265 }
2266 dvmUnlockMutex(&traceState->startStopLock);
2267#endif
2268
2269 dvmLockThreadList(self);
2270
2271 /*
2272 * Lose the JNI context.
2273 */
2274 dvmDestroyJNIEnv(self->jniEnv);
2275 self->jniEnv = NULL;
2276
2277 self->status = THREAD_ZOMBIE;
2278
2279 /*
2280 * Remove ourselves from the internal thread list.
2281 */
2282 unlinkThread(self);
2283
2284 /*
2285 * If we're the last one standing, signal anybody waiting in
2286 * DestroyJavaVM that it's okay to exit.
2287 */
2288 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2289 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2290
2291 if (gDvm.nonDaemonThreadCount == 0) {
2292 int cc;
2293
2294 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2295 //dvmDumpAllThreads(false);
2296 // cond var guarded by threadListLock, which we already hold
2297 cc = pthread_cond_signal(&gDvm.vmExitCond);
2298 assert(cc == 0);
2299 }
2300 }
2301
2302 LOGV("threadid=%d: bye!\n", self->threadId);
2303 releaseThreadId(self);
2304 dvmUnlockThreadList();
2305
2306 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002307
Bob Lee2fe146a2009-09-10 00:36:29 +02002308 dvmDetachSystemThread(self);
Bob Lee9dc72a32009-09-04 18:28:16 -07002309
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002310 freeThread(self);
2311}
2312
2313
2314/*
2315 * Suspend a single thread. Do not use to suspend yourself.
2316 *
2317 * This is used primarily for debugger/DDMS activity. Does not return
2318 * until the thread has suspended or is in a "safe" state (e.g. executing
2319 * native code outside the VM).
2320 *
2321 * The thread list lock should be held before calling here -- it's not
2322 * entirely safe to hang on to a Thread* from another thread otherwise.
2323 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2324 */
2325void dvmSuspendThread(Thread* thread)
2326{
2327 assert(thread != NULL);
2328 assert(thread != dvmThreadSelf());
2329 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2330
2331 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002332 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002333 thread->dbgSuspendCount++;
2334
2335 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2336 thread->threadId, thread->suspendCount);
2337 unlockThreadSuspendCount();
2338
2339 waitForThreadSuspend(dvmThreadSelf(), thread);
2340}
2341
2342/*
2343 * Reduce the suspend count of a thread. If it hits zero, tell it to
2344 * resume.
2345 *
2346 * Used primarily for debugger/DDMS activity. The thread in question
2347 * might have been suspended singly or as part of a suspend-all operation.
2348 *
2349 * The thread list lock should be held before calling here -- it's not
2350 * entirely safe to hang on to a Thread* from another thread otherwise.
2351 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2352 */
2353void dvmResumeThread(Thread* thread)
2354{
2355 assert(thread != NULL);
2356 assert(thread != dvmThreadSelf());
2357 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2358
2359 lockThreadSuspendCount();
2360 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002361 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002362 thread->dbgSuspendCount--;
2363 } else {
2364 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2365 thread->threadId);
2366 }
2367
2368 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2369 thread->threadId, thread->suspendCount);
2370
2371 if (thread->suspendCount == 0) {
2372 int cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2373 assert(cc == 0);
2374 }
2375
2376 unlockThreadSuspendCount();
2377}
2378
2379/*
2380 * Suspend yourself, as a result of debugger activity.
2381 */
2382void dvmSuspendSelf(bool jdwpActivity)
2383{
2384 Thread* self = dvmThreadSelf();
2385
2386 /* debugger thread may not suspend itself due to debugger activity! */
2387 assert(gDvm.jdwpState != NULL);
2388 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2389 assert(false);
2390 return;
2391 }
2392
2393 /*
2394 * Collisions with other suspends aren't really interesting. We want
2395 * to ensure that we're the only one fiddling with the suspend count
2396 * though.
2397 */
2398 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002399 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002400 self->dbgSuspendCount++;
2401
2402 /*
2403 * Suspend ourselves.
2404 */
2405 assert(self->suspendCount > 0);
2406 self->isSuspended = true;
2407 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2408
2409 /*
2410 * Tell JDWP that we've completed suspension. The JDWP thread can't
2411 * tell us to resume before we're fully asleep because we hold the
2412 * suspend count lock.
2413 *
2414 * If we got here via waitForDebugger(), don't do this part.
2415 */
2416 if (jdwpActivity) {
2417 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2418 // self->threadId, (int) self->handle);
2419 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2420 }
2421
2422 while (self->suspendCount != 0) {
2423 int cc;
2424 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
2425 &gDvm.threadSuspendCountLock);
2426 assert(cc == 0);
2427 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002428 /*
2429 * The condition was signaled but we're still suspended. This
2430 * can happen if the debugger lets go while a SIGQUIT thread
2431 * dump event is pending (assuming SignalCatcher was resumed for
2432 * just long enough to try to grab the thread-suspend lock).
2433 */
2434 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
2435 self->threadId, self->suspendCount, self->dbgSuspendCount,
2436 self->isSuspended ? 'Y' : 'N');
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002437 }
2438 }
2439 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2440 self->isSuspended = false;
2441 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2442 self->threadId, self->status);
2443
2444 unlockThreadSuspendCount();
2445}
2446
2447
2448#ifdef HAVE_GLIBC
2449# define NUM_FRAMES 20
2450# include <execinfo.h>
2451/*
2452 * glibc-only stack dump function. Requires link with "--export-dynamic".
2453 *
2454 * TODO: move this into libs/cutils and make it work for all platforms.
2455 */
2456static void printBackTrace(void)
2457{
2458 void* array[NUM_FRAMES];
2459 size_t size;
2460 char** strings;
2461 size_t i;
2462
2463 size = backtrace(array, NUM_FRAMES);
2464 strings = backtrace_symbols(array, size);
2465
2466 LOGW("Obtained %zd stack frames.\n", size);
2467
2468 for (i = 0; i < size; i++)
2469 LOGW("%s\n", strings[i]);
2470
2471 free(strings);
2472}
2473#else
2474static void printBackTrace(void) {}
2475#endif
2476
2477/*
2478 * Dump the state of the current thread and that of another thread that
2479 * we think is wedged.
2480 */
2481static void dumpWedgedThread(Thread* thread)
2482{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002483 dvmDumpThread(dvmThreadSelf(), false);
2484 printBackTrace();
2485
2486 // dumping a running thread is risky, but could be useful
2487 dvmDumpThread(thread, true);
2488
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002489 // stop now and get a core dump
2490 //abort();
2491}
2492
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002493/* "change flags" values for next two functions */
2494enum { kChangedPriority = 0x01, kChangedPolicy = 0x02 };
2495
2496/*
2497 * If the thread is running at below-normal priority, temporarily elevate
2498 * it to "normal".
2499 *
2500 * Returns zero if no changes were made. Otherwise, returns bit flags
2501 * indicating what was changed, storing the previous values in the
2502 * provided locations.
2503 */
2504static int raiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
2505 SchedPolicy* pSavedThreadPolicy)
2506{
2507 errno = 0;
2508 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2509 if (errno != 0) {
2510 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2511 thread->threadId, thread->systemTid);
2512 return 0;
2513 }
2514 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2515 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2516 thread->threadId, thread->systemTid);
2517 return 0;
2518 }
2519
2520 int changeFlags = 0;
2521
2522 /*
2523 * Change the priority if we're in the background group.
2524 */
2525 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2526 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2527 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2528 } else {
2529 changeFlags |= kChangedPolicy;
2530 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2531 thread->systemTid, *pSavedThreadPolicy);
2532 }
2533 }
2534
2535 /*
2536 * getpriority() returns the "nice" value, so larger numbers indicate
2537 * lower priority, with 0 being normal.
2538 */
2539 if (*pSavedThreadPrio > 0) {
2540 const int kHigher = 0;
2541 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2542 LOGW("Couldn't raise priority on tid %d to %d\n",
2543 thread->systemTid, kHigher);
2544 } else {
2545 changeFlags |= kChangedPriority;
2546 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2547 thread->systemTid, *pSavedThreadPrio, kHigher);
2548 }
2549 }
2550
2551 return changeFlags;
2552}
2553
2554/*
2555 * Reset the priority values for the thread in question.
2556 */
2557static void resetThreadPriority(Thread* thread, int changeFlags,
2558 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2559{
2560 if ((changeFlags & kChangedPolicy) != 0) {
2561 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2562 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2563 thread->systemTid, savedThreadPolicy);
2564 } else {
2565 LOGD("Restored policy of %d to %d\n",
2566 thread->systemTid, savedThreadPolicy);
2567 }
2568 }
2569
2570 if ((changeFlags & kChangedPriority) != 0) {
2571 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2572 {
2573 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2574 thread->systemTid, savedThreadPrio);
2575 } else {
2576 LOGD("Restored priority on %d to %d\n",
2577 thread->systemTid, savedThreadPrio);
2578 }
2579 }
2580}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002581
2582/*
2583 * Wait for another thread to see the pending suspension and stop running.
2584 * It can either suspend itself or go into a non-running state such as
2585 * VMWAIT or NATIVE in which it cannot interact with the GC.
2586 *
2587 * If we're running at a higher priority, sched_yield() may not do anything,
2588 * so we need to sleep for "long enough" to guarantee that the other
2589 * thread has a chance to finish what it's doing. Sleeping for too short
2590 * a period (e.g. less than the resolution of the sleep clock) might cause
2591 * the scheduler to return immediately, so we want to start with a
2592 * "reasonable" value and expand.
2593 *
2594 * This does not return until the other thread has stopped running.
2595 * Eventually we time out and the VM aborts.
2596 *
2597 * This does not try to detect the situation where two threads are
2598 * waiting for each other to suspend. In normal use this is part of a
2599 * suspend-all, which implies that the suspend-all lock is held, or as
2600 * part of a debugger action in which the JDWP thread is always the one
2601 * doing the suspending. (We may need to re-evaluate this now that
2602 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2603 *
2604 * TODO: track basic stats about time required to suspend VM.
2605 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002606#define FIRST_SLEEP (250*1000) /* 0.25s */
2607#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002608static void waitForThreadSuspend(Thread* self, Thread* thread)
2609{
2610 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002611 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002612 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002613 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002614 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002615 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002616
2617 int sleepIter = 0;
2618 int retryCount = 0;
2619 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002620 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002621
2622 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002623 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002624 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002625 if (firstStartWhen == 0) // first iteration of first attempt
2626 firstStartWhen = startWhen;
2627
2628 /*
2629 * After waiting for a bit, check to see if the target thread is
2630 * running at a reduced priority. If so, bump it up temporarily
2631 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002632 */
2633 if (retryCount == 2) {
2634 assert(thread->systemTid != 0);
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002635 priChangeFlags = raiseThreadPriorityIfNeeded(thread,
2636 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002637 }
2638 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002639
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002640#if defined (WITH_JIT)
2641 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002642 * If we're still waiting after the first timeout, unchain all
2643 * translations iff:
2644 * 1) There are new chains formed since the last unchain
2645 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002646 */
Ben Cheng6999d842010-01-26 16:46:15 -08002647 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2648 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002649 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002650 dvmJitUnchainAll();
2651 }
2652#endif
2653
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002654 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002655 * Sleep briefly. The iterative sleep call returns false if we've
2656 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002657 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002658 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002659 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002660 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002661 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002662 thread->threadId, priChangeFlags);
2663 if (retryCount > 1) {
2664 /* stack trace logging is slow; skip on first iter */
2665 dumpWedgedThread(thread);
2666 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002667 complained = true;
2668 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002669
2670 // keep going; could be slow due to valgrind
2671 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002672 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002673
2674 if (retryCount++ == kMaxRetries) {
2675 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2676 self->threadId, thread->threadId);
2677 dvmDumpAllThreads(false);
2678 dvmAbort();
2679 }
2680 }
2681 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002682
2683 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002684 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2685 self->threadId,
2686 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002687 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2688 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002689 if (priChangeFlags != 0) {
2690 resetThreadPriority(thread, priChangeFlags, savedThreadPrio,
2691 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002692 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002693}
2694
2695/*
2696 * Suspend all threads except the current one. This is used by the GC,
2697 * the debugger, and by any thread that hits a "suspend all threads"
2698 * debugger event (e.g. breakpoint or exception).
2699 *
2700 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2701 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2702 * create objects and even execute arbitrary code. The "why" argument
2703 * allows the caller to say why the suspension is taking place.
2704 *
2705 * This can be called when a global suspend has already happened, due to
2706 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2707 * doesn't work.
2708 *
2709 * DO NOT grab any locks before calling here. We grab & release the thread
2710 * lock and suspend lock here (and we're not using recursive threads), and
2711 * we might have to self-suspend if somebody else beats us here.
2712 *
2713 * The current thread may not be attached to the VM. This can happen if
2714 * we happen to GC as the result of an allocation of a Thread object.
2715 */
2716void dvmSuspendAllThreads(SuspendCause why)
2717{
2718 Thread* self = dvmThreadSelf();
2719 Thread* thread;
2720
2721 assert(why != 0);
2722
2723 /*
2724 * Start by grabbing the thread suspend lock. If we can't get it, most
2725 * likely somebody else is in the process of performing a suspend or
2726 * resume, so lockThreadSuspend() will cause us to self-suspend.
2727 *
2728 * We keep the lock until all other threads are suspended.
2729 */
2730 lockThreadSuspend("susp-all", why);
2731
2732 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2733
2734 /*
2735 * This is possible if the current thread was in VMWAIT mode when a
2736 * suspend-all happened, and then decided to do its own suspend-all.
2737 * This can happen when a couple of threads have simultaneous events
2738 * of interest to the debugger.
2739 */
2740 //assert(self->suspendCount == 0);
2741
2742 /*
2743 * Increment everybody's suspend count (except our own).
2744 */
2745 dvmLockThreadList(self);
2746
2747 lockThreadSuspendCount();
2748 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2749 if (thread == self)
2750 continue;
2751
2752 /* debugger events don't suspend JDWP thread */
2753 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2754 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2755 continue;
2756
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002757 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002758 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2759 thread->dbgSuspendCount++;
2760 }
2761 unlockThreadSuspendCount();
2762
2763 /*
2764 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2765 * indicate the code is either running natively or sleeping quietly.
2766 * Any attempt to transition back to THREAD_RUNNING will cause a check
2767 * for suspension, so it should be impossible for anything to execute
2768 * interpreted code or modify objects (assuming native code plays nicely).
2769 *
2770 * It's also okay if the thread transitions to a non-RUNNING state.
2771 *
2772 * Note we released the threadSuspendCountLock before getting here,
2773 * so if another thread is fiddling with its suspend count (perhaps
2774 * self-suspending for the debugger) it won't block while we're waiting
2775 * in here.
2776 */
2777 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2778 if (thread == self)
2779 continue;
2780
2781 /* debugger events don't suspend JDWP thread */
2782 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2783 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2784 continue;
2785
2786 /* wait for the other thread to see the pending suspend */
2787 waitForThreadSuspend(self, thread);
2788
Jeff Hao97319a82009-08-12 16:57:15 -07002789 LOG_THREAD("threadid=%d: threadid=%d status=%d c=%d dc=%d isSusp=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002790 self->threadId,
2791 thread->threadId, thread->status, thread->suspendCount,
2792 thread->dbgSuspendCount, thread->isSuspended);
2793 }
2794
2795 dvmUnlockThreadList();
2796 unlockThreadSuspend();
2797
2798 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2799}
2800
2801/*
2802 * Resume all threads that are currently suspended.
2803 *
2804 * The "why" must match with the previous suspend.
2805 */
2806void dvmResumeAllThreads(SuspendCause why)
2807{
2808 Thread* self = dvmThreadSelf();
2809 Thread* thread;
2810 int cc;
2811
2812 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2813 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2814
2815 /*
2816 * Decrement the suspend counts for all threads. No need for atomic
2817 * writes, since nobody should be moving until we decrement the count.
2818 * We do need to hold the thread list because of JNI attaches.
2819 */
2820 dvmLockThreadList(self);
2821 lockThreadSuspendCount();
2822 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2823 if (thread == self)
2824 continue;
2825
2826 /* debugger events don't suspend JDWP thread */
2827 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2828 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002829 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002830 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002831 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002832
2833 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002834 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002835 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2836 thread->dbgSuspendCount--;
2837 } else {
2838 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2839 thread->threadId);
2840 }
2841 }
2842 unlockThreadSuspendCount();
2843 dvmUnlockThreadList();
2844
2845 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002846 * In some ways it makes sense to continue to hold the thread-suspend
2847 * lock while we issue the wakeup broadcast. It allows us to complete
2848 * one operation before moving on to the next, which simplifies the
2849 * thread activity debug traces.
2850 *
2851 * This approach caused us some difficulty under Linux, because the
2852 * condition variable broadcast not only made the threads runnable,
2853 * but actually caused them to execute, and it was a while before
2854 * the thread performing the wakeup had an opportunity to release the
2855 * thread-suspend lock.
2856 *
2857 * This is a problem because, when a thread tries to acquire that
2858 * lock, it times out after 3 seconds. If at some point the thread
2859 * is told to suspend, the clock resets; but since the VM is still
2860 * theoretically mid-resume, there's no suspend pending. If, for
2861 * example, the GC was waking threads up while the SIGQUIT handler
2862 * was trying to acquire the lock, we would occasionally time out on
2863 * a busy system and SignalCatcher would abort.
2864 *
2865 * We now perform the unlock before the wakeup broadcast. The next
2866 * suspend can't actually start until the broadcast completes and
2867 * returns, because we're holding the thread-suspend-count lock, but the
2868 * suspending thread is now able to make progress and we avoid the abort.
2869 *
2870 * (Technically there is a narrow window between when we release
2871 * the thread-suspend lock and grab the thread-suspend-count lock.
2872 * This could cause us to send a broadcast to threads with nonzero
2873 * suspend counts, but this is expected and they'll all just fall
2874 * right back to sleep. It's probably safe to grab the suspend-count
2875 * lock before releasing thread-suspend, since we're still following
2876 * the correct order of acquisition, but it feels weird.)
2877 */
2878
2879 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2880 unlockThreadSuspend();
2881
2882 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002883 * Broadcast a notification to all suspended threads, some or all of
2884 * which may choose to wake up. No need to wait for them.
2885 */
2886 lockThreadSuspendCount();
2887 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2888 assert(cc == 0);
2889 unlockThreadSuspendCount();
2890
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002891 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2892}
2893
2894/*
2895 * Undo any debugger suspensions. This is called when the debugger
2896 * disconnects.
2897 */
2898void dvmUndoDebuggerSuspensions(void)
2899{
2900 Thread* self = dvmThreadSelf();
2901 Thread* thread;
2902 int cc;
2903
2904 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2905 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2906
2907 /*
2908 * Decrement the suspend counts for all threads. No need for atomic
2909 * writes, since nobody should be moving until we decrement the count.
2910 * We do need to hold the thread list because of JNI attaches.
2911 */
2912 dvmLockThreadList(self);
2913 lockThreadSuspendCount();
2914 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2915 if (thread == self)
2916 continue;
2917
2918 /* debugger events don't suspend JDWP thread */
2919 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2920 assert(thread->dbgSuspendCount == 0);
2921 continue;
2922 }
2923
2924 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002925 dvmAddToThreadSuspendCount(&thread->suspendCount,
2926 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002927 thread->dbgSuspendCount = 0;
2928 }
2929 unlockThreadSuspendCount();
2930 dvmUnlockThreadList();
2931
2932 /*
2933 * Broadcast a notification to all suspended threads, some or all of
2934 * which may choose to wake up. No need to wait for them.
2935 */
2936 lockThreadSuspendCount();
2937 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2938 assert(cc == 0);
2939 unlockThreadSuspendCount();
2940
2941 unlockThreadSuspend();
2942
2943 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2944}
2945
2946/*
2947 * Determine if a thread is suspended.
2948 *
2949 * As with all operations on foreign threads, the caller should hold
2950 * the thread list lock before calling.
2951 */
2952bool dvmIsSuspended(Thread* thread)
2953{
2954 /*
2955 * The thread could be:
2956 * (1) Running happily. status is RUNNING, isSuspended is false,
2957 * suspendCount is zero. Return "false".
2958 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2959 * suspendCount is nonzero. Return "false".
2960 * (3) Suspended. suspendCount is nonzero, and either (status is
2961 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2962 * Return "true".
2963 * (4) Waking up. suspendCount is zero, status is RUNNING and
2964 * isSuspended is true. Return "false" (since it could change
2965 * out from under us, unless we hold suspendCountLock).
2966 */
2967
2968 return (thread->suspendCount != 0 &&
2969 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2970 (thread->status != THREAD_RUNNING)));
2971}
2972
2973/*
2974 * Wait until another thread self-suspends. This is specifically for
2975 * synchronization between the JDWP thread and a thread that has decided
2976 * to suspend itself after sending an event to the debugger.
2977 *
2978 * Threads that encounter "suspend all" events work as well -- the thread
2979 * in question suspends everybody else and then itself.
2980 *
2981 * We can't hold a thread lock here or in the caller, because we could
2982 * get here just before the to-be-waited-for-thread issues a "suspend all".
2983 * There's an opportunity for badness if the thread we're waiting for exits
2984 * and gets cleaned up, but since the thread in question is processing a
2985 * debugger event, that's not really a possibility. (To avoid deadlock,
2986 * it's important that we not be in THREAD_RUNNING while we wait.)
2987 */
2988void dvmWaitForSuspend(Thread* thread)
2989{
2990 Thread* self = dvmThreadSelf();
2991
2992 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
2993 self->threadId, thread->threadId);
2994
2995 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2996 assert(thread != self);
2997 assert(self->status != THREAD_RUNNING);
2998
2999 waitForThreadSuspend(self, thread);
3000
3001 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3002 self->threadId, thread->threadId);
3003}
3004
3005/*
3006 * Check to see if we need to suspend ourselves. If so, go to sleep on
3007 * a condition variable.
3008 *
3009 * Takes "self" as an argument as an optimization. Pass in NULL to have
3010 * it do the lookup.
3011 *
3012 * Returns "true" if we suspended ourselves.
3013 */
3014bool dvmCheckSuspendPending(Thread* self)
3015{
3016 bool didSuspend;
3017
3018 if (self == NULL)
3019 self = dvmThreadSelf();
3020
3021 /* fast path: if count is zero, bail immediately */
3022 if (self->suspendCount == 0)
3023 return false;
3024
3025 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3026
3027 assert(self->suspendCount >= 0); /* XXX: valid? useful? */
3028
3029 didSuspend = (self->suspendCount != 0);
3030 self->isSuspended = true;
3031 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
3032 while (self->suspendCount != 0) {
3033 /* wait for wakeup signal; releases lock */
3034 int cc;
3035 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
3036 &gDvm.threadSuspendCountLock);
3037 assert(cc == 0);
3038 }
3039 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
3040 self->isSuspended = false;
3041 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3042 self->threadId, self->status);
3043
3044 unlockThreadSuspendCount();
3045
3046 return didSuspend;
3047}
3048
3049/*
3050 * Update our status.
3051 *
3052 * The "self" argument, which may be NULL, is accepted as an optimization.
3053 *
3054 * Returns the old status.
3055 */
3056ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3057{
3058 ThreadStatus oldStatus;
3059
3060 if (self == NULL)
3061 self = dvmThreadSelf();
3062
3063 LOGVV("threadid=%d: (status %d -> %d)\n",
3064 self->threadId, self->status, newStatus);
3065
3066 oldStatus = self->status;
3067
3068 if (newStatus == THREAD_RUNNING) {
3069 /*
3070 * Change our status to THREAD_RUNNING. The transition requires
3071 * that we check for pending suspension, because the VM considers
3072 * us to be "asleep" in all other states.
3073 *
3074 * We need to do the "suspend pending" check FIRST, because it grabs
3075 * a lock that could be held by something that wants us to suspend.
3076 * If we're in RUNNING it will wait for us, and we'll be waiting
3077 * for the lock it holds.
3078 */
3079 assert(self->status != THREAD_RUNNING);
3080
3081 dvmCheckSuspendPending(self);
3082 self->status = THREAD_RUNNING;
3083 } else {
3084 /*
3085 * Change from one state to another, neither of which is
3086 * THREAD_RUNNING. This is most common during system or thread
3087 * initialization.
3088 */
3089 self->status = newStatus;
3090 }
3091
3092 return oldStatus;
3093}
3094
3095/*
3096 * Get a statically defined thread group from a field in the ThreadGroup
3097 * Class object. Expected arguments are "mMain" and "mSystem".
3098 */
3099static Object* getStaticThreadGroup(const char* fieldName)
3100{
3101 StaticField* groupField;
3102 Object* groupObj;
3103
3104 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3105 fieldName, "Ljava/lang/ThreadGroup;");
3106 if (groupField == NULL) {
3107 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3108 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3109 return NULL;
3110 }
3111 groupObj = dvmGetStaticFieldObject(groupField);
3112 if (groupObj == NULL) {
3113 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3114 dvmThrowException("Ljava/lang/InternalError;", NULL);
3115 return NULL;
3116 }
3117
3118 return groupObj;
3119}
3120Object* dvmGetSystemThreadGroup(void)
3121{
3122 return getStaticThreadGroup("mSystem");
3123}
3124Object* dvmGetMainThreadGroup(void)
3125{
3126 return getStaticThreadGroup("mMain");
3127}
3128
3129/*
3130 * Given a VMThread object, return the associated Thread*.
3131 *
3132 * NOTE: if the thread detaches, the struct Thread will disappear, and
3133 * we will be touching invalid data. For safety, lock the thread list
3134 * before calling this.
3135 */
3136Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3137{
3138 int vmData;
3139
3140 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003141
3142 if (false) {
3143 Thread* thread = gDvm.threadList;
3144 while (thread != NULL) {
3145 if ((Thread*)vmData == thread)
3146 break;
3147
3148 thread = thread->next;
3149 }
3150
3151 if (thread == NULL) {
3152 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3153 vmThreadObj, (Thread*)vmData);
3154 vmData = 0;
3155 }
3156 }
3157
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003158 return (Thread*) vmData;
3159}
3160
3161
3162/*
3163 * Conversion map for "nice" values.
3164 *
3165 * We use Android thread priority constants to be consistent with the rest
3166 * of the system. In some cases adjacent entries may overlap.
3167 */
3168static const int kNiceValues[10] = {
3169 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3170 ANDROID_PRIORITY_BACKGROUND + 6,
3171 ANDROID_PRIORITY_BACKGROUND + 3,
3172 ANDROID_PRIORITY_BACKGROUND,
3173 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3174 ANDROID_PRIORITY_NORMAL - 2,
3175 ANDROID_PRIORITY_NORMAL - 4,
3176 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3177 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3178 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3179};
3180
3181/*
3182 * Change the priority of a system thread to match that of the Thread object.
3183 *
3184 * We map a priority value from 1-10 to Linux "nice" values, where lower
3185 * numbers indicate higher priority.
3186 */
3187void dvmChangeThreadPriority(Thread* thread, int newPriority)
3188{
3189 pid_t pid = thread->systemTid;
3190 int newNice;
3191
3192 if (newPriority < 1 || newPriority > 10) {
3193 LOGW("bad priority %d\n", newPriority);
3194 newPriority = 5;
3195 }
3196 newNice = kNiceValues[newPriority-1];
3197
Andy McFaddend62c0b52009-08-04 15:02:12 -07003198 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003199 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003200 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003201 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003202 }
3203
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003204 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3205 char* str = dvmGetThreadName(thread);
3206 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3207 pid, str, newPriority, newNice, strerror(errno));
3208 free(str);
3209 } else {
3210 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3211 pid, newPriority, newNice);
3212 }
3213}
3214
3215/*
3216 * Get the thread priority for the current thread by querying the system.
3217 * This is useful when attaching a thread through JNI.
3218 *
3219 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3220 */
3221static int getThreadPriorityFromSystem(void)
3222{
3223 int i, sysprio, jprio;
3224
3225 errno = 0;
3226 sysprio = getpriority(PRIO_PROCESS, 0);
3227 if (sysprio == -1 && errno != 0) {
3228 LOGW("getpriority() failed: %s\n", strerror(errno));
3229 return THREAD_NORM_PRIORITY;
3230 }
3231
3232 jprio = THREAD_MIN_PRIORITY;
3233 for (i = 0; i < NELEM(kNiceValues); i++) {
3234 if (sysprio >= kNiceValues[i])
3235 break;
3236 jprio++;
3237 }
3238 if (jprio > THREAD_MAX_PRIORITY)
3239 jprio = THREAD_MAX_PRIORITY;
3240
3241 return jprio;
3242}
3243
3244
3245/*
3246 * Return true if the thread is on gDvm.threadList.
3247 * Caller should not hold gDvm.threadListLock.
3248 */
3249bool dvmIsOnThreadList(const Thread* thread)
3250{
3251 bool ret = false;
3252
3253 dvmLockThreadList(NULL);
3254 if (thread == gDvm.threadList) {
3255 ret = true;
3256 } else {
3257 ret = thread->prev != NULL || thread->next != NULL;
3258 }
3259 dvmUnlockThreadList();
3260
3261 return ret;
3262}
3263
3264/*
3265 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3266 * output target.
3267 */
3268void dvmDumpThread(Thread* thread, bool isRunning)
3269{
3270 DebugOutputTarget target;
3271
3272 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3273 dvmDumpThreadEx(&target, thread, isRunning);
3274}
3275
3276/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003277 * Try to get the scheduler group.
3278 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003279 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003280 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003281 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003282 *
3283 * We return the part after the "/", which will be an empty string for
3284 * the default cgroup. If the string is longer than "bufLen", the string
3285 * will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003286 *
3287 * TODO: this is cloned from a static function in libcutils; expose that?
Andy McFaddend62c0b52009-08-04 15:02:12 -07003288 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003289static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003290{
3291#ifdef HAVE_ANDROID_OS
3292 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003293 char lineBuf[256];
3294 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003295
Andy McFadden7f64ede2010-03-03 15:37:10 -08003296 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
3297 if (!(fp = fopen(pathBuf, "r"))) {
3298 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003299 }
3300
Andy McFadden7f64ede2010-03-03 15:37:10 -08003301 while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
3302 char *next = lineBuf;
3303 char *subsys;
3304 char *grp;
3305 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003306
Andy McFadden7f64ede2010-03-03 15:37:10 -08003307 /* Junk the first field */
3308 if (!strsep(&next, ":")) {
3309 goto out_bad_data;
3310 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003311
Andy McFadden7f64ede2010-03-03 15:37:10 -08003312 if (!(subsys = strsep(&next, ":"))) {
3313 goto out_bad_data;
3314 }
3315
3316 if (strcmp(subsys, "cpu")) {
3317 /* Not the subsys we're looking for */
3318 continue;
3319 }
3320
3321 if (!(grp = strsep(&next, ":"))) {
3322 goto out_bad_data;
3323 }
3324 grp++; /* Drop the leading '/' */
3325 len = strlen(grp);
3326 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3327
3328 if (bufLen <= len) {
3329 len = bufLen - 1;
3330 }
3331 strncpy(buf, grp, len);
3332 buf[len] = '\0';
3333 fclose(fp);
3334 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003335 }
3336
Andy McFadden7f64ede2010-03-03 15:37:10 -08003337 LOGE("Failed to find cpu subsys");
3338 fclose(fp);
3339 return -1;
3340 out_bad_data:
3341 LOGE("Bad cgroup data {%s}", lineBuf);
3342 fclose(fp);
3343 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003344#else
Andy McFadden7f64ede2010-03-03 15:37:10 -08003345 errno = ENOSYS;
3346 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003347#endif
3348}
3349
3350/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003351 * Convert ThreadStatus to a string.
3352 */
3353const char* dvmGetThreadStatusStr(ThreadStatus status)
3354{
3355 switch (status) {
3356 case THREAD_ZOMBIE: return "ZOMBIE";
3357 case THREAD_RUNNING: return "RUNNABLE";
3358 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3359 case THREAD_MONITOR: return "MONITOR";
3360 case THREAD_WAIT: return "WAIT";
3361 case THREAD_INITIALIZING: return "INITIALIZING";
3362 case THREAD_STARTING: return "STARTING";
3363 case THREAD_NATIVE: return "NATIVE";
3364 case THREAD_VMWAIT: return "VMWAIT";
3365 default: return "UNKNOWN";
3366 }
3367}
3368
3369/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003370 * Print information about the specified thread.
3371 *
3372 * Works best when the thread in question is "self" or has been suspended.
3373 * When dumping a separate thread that's still running, set "isRunning" to
3374 * use a more cautious thread dump function.
3375 */
3376void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3377 bool isRunning)
3378{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003379 Object* threadObj;
3380 Object* groupObj;
3381 StringObject* nameStr;
3382 char* threadName = NULL;
3383 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003384 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003385 bool isDaemon;
3386 int priority; // java.lang.Thread priority
3387 int policy; // pthread policy
3388 struct sched_param sp; // pthread scheduling parameters
3389
3390 threadObj = thread->threadObj;
3391 if (threadObj == NULL) {
3392 LOGW("Can't dump thread %d: threadObj not set\n", thread->threadId);
3393 return;
3394 }
3395 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3396 gDvm.offJavaLangThread_name);
3397 threadName = dvmCreateCstrFromString(nameStr);
3398
3399 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3400 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3401
3402 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3403 LOGW("Warning: pthread_getschedparam failed\n");
3404 policy = -1;
3405 sp.sched_priority = -1;
3406 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003407 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
3408 sizeof(schedulerGroupBuf)) != 0)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003409 {
3410 strcpy(schedulerGroupBuf, "unknown");
3411 } else if (schedulerGroupBuf[0] == '\0') {
3412 strcpy(schedulerGroupBuf, "default");
3413 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003414
3415 /* a null value for group is not expected, but deal with it anyway */
3416 groupObj = (Object*) dvmGetFieldObject(threadObj,
3417 gDvm.offJavaLangThread_group);
3418 if (groupObj != NULL) {
3419 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3420 "name", "Ljava/lang/String;");
3421 if (offset < 0) {
3422 LOGW("Unable to find 'name' field in ThreadGroup\n");
3423 } else {
3424 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3425 groupName = dvmCreateCstrFromString(nameStr);
3426 }
3427 }
3428 if (groupName == NULL)
3429 groupName = strdup("(BOGUS GROUP)");
3430
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003431 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003432 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003433 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003434 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3435#if defined(WITH_JIT)
3436 thread->inJitCodeCache ? " JIT" : ""
3437#else
3438 ""
3439#endif
3440 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003441 dvmPrintDebugMessage(target,
Andy McFadden2aa43612009-06-17 16:29:30 -07003442 " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003443 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden2aa43612009-06-17 16:29:30 -07003444 thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003445 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003446 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003447 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003448 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003449
3450#ifdef WITH_MONITOR_TRACKING
3451 if (!isRunning) {
3452 LockedObjectData* lod = thread->pLockedObjects;
3453 if (lod != NULL)
3454 dvmPrintDebugMessage(target, " | monitors held:\n");
3455 else
3456 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3457 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003458 Object* obj = lod->obj;
3459 if (obj->clazz == gDvm.classJavaLangClass) {
3460 ClassObject* clazz = (ClassObject*) obj;
3461 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3462 obj, lod->recursionCount, obj->clazz->descriptor,
3463 clazz->descriptor);
3464 } else {
3465 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3466 obj, lod->recursionCount, obj->clazz->descriptor);
3467 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003468 lod = lod->next;
3469 }
3470 }
3471#endif
3472
3473 if (isRunning)
3474 dvmDumpRunningThreadStack(target, thread);
3475 else
3476 dvmDumpThreadStack(target, thread);
3477
3478 free(threadName);
3479 free(groupName);
3480
3481}
3482
3483/*
3484 * Get the name of a thread.
3485 *
3486 * For correctness, the caller should hold the thread list lock to ensure
3487 * that the thread doesn't go away mid-call.
3488 *
3489 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3490 */
3491char* dvmGetThreadName(Thread* thread)
3492{
3493 StringObject* nameObj;
3494
3495 if (thread->threadObj == NULL) {
3496 LOGW("threadObj is NULL, name not available\n");
3497 return strdup("-unknown-");
3498 }
3499
3500 nameObj = (StringObject*)
3501 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3502 return dvmCreateCstrFromString(nameObj);
3503}
3504
3505/*
3506 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3507 * an output target.
3508 */
3509void dvmDumpAllThreads(bool grabLock)
3510{
3511 DebugOutputTarget target;
3512
3513 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3514 dvmDumpAllThreadsEx(&target, grabLock);
3515}
3516
3517/*
3518 * Print information about all known threads. Assumes they have been
3519 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3520 *
3521 * If "grabLock" is true, we grab the thread lock list. This is important
3522 * to do unless the caller already holds the lock.
3523 */
3524void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3525{
3526 Thread* thread;
3527
3528 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3529
3530 if (grabLock)
3531 dvmLockThreadList(dvmThreadSelf());
3532
3533 thread = gDvm.threadList;
3534 while (thread != NULL) {
3535 dvmDumpThreadEx(target, thread, false);
3536
3537 /* verify link */
3538 assert(thread->next == NULL || thread->next->prev == thread);
3539
3540 thread = thread->next;
3541 }
3542
3543 if (grabLock)
3544 dvmUnlockThreadList();
3545}
3546
3547#ifdef WITH_MONITOR_TRACKING
3548/*
3549 * Count up the #of locked objects in the current thread.
3550 */
3551static int getThreadObjectCount(const Thread* self)
3552{
3553 LockedObjectData* lod;
3554 int count = 0;
3555
3556 lod = self->pLockedObjects;
3557 while (lod != NULL) {
3558 count++;
3559 lod = lod->next;
3560 }
3561 return count;
3562}
3563
3564/*
3565 * Add the object to the thread's locked object list if it doesn't already
3566 * exist. The most recently added object is the most likely to be released
3567 * next, so we insert at the head of the list.
3568 *
3569 * If it already exists, we increase the recursive lock count.
3570 *
3571 * The object's lock may be thin or fat.
3572 */
3573void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3574{
3575 LockedObjectData* newLod;
3576 LockedObjectData* lod;
3577 int* trace;
3578 int depth;
3579
3580 lod = self->pLockedObjects;
3581 while (lod != NULL) {
3582 if (lod->obj == obj) {
3583 lod->recursionCount++;
3584 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3585 return;
3586 }
3587 lod = lod->next;
3588 }
3589
3590 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3591 if (newLod == NULL) {
3592 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3593 return;
3594 }
3595 newLod->obj = obj;
3596 newLod->recursionCount = 0;
3597
3598 if (withTrace) {
3599 trace = dvmFillInStackTraceRaw(self, &depth);
3600 newLod->rawStackTrace = trace;
3601 newLod->stackDepth = depth;
3602 }
3603
3604 newLod->next = self->pLockedObjects;
3605 self->pLockedObjects = newLod;
3606
3607 LOGV("+++ threadid=%d: added %p, now %d\n",
3608 self->threadId, newLod, getThreadObjectCount(self));
3609}
3610
3611/*
3612 * Remove the object from the thread's locked object list. If the entry
3613 * has a nonzero recursion count, we just decrement the count instead.
3614 */
3615void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3616{
3617 LockedObjectData* lod;
3618 LockedObjectData* prevLod;
3619
3620 lod = self->pLockedObjects;
3621 prevLod = NULL;
3622 while (lod != NULL) {
3623 if (lod->obj == obj) {
3624 if (lod->recursionCount > 0) {
3625 lod->recursionCount--;
3626 LOGV("+++ -recursive lock %p -> %d\n",
3627 obj, lod->recursionCount);
3628 return;
3629 } else {
3630 break;
3631 }
3632 }
3633 prevLod = lod;
3634 lod = lod->next;
3635 }
3636
3637 if (lod == NULL) {
3638 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3639 return;
3640 }
3641 if (prevLod == NULL) {
3642 /* first item in list */
3643 assert(self->pLockedObjects == lod);
3644 self->pLockedObjects = lod->next;
3645 } else {
3646 /* middle/end of list */
3647 prevLod->next = lod->next;
3648 }
3649
3650 LOGV("+++ threadid=%d: removed %p, now %d\n",
3651 self->threadId, lod, getThreadObjectCount(self));
3652 free(lod->rawStackTrace);
3653 free(lod);
3654}
3655
3656/*
3657 * If the specified object is already in the thread's locked object list,
3658 * return the LockedObjectData struct. Otherwise return NULL.
3659 */
3660LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3661{
3662 LockedObjectData* lod;
3663
3664 lod = self->pLockedObjects;
3665 while (lod != NULL) {
3666 if (lod->obj == obj)
3667 return lod;
3668 lod = lod->next;
3669 }
3670 return NULL;
3671}
3672#endif /*WITH_MONITOR_TRACKING*/
3673
3674
3675/*
3676 * GC helper functions
3677 */
3678
The Android Open Source Project99409882009-03-18 22:20:24 -07003679/*
3680 * Add the contents of the registers from the interpreted call stack.
3681 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003682static void gcScanInterpStackReferences(Thread *thread)
3683{
3684 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003685#if WITH_EXTRA_GC_CHECKS > 1
3686 bool first = true;
3687#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003688
3689 framePtr = (const u4 *)thread->curFrame;
3690 while (framePtr != NULL) {
3691 const StackSaveArea *saveArea;
3692 const Method *method;
3693
3694 saveArea = SAVEAREA_FROM_FP(framePtr);
3695 method = saveArea->method;
The Android Open Source Project99409882009-03-18 22:20:24 -07003696 if (method != NULL && !dvmIsNativeMethod(method)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003697#ifdef COUNT_PRECISE_METHODS
3698 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003699 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3700 LOGI("PGC: added %s.%s %p\n",
3701 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003702#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003703#if WITH_EXTRA_GC_CHECKS > 1
3704 /*
3705 * May also want to enable the memset() in the "invokeMethod"
3706 * goto target in the portable interpreter. That sets the stack
3707 * to a pattern that makes referring to uninitialized data
3708 * very obvious.
3709 */
3710
3711 if (first) {
3712 /*
3713 * First frame, isn't native, check the "alternate" saved PC
3714 * as a sanity check.
3715 *
3716 * It seems like we could check the second frame if the first
3717 * is native, since the PCs should be the same. It turns out
3718 * this doesn't always work. The problem is that we could
3719 * have calls in the sequence:
3720 * interp method #2
3721 * native method
3722 * interp method #1
3723 *
3724 * and then GC while in the native method after returning
3725 * from interp method #2. The currentPc on the stack is
3726 * for interp method #1, but thread->currentPc2 is still
3727 * set for the last thing interp method #2 did.
3728 *
3729 * This can also happen in normal execution:
3730 * - sget-object on not-yet-loaded class
3731 * - class init updates currentPc2
3732 * - static field init is handled by parsing annotations;
3733 * static String init requires creation of a String object,
3734 * which can cause a GC
3735 *
3736 * Essentially, any pattern that involves executing
3737 * interpreted code and then causes an allocation without
3738 * executing instructions in the original method will hit
3739 * this. These are rare enough that the test still has
3740 * some value.
3741 */
3742 if (saveArea->xtra.currentPc != thread->currentPc2) {
3743 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3744 saveArea->xtra.currentPc, thread->currentPc2,
3745 method->clazz->descriptor, method->name, method->insns);
3746 if (saveArea->xtra.currentPc != NULL)
3747 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3748 if (thread->currentPc2 != NULL)
3749 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3750 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003751 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003752 } else {
3753 /*
3754 * It's unusual, but not impossible, for a non-first frame
3755 * to be at something other than a method invocation. For
3756 * example, if we do a new-instance on a nonexistent class,
3757 * we'll have a lot of class loader activity on the stack
3758 * above the frame with the "new" operation. Could also
3759 * happen while we initialize a Throwable when an instruction
3760 * fails.
3761 *
3762 * So there's not much we can do here to verify the PC,
3763 * except to verify that it's a GC point.
3764 */
3765 }
3766 assert(saveArea->xtra.currentPc != NULL);
3767#endif
3768
3769 const RegisterMap* pMap;
3770 const u1* regVector;
3771 int i;
3772
Andy McFaddencf8b55c2009-04-13 15:26:03 -07003773 Method* nonConstMethod = (Method*) method; // quiet gcc
3774 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07003775 if (pMap != NULL) {
3776 /* found map, get registers for this address */
3777 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07003778 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07003779 if (regVector == NULL) {
3780 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
3781 method->clazz->descriptor, method->name, addr);
3782 } else {
3783 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
3784 method->clazz->descriptor, method->name, addr,
3785 thread->threadId);
3786 }
3787 } else {
3788 /*
3789 * No map found. If precise GC is disabled this is
3790 * expected -- we don't create pointers to the map data even
3791 * if it's present -- but if it's enabled it means we're
3792 * unexpectedly falling back on a conservative scan, so it's
3793 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07003794 */
3795 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07003796 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07003797 method->clazz->descriptor, method->name);
3798 }
3799 regVector = NULL;
3800 }
3801
3802 if (regVector == NULL) {
3803 /* conservative scan */
3804 for (i = method->registersSize - 1; i >= 0; i--) {
3805 u4 rval = *framePtr++;
3806 if (rval != 0 && (rval & 0x3) == 0) {
3807 dvmMarkIfObject((Object *)rval);
3808 }
3809 }
3810 } else {
3811 /*
3812 * Precise scan. v0 is at the lowest address on the
3813 * interpreted stack, and is the first bit in the register
3814 * vector, so we can walk through the register map and
3815 * memory in the same direction.
3816 *
3817 * A '1' bit indicates a live reference.
3818 */
3819 u2 bits = 1 << 1;
3820 for (i = method->registersSize - 1; i >= 0; i--) {
3821 u4 rval = *framePtr++;
3822
3823 bits >>= 1;
3824 if (bits == 1) {
3825 /* set bit 9 so we can tell when we're empty */
3826 bits = *regVector++ | 0x0100;
3827 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
3828 }
3829
3830 if (rval != 0 && (bits & 0x01) != 0) {
3831 /*
3832 * Non-null, register marked as live reference. This
3833 * should always be a valid object.
3834 */
3835#if WITH_EXTRA_GC_CHECKS > 0
3836 if ((rval & 0x3) != 0 ||
3837 !dvmIsValidObject((Object*) rval))
3838 {
3839 /* this is very bad */
3840 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
3841 method->registersSize-1 - i, rval);
3842 } else
3843#endif
3844 {
3845 dvmMarkObjectNonNull((Object *)rval);
3846 }
3847 } else {
3848 /*
3849 * Null or non-reference, do nothing at all.
3850 */
3851#if WITH_EXTRA_GC_CHECKS > 1
3852 if (dvmIsValidObject((Object*) rval)) {
3853 /* this is normal, but we feel chatty */
3854 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
3855 method->registersSize-1 - i, rval);
3856 }
3857#endif
3858 }
3859 }
3860 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003861 }
3862 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003863 /* else this is a break frame and there is nothing to mark, or
3864 * this is a native method and the registers are just the "ins",
3865 * copied from various registers in the caller's set.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003866 */
3867
The Android Open Source Project99409882009-03-18 22:20:24 -07003868#if WITH_EXTRA_GC_CHECKS > 1
3869 first = false;
3870#endif
3871
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003872 /* Don't fall into an infinite loop if things get corrupted.
3873 */
3874 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
3875 saveArea->prevFrame == NULL);
3876 framePtr = saveArea->prevFrame;
3877 }
3878}
3879
3880static void gcScanReferenceTable(ReferenceTable *refTable)
3881{
3882 Object **op;
3883
3884 //TODO: these asserts are overkill; turn them off when things stablize.
3885 assert(refTable != NULL);
3886 assert(refTable->table != NULL);
3887 assert(refTable->nextEntry != NULL);
3888 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
3889 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
3890
3891 op = refTable->table;
3892 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
3893 dvmMarkObjectNonNull(*(op++));
3894 }
3895}
3896
Andy McFaddend5ab7262009-08-25 07:19:34 -07003897static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
3898{
3899 Object** op = pRefTable->table;
3900 int numEntries = dvmIndirectRefTableEntries(pRefTable);
3901 int i;
3902
3903 for (i = 0; i < numEntries; i++) {
3904 Object* obj = *op;
3905 if (obj != NULL)
3906 dvmMarkObjectNonNull(obj);
3907 op++;
3908 }
3909}
3910
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003911/*
3912 * Scan a Thread and mark any objects it references.
3913 */
3914static void gcScanThread(Thread *thread)
3915{
3916 assert(thread != NULL);
3917
3918 /*
3919 * The target thread must be suspended or in a state where it can't do
3920 * any harm (e.g. in Object.wait()). The only exception is the current
3921 * thread, which will still be active and in the "running" state.
3922 *
3923 * (Newly-created threads shouldn't be able to shift themselves to
3924 * RUNNING without a suspend-pending check, so this shouldn't cause
3925 * a false-positive.)
3926 */
Andy McFaddend40223e2009-12-07 15:35:51 -08003927 if (thread->status == THREAD_RUNNING && !thread->isSuspended &&
3928 thread != dvmThreadSelf())
3929 {
3930 Thread* self = dvmThreadSelf();
3931 LOGW("threadid=%d: BUG: GC scanning a running thread (%d)\n",
3932 self->threadId, thread->threadId);
3933 dvmDumpThread(thread, true);
3934 LOGW("Found by:\n");
3935 dvmDumpThread(self, false);
3936
3937 /* continue anyway? */
3938 dvmAbort();
3939 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003940
3941 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
3942
3943 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
3944
3945 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
3946
3947 dvmMarkObject(thread->exception); // usually NULL
3948 gcScanReferenceTable(&thread->internalLocalRefTable);
3949
3950 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
3951
Andy McFaddend5ab7262009-08-25 07:19:34 -07003952#ifdef USE_INDIRECT_REF
3953 gcScanIndirectRefTable(&thread->jniLocalRefTable);
3954#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003955 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07003956#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003957
3958 if (thread->jniMonitorRefTable.table != NULL) {
3959 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
3960
3961 gcScanReferenceTable(&thread->jniMonitorRefTable);
3962 }
3963
3964 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
3965
3966 gcScanInterpStackReferences(thread);
3967
3968 HPROF_CLEAR_GC_SCAN_STATE();
3969}
3970
3971static void gcScanAllThreads()
3972{
3973 Thread *thread;
3974
3975 /* Lock the thread list so we can safely use the
3976 * next/prev pointers.
3977 */
3978 dvmLockThreadList(dvmThreadSelf());
3979
3980 for (thread = gDvm.threadList; thread != NULL;
3981 thread = thread->next)
3982 {
3983 /* We need to scan our own stack, so don't special-case
3984 * the current thread.
3985 */
3986 gcScanThread(thread);
3987 }
3988
3989 dvmUnlockThreadList();
3990}
3991
3992void dvmGcScanRootThreadGroups()
3993{
3994 /* We scan the VM's list of threads instead of going
3995 * through the actual ThreadGroups, but it should be
3996 * equivalent.
3997 *
Jeff Hao97319a82009-08-12 16:57:15 -07003998 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003999 * the root set, which should always be true; it's
4000 * loaded by the built-in class loader, which is part
4001 * of the root set.
4002 */
4003 gcScanAllThreads();
4004}