blob: 338c8b9332fc0d7f2a8ea9eaed3369a0864cfeaa [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);
723 // TODO: JIT can get stuck, dvmJitUnchainAll doesn't help?
724 }
Andy McFadden44860362009-08-06 17:56:14 -0700725 }
726
727 usleep(200 * 1000);
728 }
729 dvmUnlockThreadList();
730 }
731
732#if 0 /* bad things happen if they come out of JNI or "spuriously" wake up */
733 /*
734 * Abandon the threads and recover their resources.
735 */
736 target = gDvm.threadList;
737 while (target != NULL) {
738 Thread* nextTarget = target->next;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800739 unlinkThread(target);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800740 freeThread(target);
741 target = nextTarget;
742 }
Andy McFadden44860362009-08-06 17:56:14 -0700743#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800744
Andy McFadden44860362009-08-06 17:56:14 -0700745 //dvmDumpAllThreads(true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800746}
747
748
749/*
750 * Finish preparing the parts of the Thread struct required to support
751 * JNI registration.
752 */
753bool dvmPrepMainForJni(JNIEnv* pEnv)
754{
755 Thread* self;
756
757 /* main thread is always first in list at this point */
758 self = gDvm.threadList;
759 assert(self->threadId == kMainThreadId);
760
761 /* create a "fake" JNI frame at the top of the main thread interp stack */
762 if (!createFakeEntryFrame(self))
763 return false;
764
765 /* fill these in, since they weren't ready at dvmCreateJNIEnv time */
766 dvmSetJniEnvThreadId(pEnv, self);
767 dvmSetThreadJNIEnv(self, (JNIEnv*) pEnv);
768
769 return true;
770}
771
772
773/*
774 * Finish preparing the main thread, allocating some objects to represent
775 * it. As part of doing so, we finish initializing Thread and ThreadGroup.
Andy McFaddena1a7a342009-05-04 13:29:30 -0700776 * This will execute some interpreted code (e.g. class initializers).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800777 */
778bool dvmPrepMainThread(void)
779{
780 Thread* thread;
781 Object* groupObj;
782 Object* threadObj;
783 Object* vmThreadObj;
784 StringObject* threadNameStr;
785 Method* init;
786 JValue unused;
787
788 LOGV("+++ finishing prep on main VM thread\n");
789
790 /* main thread is always first in list at this point */
791 thread = gDvm.threadList;
792 assert(thread->threadId == kMainThreadId);
793
794 /*
795 * Make sure the classes are initialized. We have to do this before
796 * we create an instance of them.
797 */
798 if (!dvmInitClass(gDvm.classJavaLangClass)) {
799 LOGE("'Class' class failed to initialize\n");
800 return false;
801 }
802 if (!dvmInitClass(gDvm.classJavaLangThreadGroup) ||
803 !dvmInitClass(gDvm.classJavaLangThread) ||
804 !dvmInitClass(gDvm.classJavaLangVMThread))
805 {
806 LOGE("thread classes failed to initialize\n");
807 return false;
808 }
809
810 groupObj = dvmGetMainThreadGroup();
811 if (groupObj == NULL)
812 return false;
813
814 /*
815 * Allocate and construct a Thread with the internal-creation
816 * constructor.
817 */
818 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
819 if (threadObj == NULL) {
820 LOGE("unable to allocate main thread object\n");
821 return false;
822 }
823 dvmReleaseTrackedAlloc(threadObj, NULL);
824
825 threadNameStr = dvmCreateStringFromCstr("main", ALLOC_DEFAULT);
826 if (threadNameStr == NULL)
827 return false;
828 dvmReleaseTrackedAlloc((Object*)threadNameStr, NULL);
829
830 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
831 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
832 assert(init != NULL);
833 dvmCallMethod(thread, init, threadObj, &unused, groupObj, threadNameStr,
834 THREAD_NORM_PRIORITY, false);
835 if (dvmCheckException(thread)) {
836 LOGE("exception thrown while constructing main thread object\n");
837 return false;
838 }
839
840 /*
841 * Allocate and construct a VMThread.
842 */
843 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
844 if (vmThreadObj == NULL) {
845 LOGE("unable to allocate main vmthread object\n");
846 return false;
847 }
848 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
849
850 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangVMThread, "<init>",
851 "(Ljava/lang/Thread;)V");
852 dvmCallMethod(thread, init, vmThreadObj, &unused, threadObj);
853 if (dvmCheckException(thread)) {
854 LOGE("exception thrown while constructing main vmthread object\n");
855 return false;
856 }
857
858 /* set the VMThread.vmData field to our Thread struct */
859 assert(gDvm.offJavaLangVMThread_vmData != 0);
860 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)thread);
861
862 /*
863 * Stuff the VMThread back into the Thread. From this point on, other
Andy McFaddena1a7a342009-05-04 13:29:30 -0700864 * Threads will see that this Thread is running (at least, they would,
865 * if there were any).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800866 */
867 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread,
868 vmThreadObj);
869
870 thread->threadObj = threadObj;
871
872 /*
Andy McFaddena1a7a342009-05-04 13:29:30 -0700873 * Set the context class loader. This invokes a ClassLoader method,
874 * which could conceivably call Thread.currentThread(), so we want the
875 * Thread to be fully configured before we do this.
876 */
877 Object* systemLoader = dvmGetSystemClassLoader();
878 if (systemLoader == NULL) {
879 LOGW("WARNING: system class loader is NULL (setting main ctxt)\n");
880 /* keep going */
881 }
882 int ctxtClassLoaderOffset = dvmFindFieldOffset(gDvm.classJavaLangThread,
883 "contextClassLoader", "Ljava/lang/ClassLoader;");
884 if (ctxtClassLoaderOffset < 0) {
885 LOGE("Unable to find contextClassLoader field in Thread\n");
886 return false;
887 }
888 dvmSetFieldObject(threadObj, ctxtClassLoaderOffset, systemLoader);
889
890 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800891 * Finish our thread prep.
892 */
893
894 /* include self in non-daemon threads (mainly for AttachCurrentThread) */
895 gDvm.nonDaemonThreadCount++;
896
897 return true;
898}
899
900
901/*
902 * Alloc and initialize a Thread struct.
903 *
904 * "threadObj" is the java.lang.Thread object. It will be NULL for the
905 * main VM thread, but non-NULL for everything else.
906 *
907 * Does not create any objects, just stuff on the system (malloc) heap. (If
908 * this changes, we need to use ALLOC_NO_GC. And also verify that we're
909 * ready to load classes at the time this is called.)
910 */
911static Thread* allocThread(int interpStackSize)
912{
913 Thread* thread;
914 u1* stackBottom;
915
916 thread = (Thread*) calloc(1, sizeof(Thread));
917 if (thread == NULL)
918 return NULL;
919
Jeff Hao97319a82009-08-12 16:57:15 -0700920#if defined(WITH_SELF_VERIFICATION)
921 if (dvmSelfVerificationShadowSpaceAlloc(thread) == NULL)
922 return NULL;
923#endif
924
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800925 assert(interpStackSize >= kMinStackSize && interpStackSize <=kMaxStackSize);
926
927 thread->status = THREAD_INITIALIZING;
928 thread->suspendCount = 0;
929
930#ifdef WITH_ALLOC_LIMITS
931 thread->allocLimit = -1;
932#endif
933
934 /*
935 * Allocate and initialize the interpreted code stack. We essentially
936 * "lose" the alloc pointer, which points at the bottom of the stack,
937 * but we can get it back later because we know how big the stack is.
938 *
939 * The stack must be aligned on a 4-byte boundary.
940 */
941#ifdef MALLOC_INTERP_STACK
942 stackBottom = (u1*) malloc(interpStackSize);
943 if (stackBottom == NULL) {
Jeff Hao97319a82009-08-12 16:57:15 -0700944#if defined(WITH_SELF_VERIFICATION)
945 dvmSelfVerificationShadowSpaceFree(thread);
946#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800947 free(thread);
948 return NULL;
949 }
950 memset(stackBottom, 0xc5, interpStackSize); // stop valgrind complaints
951#else
952 stackBottom = mmap(NULL, interpStackSize, PROT_READ | PROT_WRITE,
953 MAP_PRIVATE | MAP_ANON, -1, 0);
954 if (stackBottom == MAP_FAILED) {
Jeff Hao97319a82009-08-12 16:57:15 -0700955#if defined(WITH_SELF_VERIFICATION)
956 dvmSelfVerificationShadowSpaceFree(thread);
957#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800958 free(thread);
959 return NULL;
960 }
961#endif
962
963 assert(((u4)stackBottom & 0x03) == 0); // looks like our malloc ensures this
964 thread->interpStackSize = interpStackSize;
965 thread->interpStackStart = stackBottom + interpStackSize;
966 thread->interpStackEnd = stackBottom + STACK_OVERFLOW_RESERVE;
967
968 /* give the thread code a chance to set things up */
969 dvmInitInterpStack(thread, interpStackSize);
970
971 return thread;
972}
973
974/*
975 * Get a meaningful thread ID. At present this only has meaning under Linux,
976 * where getpid() and gettid() sometimes agree and sometimes don't depending
977 * on your thread model (try "export LD_ASSUME_KERNEL=2.4.19").
978 */
979pid_t dvmGetSysThreadId(void)
980{
981#ifdef HAVE_GETTID
982 return gettid();
983#else
984 return getpid();
985#endif
986}
987
988/*
989 * Finish initialization of a Thread struct.
990 *
991 * This must be called while executing in the new thread, but before the
992 * thread is added to the thread list.
993 *
994 * *** NOTE: The threadListLock must be held by the caller (needed for
995 * assignThreadId()).
996 */
997static bool prepareThread(Thread* thread)
998{
999 assignThreadId(thread);
1000 thread->handle = pthread_self();
1001 thread->systemTid = dvmGetSysThreadId();
1002
1003 //LOGI("SYSTEM TID IS %d (pid is %d)\n", (int) thread->systemTid,
1004 // (int) getpid());
1005 setThreadSelf(thread);
1006
1007 LOGV("threadid=%d: interp stack at %p\n",
1008 thread->threadId, thread->interpStackStart - thread->interpStackSize);
1009
1010 /*
1011 * Initialize invokeReq.
1012 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001013 dvmInitMutex(&thread->invokeReq.lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001014 pthread_cond_init(&thread->invokeReq.cv, NULL);
1015
1016 /*
1017 * Initialize our reference tracking tables.
1018 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001019 * Most threads won't use jniMonitorRefTable, so we clear out the
1020 * structure but don't call the init function (which allocs storage).
1021 */
Andy McFaddend5ab7262009-08-25 07:19:34 -07001022#ifdef USE_INDIRECT_REF
1023 if (!dvmInitIndirectRefTable(&thread->jniLocalRefTable,
1024 kJniLocalRefMin, kJniLocalRefMax, kIndirectKindLocal))
1025 return false;
1026#else
1027 /*
1028 * The JNI local ref table *must* be fixed-size because we keep pointers
1029 * into the table in our stack frames.
1030 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001031 if (!dvmInitReferenceTable(&thread->jniLocalRefTable,
1032 kJniLocalRefMax, kJniLocalRefMax))
1033 return false;
Andy McFaddend5ab7262009-08-25 07:19:34 -07001034#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001035 if (!dvmInitReferenceTable(&thread->internalLocalRefTable,
1036 kInternalRefDefault, kInternalRefMax))
1037 return false;
1038
1039 memset(&thread->jniMonitorRefTable, 0, sizeof(thread->jniMonitorRefTable));
1040
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001041 pthread_cond_init(&thread->waitCond, NULL);
1042 dvmInitMutex(&thread->waitMutex);
1043
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001044 return true;
1045}
1046
1047/*
1048 * Remove a thread from the internal list.
1049 * Clear out the links to make it obvious that the thread is
1050 * no longer on the list. Caller must hold gDvm.threadListLock.
1051 */
1052static void unlinkThread(Thread* thread)
1053{
1054 LOG_THREAD("threadid=%d: removing from list\n", thread->threadId);
1055 if (thread == gDvm.threadList) {
1056 assert(thread->prev == NULL);
1057 gDvm.threadList = thread->next;
1058 } else {
1059 assert(thread->prev != NULL);
1060 thread->prev->next = thread->next;
1061 }
1062 if (thread->next != NULL)
1063 thread->next->prev = thread->prev;
1064 thread->prev = thread->next = NULL;
1065}
1066
1067/*
1068 * Free a Thread struct, and all the stuff allocated within.
1069 */
1070static void freeThread(Thread* thread)
1071{
1072 if (thread == NULL)
1073 return;
1074
1075 /* thread->threadId is zero at this point */
1076 LOGVV("threadid=%d: freeing\n", thread->threadId);
1077
1078 if (thread->interpStackStart != NULL) {
1079 u1* interpStackBottom;
1080
1081 interpStackBottom = thread->interpStackStart;
1082 interpStackBottom -= thread->interpStackSize;
1083#ifdef MALLOC_INTERP_STACK
1084 free(interpStackBottom);
1085#else
1086 if (munmap(interpStackBottom, thread->interpStackSize) != 0)
1087 LOGW("munmap(thread stack) failed\n");
1088#endif
1089 }
1090
Andy McFaddend5ab7262009-08-25 07:19:34 -07001091#ifdef USE_INDIRECT_REF
1092 dvmClearIndirectRefTable(&thread->jniLocalRefTable);
1093#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001094 dvmClearReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07001095#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001096 dvmClearReferenceTable(&thread->internalLocalRefTable);
1097 if (&thread->jniMonitorRefTable.table != NULL)
1098 dvmClearReferenceTable(&thread->jniMonitorRefTable);
1099
Jeff Hao97319a82009-08-12 16:57:15 -07001100#if defined(WITH_SELF_VERIFICATION)
1101 dvmSelfVerificationShadowSpaceFree(thread);
1102#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001103 free(thread);
1104}
1105
1106/*
1107 * Like pthread_self(), but on a Thread*.
1108 */
1109Thread* dvmThreadSelf(void)
1110{
1111 return (Thread*) pthread_getspecific(gDvm.pthreadKeySelf);
1112}
1113
1114/*
1115 * Explore our sense of self. Stuffs the thread pointer into TLS.
1116 */
1117static void setThreadSelf(Thread* thread)
1118{
1119 int cc;
1120
1121 cc = pthread_setspecific(gDvm.pthreadKeySelf, thread);
1122 if (cc != 0) {
1123 /*
1124 * Sometimes this fails under Bionic with EINVAL during shutdown.
1125 * This can happen if the timing is just right, e.g. a thread
1126 * fails to attach during shutdown, but the "fail" path calls
1127 * here to ensure we clean up after ourselves.
1128 */
1129 if (thread != NULL) {
1130 LOGE("pthread_setspecific(%p) failed, err=%d\n", thread, cc);
1131 dvmAbort(); /* the world is fundamentally hosed */
1132 }
1133 }
1134}
1135
1136/*
1137 * This is associated with the pthreadKeySelf key. It's called by the
1138 * pthread library when a thread is exiting and the "self" pointer in TLS
1139 * is non-NULL, meaning the VM hasn't had a chance to clean up. In normal
Andy McFadden909ce242009-12-10 16:38:30 -08001140 * operation this will not be called.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001141 *
1142 * This is mainly of use to ensure that we don't leak resources if, for
1143 * example, a thread attaches itself to us with AttachCurrentThread and
1144 * then exits without notifying the VM.
Andy McFadden34e25bb2009-04-15 13:27:12 -07001145 *
1146 * We could do the detach here instead of aborting, but this will lead to
1147 * portability problems. Other implementations do not do this check and
1148 * will simply be unaware that the thread has exited, leading to resource
1149 * leaks (and, if this is a non-daemon thread, an infinite hang when the
1150 * VM tries to shut down).
Andy McFadden909ce242009-12-10 16:38:30 -08001151 *
1152 * Because some implementations may want to use the pthread destructor
1153 * to initiate the detach, and the ordering of destructors is not defined,
1154 * 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 -08001155 */
1156static void threadExitCheck(void* arg)
1157{
Andy McFadden909ce242009-12-10 16:38:30 -08001158 const int kMaxCount = 2;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001159
Andy McFadden909ce242009-12-10 16:38:30 -08001160 Thread* self = (Thread*) arg;
1161 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001162
Andy McFadden909ce242009-12-10 16:38:30 -08001163 LOGV("threadid=%d: threadExitCheck(%p) count=%d\n",
1164 self->threadId, arg, self->threadExitCheckCount);
1165
1166 if (self->status == THREAD_ZOMBIE) {
1167 LOGW("threadid=%d: Weird -- shouldn't be in threadExitCheck\n",
1168 self->threadId);
1169 return;
1170 }
1171
1172 if (self->threadExitCheckCount < kMaxCount) {
1173 /*
1174 * Spin a couple of times to let other destructors fire.
1175 */
1176 LOGD("threadid=%d: thread exiting, not yet detached (count=%d)\n",
1177 self->threadId, self->threadExitCheckCount);
1178 self->threadExitCheckCount++;
1179 int cc = pthread_setspecific(gDvm.pthreadKeySelf, self);
1180 if (cc != 0) {
1181 LOGE("threadid=%d: unable to re-add thread to TLS\n",
1182 self->threadId);
1183 dvmAbort();
1184 }
1185 } else {
1186 LOGE("threadid=%d: native thread exited without detaching\n",
1187 self->threadId);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001188 dvmAbort();
1189 }
1190}
1191
1192
1193/*
1194 * Assign the threadId. This needs to be a small integer so that our
1195 * "thin" locks fit in a small number of bits.
1196 *
1197 * We reserve zero for use as an invalid ID.
1198 *
1199 * This must be called with threadListLock held (unless we're still
1200 * initializing the system).
1201 */
1202static void assignThreadId(Thread* thread)
1203{
Carl Shapiro59a93122010-01-26 17:12:51 -08001204 /*
1205 * Find a small unique integer. threadIdMap is a vector of
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001206 * kMaxThreadId bits; dvmAllocBit() returns the index of a
1207 * bit, meaning that it will always be < kMaxThreadId.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001208 */
1209 int num = dvmAllocBit(gDvm.threadIdMap);
1210 if (num < 0) {
1211 LOGE("Ran out of thread IDs\n");
1212 dvmAbort(); // TODO: make this a non-fatal error result
1213 }
1214
Carl Shapiro59a93122010-01-26 17:12:51 -08001215 thread->threadId = num + 1;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001216
1217 assert(thread->threadId != 0);
1218 assert(thread->threadId != DVM_LOCK_INITIAL_THIN_VALUE);
1219}
1220
1221/*
1222 * Give back the thread ID.
1223 */
1224static void releaseThreadId(Thread* thread)
1225{
1226 assert(thread->threadId > 0);
Carl Shapiro7eed8082010-01-28 16:12:44 -08001227 dvmClearBit(gDvm.threadIdMap, thread->threadId - 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001228 thread->threadId = 0;
1229}
1230
1231
1232/*
1233 * Add a stack frame that makes it look like the native code in the main
1234 * thread was originally invoked from interpreted code. This gives us a
1235 * place to hang JNI local references. The VM spec says (v2 5.2) that the
1236 * VM begins by executing "main" in a class, so in a way this brings us
1237 * closer to the spec.
1238 */
1239static bool createFakeEntryFrame(Thread* thread)
1240{
1241 assert(thread->threadId == kMainThreadId); // main thread only
1242
1243 /* find the method on first use */
1244 if (gDvm.methFakeNativeEntry == NULL) {
1245 ClassObject* nativeStart;
1246 Method* mainMeth;
1247
1248 nativeStart = dvmFindSystemClassNoInit(
1249 "Ldalvik/system/NativeStart;");
1250 if (nativeStart == NULL) {
1251 LOGE("Unable to find dalvik.system.NativeStart class\n");
1252 return false;
1253 }
1254
1255 /*
1256 * Because we are creating a frame that represents application code, we
1257 * want to stuff the application class loader into the method's class
1258 * loader field, even though we're using the system class loader to
1259 * load it. This makes life easier over in JNI FindClass (though it
1260 * could bite us in other ways).
1261 *
1262 * Unfortunately this is occurring too early in the initialization,
1263 * of necessity coming before JNI is initialized, and we're not quite
1264 * ready to set up the application class loader.
1265 *
1266 * So we save a pointer to the method in gDvm.methFakeNativeEntry
1267 * and check it in FindClass. The method is private so nobody else
1268 * can call it.
1269 */
1270 //nativeStart->classLoader = dvmGetSystemClassLoader();
1271
1272 mainMeth = dvmFindDirectMethodByDescriptor(nativeStart,
1273 "main", "([Ljava/lang/String;)V");
1274 if (mainMeth == NULL) {
1275 LOGE("Unable to find 'main' in dalvik.system.NativeStart\n");
1276 return false;
1277 }
1278
1279 gDvm.methFakeNativeEntry = mainMeth;
1280 }
1281
1282 return dvmPushJNIFrame(thread, gDvm.methFakeNativeEntry);
1283}
1284
1285
1286/*
1287 * Add a stack frame that makes it look like the native thread has been
1288 * executing interpreted code. This gives us a place to hang JNI local
1289 * references.
1290 */
1291static bool createFakeRunFrame(Thread* thread)
1292{
1293 ClassObject* nativeStart;
1294 Method* runMeth;
1295
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001296 nativeStart =
1297 dvmFindSystemClassNoInit("Ldalvik/system/NativeStart;");
1298 if (nativeStart == NULL) {
1299 LOGE("Unable to find dalvik.system.NativeStart class\n");
1300 return false;
1301 }
1302
1303 runMeth = dvmFindVirtualMethodByDescriptor(nativeStart, "run", "()V");
1304 if (runMeth == NULL) {
1305 LOGE("Unable to find 'run' in dalvik.system.NativeStart\n");
1306 return false;
1307 }
1308
1309 return dvmPushJNIFrame(thread, runMeth);
1310}
1311
1312/*
1313 * Helper function to set the name of the current thread
1314 */
1315static void setThreadName(const char *threadName)
1316{
1317#if defined(HAVE_PRCTL)
1318 int hasAt = 0;
1319 int hasDot = 0;
1320 const char *s = threadName;
1321 while (*s) {
1322 if (*s == '.') hasDot = 1;
1323 else if (*s == '@') hasAt = 1;
1324 s++;
1325 }
1326 int len = s - threadName;
1327 if (len < 15 || hasAt || !hasDot) {
1328 s = threadName;
1329 } else {
1330 s = threadName + len - 15;
1331 }
1332 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
1333#endif
1334}
1335
1336/*
1337 * Create a thread as a result of java.lang.Thread.start().
1338 *
1339 * We do have to worry about some concurrency problems, e.g. programs
1340 * that try to call Thread.start() on the same object from multiple threads.
1341 * (This will fail for all but one, but we have to make sure that it succeeds
1342 * for exactly one.)
1343 *
1344 * Some of the complexity here arises from our desire to mimic the
1345 * Thread vs. VMThread class decomposition we inherited. We've been given
1346 * a Thread, and now we need to create a VMThread and then populate both
1347 * objects. We also need to create one of our internal Thread objects.
1348 *
1349 * Pass in a stack size of 0 to get the default.
1350 */
1351bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
1352{
1353 pthread_attr_t threadAttr;
1354 pthread_t threadHandle;
1355 Thread* self;
1356 Thread* newThread = NULL;
1357 Object* vmThreadObj = NULL;
1358 int stackSize;
1359
1360 assert(threadObj != NULL);
1361
1362 if(gDvm.zygote) {
Bob Lee9dc72a32009-09-04 18:28:16 -07001363 // Allow the sampling profiler thread. We shut it down before forking.
1364 StringObject* nameStr = (StringObject*) dvmGetFieldObject(threadObj,
1365 gDvm.offJavaLangThread_name);
1366 char* threadName = dvmCreateCstrFromString(nameStr);
1367 bool profilerThread = strcmp(threadName, "SamplingProfiler") == 0;
1368 free(threadName);
1369 if (!profilerThread) {
1370 dvmThrowException("Ljava/lang/IllegalStateException;",
1371 "No new threads in -Xzygote mode");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001372
Bob Lee9dc72a32009-09-04 18:28:16 -07001373 goto fail;
1374 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001375 }
1376
1377 self = dvmThreadSelf();
1378 if (reqStackSize == 0)
1379 stackSize = gDvm.stackSize;
1380 else if (reqStackSize < kMinStackSize)
1381 stackSize = kMinStackSize;
1382 else if (reqStackSize > kMaxStackSize)
1383 stackSize = kMaxStackSize;
1384 else
1385 stackSize = reqStackSize;
1386
1387 pthread_attr_init(&threadAttr);
1388 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1389
1390 /*
1391 * To minimize the time spent in the critical section, we allocate the
1392 * vmThread object here.
1393 */
1394 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
1395 if (vmThreadObj == NULL)
1396 goto fail;
1397
1398 newThread = allocThread(stackSize);
1399 if (newThread == NULL)
1400 goto fail;
1401 newThread->threadObj = threadObj;
1402
1403 assert(newThread->status == THREAD_INITIALIZING);
1404
1405 /*
1406 * We need to lock out other threads while we test and set the
1407 * "vmThread" field in java.lang.Thread, because we use that to determine
1408 * if this thread has been started before. We use the thread list lock
1409 * because it's handy and we're going to need to grab it again soon
1410 * anyway.
1411 */
1412 dvmLockThreadList(self);
1413
1414 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
1415 dvmUnlockThreadList();
1416 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
1417 "thread has already been started");
1418 goto fail;
1419 }
1420
1421 /*
1422 * There are actually three data structures: Thread (object), VMThread
1423 * (object), and Thread (C struct). All of them point to at least one
1424 * other.
1425 *
1426 * As soon as "VMThread.vmData" is assigned, other threads can start
1427 * making calls into us (e.g. setPriority).
1428 */
1429 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)newThread);
1430 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
1431
1432 /*
1433 * Thread creation might take a while, so release the lock.
1434 */
1435 dvmUnlockThreadList();
1436
Andy McFadden2aa43612009-06-17 16:29:30 -07001437 int cc, oldStatus;
1438 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1439 cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart,
1440 newThread);
1441 oldStatus = dvmChangeStatus(self, oldStatus);
1442
1443 if (cc != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001444 /*
1445 * Failure generally indicates that we have exceeded system
1446 * resource limits. VirtualMachineError is probably too severe,
1447 * so use OutOfMemoryError.
1448 */
1449 LOGE("Thread creation failed (err=%s)\n", strerror(errno));
1450
1451 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, NULL);
1452
1453 dvmThrowException("Ljava/lang/OutOfMemoryError;",
1454 "thread creation failed");
1455 goto fail;
1456 }
1457
1458 /*
1459 * We need to wait for the thread to start. Otherwise, depending on
1460 * the whims of the OS scheduler, we could return and the code in our
1461 * thread could try to do operations on the new thread before it had
1462 * finished starting.
1463 *
1464 * The new thread will lock the thread list, change its state to
1465 * THREAD_STARTING, broadcast to gDvm.threadStartCond, and then sleep
1466 * on gDvm.threadStartCond (which uses the thread list lock). This
1467 * thread (the parent) will either see that the thread is already ready
1468 * after we grab the thread list lock, or will be awakened from the
1469 * condition variable on the broadcast.
1470 *
1471 * We don't want to stall the rest of the VM while the new thread
1472 * starts, which can happen if the GC wakes up at the wrong moment.
1473 * So, we change our own status to VMWAIT, and self-suspend if
1474 * necessary after we finish adding the new thread.
1475 *
1476 *
1477 * We have to deal with an odd race with the GC/debugger suspension
1478 * mechanism when creating a new thread. The information about whether
1479 * or not a thread should be suspended is contained entirely within
1480 * the Thread struct; this is usually cleaner to deal with than having
1481 * one or more globally-visible suspension flags. The trouble is that
1482 * we could create the thread while the VM is trying to suspend all
1483 * threads. The suspend-count won't be nonzero for the new thread,
1484 * so dvmChangeStatus(THREAD_RUNNING) won't cause a suspension.
1485 *
1486 * The easiest way to deal with this is to prevent the new thread from
1487 * running until the parent says it's okay. This results in the
Andy McFadden2aa43612009-06-17 16:29:30 -07001488 * following (correct) sequence of events for a "badly timed" GC
1489 * (where '-' is us, 'o' is the child, and '+' is some other thread):
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001490 *
1491 * - call pthread_create()
1492 * - lock thread list
1493 * - put self into THREAD_VMWAIT so GC doesn't wait for us
1494 * - sleep on condition var (mutex = thread list lock) until child starts
1495 * + GC triggered by another thread
1496 * + thread list locked; suspend counts updated; thread list unlocked
1497 * + loop waiting for all runnable threads to suspend
1498 * + success, start GC
1499 * o child thread wakes, signals condition var to wake parent
1500 * o child waits for parent ack on condition variable
1501 * - we wake up, locking thread list
1502 * - add child to thread list
1503 * - unlock thread list
1504 * - change our state back to THREAD_RUNNING; GC causes us to suspend
1505 * + GC finishes; all threads in thread list are resumed
1506 * - lock thread list
1507 * - set child to THREAD_VMWAIT, and signal it to start
1508 * - unlock thread list
1509 * o child resumes
1510 * o child changes state to THREAD_RUNNING
1511 *
1512 * The above shows the GC starting up during thread creation, but if
1513 * it starts anywhere after VMThread.create() is called it will
1514 * produce the same series of events.
1515 *
1516 * Once the child is in the thread list, it will be suspended and
1517 * resumed like any other thread. In the above scenario the resume-all
1518 * code will try to resume the new thread, which was never actually
1519 * suspended, and try to decrement the child's thread suspend count to -1.
1520 * We can catch this in the resume-all code.
1521 *
1522 * Bouncing back and forth between threads like this adds a small amount
1523 * of scheduler overhead to thread startup.
1524 *
1525 * One alternative to having the child wait for the parent would be
1526 * to have the child inherit the parents' suspension count. This
1527 * would work for a GC, since we can safely assume that the parent
1528 * thread didn't cause it, but we must only do so if the parent suspension
1529 * was caused by a suspend-all. If the parent was being asked to
1530 * suspend singly by the debugger, the child should not inherit the value.
1531 *
1532 * We could also have a global "new thread suspend count" that gets
1533 * picked up by new threads before changing state to THREAD_RUNNING.
1534 * This would be protected by the thread list lock and set by a
1535 * suspend-all.
1536 */
1537 dvmLockThreadList(self);
1538 assert(self->status == THREAD_RUNNING);
1539 self->status = THREAD_VMWAIT;
1540 while (newThread->status != THREAD_STARTING)
1541 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1542
1543 LOG_THREAD("threadid=%d: adding to list\n", newThread->threadId);
1544 newThread->next = gDvm.threadList->next;
1545 if (newThread->next != NULL)
1546 newThread->next->prev = newThread;
1547 newThread->prev = gDvm.threadList;
1548 gDvm.threadList->next = newThread;
1549
1550 if (!dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon))
1551 gDvm.nonDaemonThreadCount++; // guarded by thread list lock
1552
1553 dvmUnlockThreadList();
1554
1555 /* change status back to RUNNING, self-suspending if necessary */
1556 dvmChangeStatus(self, THREAD_RUNNING);
1557
1558 /*
1559 * Tell the new thread to start.
1560 *
1561 * We must hold the thread list lock before messing with another thread.
1562 * In the general case we would also need to verify that newThread was
1563 * still in the thread list, but in our case the thread has not started
1564 * executing user code and therefore has not had a chance to exit.
1565 *
1566 * We move it to VMWAIT, and it then shifts itself to RUNNING, which
1567 * comes with a suspend-pending check.
1568 */
1569 dvmLockThreadList(self);
1570
1571 assert(newThread->status == THREAD_STARTING);
1572 newThread->status = THREAD_VMWAIT;
1573 pthread_cond_broadcast(&gDvm.threadStartCond);
1574
1575 dvmUnlockThreadList();
1576
1577 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1578 return true;
1579
1580fail:
1581 freeThread(newThread);
1582 dvmReleaseTrackedAlloc(vmThreadObj, NULL);
1583 return false;
1584}
1585
1586/*
1587 * pthread entry function for threads started from interpreted code.
1588 */
1589static void* interpThreadStart(void* arg)
1590{
1591 Thread* self = (Thread*) arg;
1592
1593 char *threadName = dvmGetThreadName(self);
1594 setThreadName(threadName);
1595 free(threadName);
1596
1597 /*
1598 * Finish initializing the Thread struct.
1599 */
1600 prepareThread(self);
1601
1602 LOG_THREAD("threadid=%d: created from interp\n", self->threadId);
1603
1604 /*
1605 * Change our status and wake our parent, who will add us to the
1606 * thread list and advance our state to VMWAIT.
1607 */
1608 dvmLockThreadList(self);
1609 self->status = THREAD_STARTING;
1610 pthread_cond_broadcast(&gDvm.threadStartCond);
1611
1612 /*
1613 * Wait until the parent says we can go. Assuming there wasn't a
1614 * suspend pending, this will happen immediately. When it completes,
1615 * we're full-fledged citizens of the VM.
1616 *
1617 * We have to use THREAD_VMWAIT here rather than THREAD_RUNNING
1618 * because the pthread_cond_wait below needs to reacquire a lock that
1619 * suspend-all is also interested in. If we get unlucky, the parent could
1620 * change us to THREAD_RUNNING, then a GC could start before we get
1621 * signaled, and suspend-all will grab the thread list lock and then
1622 * wait for us to suspend. We'll be in the tail end of pthread_cond_wait
1623 * trying to get the lock.
1624 */
1625 while (self->status != THREAD_VMWAIT)
1626 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1627
1628 dvmUnlockThreadList();
1629
1630 /*
1631 * Add a JNI context.
1632 */
1633 self->jniEnv = dvmCreateJNIEnv(self);
1634
1635 /*
1636 * Change our state so the GC will wait for us from now on. If a GC is
1637 * in progress this call will suspend us.
1638 */
1639 dvmChangeStatus(self, THREAD_RUNNING);
1640
1641 /*
1642 * Notify the debugger & DDM. The debugger notification may cause
1643 * us to suspend ourselves (and others).
1644 */
1645 if (gDvm.debuggerConnected)
1646 dvmDbgPostThreadStart(self);
1647
1648 /*
1649 * Set the system thread priority according to the Thread object's
1650 * priority level. We don't usually need to do this, because both the
1651 * Thread object and system thread priorities inherit from parents. The
1652 * tricky case is when somebody creates a Thread object, calls
1653 * setPriority(), and then starts the thread. We could manage this with
1654 * a "needs priority update" flag to avoid the redundant call.
1655 */
Andy McFadden4879df92009-08-07 14:49:40 -07001656 int priority = dvmGetFieldInt(self->threadObj,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001657 gDvm.offJavaLangThread_priority);
1658 dvmChangeThreadPriority(self, priority);
1659
1660 /*
1661 * Execute the "run" method.
1662 *
1663 * At this point our stack is empty, so somebody who comes looking for
1664 * stack traces right now won't have much to look at. This is normal.
1665 */
1666 Method* run = self->threadObj->clazz->vtable[gDvm.voffJavaLangThread_run];
1667 JValue unused;
1668
1669 LOGV("threadid=%d: calling run()\n", self->threadId);
1670 assert(strcmp(run->name, "run") == 0);
1671 dvmCallMethod(self, run, self->threadObj, &unused);
1672 LOGV("threadid=%d: exiting\n", self->threadId);
1673
1674 /*
1675 * Remove the thread from various lists, report its death, and free
1676 * its resources.
1677 */
1678 dvmDetachCurrentThread();
1679
1680 return NULL;
1681}
1682
1683/*
1684 * The current thread is exiting with an uncaught exception. The
1685 * Java programming language allows the application to provide a
1686 * thread-exit-uncaught-exception handler for the VM, for a specific
1687 * Thread, and for all threads in a ThreadGroup.
1688 *
1689 * Version 1.5 added the per-thread handler. We need to call
1690 * "uncaughtException" in the handler object, which is either the
1691 * ThreadGroup object or the Thread-specific handler.
1692 */
1693static void threadExitUncaughtException(Thread* self, Object* group)
1694{
1695 Object* exception;
1696 Object* handlerObj;
1697 ClassObject* throwable;
1698 Method* uncaughtHandler = NULL;
1699 InstField* threadHandler;
1700
1701 LOGW("threadid=%d: thread exiting with uncaught exception (group=%p)\n",
1702 self->threadId, group);
1703 assert(group != NULL);
1704
1705 /*
1706 * Get a pointer to the exception, then clear out the one in the
1707 * thread. We don't want to have it set when executing interpreted code.
1708 */
1709 exception = dvmGetException(self);
1710 dvmAddTrackedAlloc(exception, self);
1711 dvmClearException(self);
1712
1713 /*
1714 * Get the Thread's "uncaughtHandler" object. Use it if non-NULL;
1715 * else use "group" (which is an instance of UncaughtExceptionHandler).
1716 */
1717 threadHandler = dvmFindInstanceField(gDvm.classJavaLangThread,
1718 "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
1719 if (threadHandler == NULL) {
1720 LOGW("WARNING: no 'uncaughtHandler' field in java/lang/Thread\n");
1721 goto bail;
1722 }
1723 handlerObj = dvmGetFieldObject(self->threadObj, threadHandler->byteOffset);
1724 if (handlerObj == NULL)
1725 handlerObj = group;
1726
1727 /*
1728 * Find the "uncaughtHandler" field in this object.
1729 */
1730 uncaughtHandler = dvmFindVirtualMethodHierByDescriptor(handlerObj->clazz,
1731 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
1732
1733 if (uncaughtHandler != NULL) {
1734 //LOGI("+++ calling %s.uncaughtException\n",
1735 // handlerObj->clazz->descriptor);
1736 JValue unused;
1737 dvmCallMethod(self, uncaughtHandler, handlerObj, &unused,
1738 self->threadObj, exception);
1739 } else {
1740 /* restore it and dump a stack trace */
1741 LOGW("WARNING: no 'uncaughtException' method in class %s\n",
1742 handlerObj->clazz->descriptor);
1743 dvmSetException(self, exception);
1744 dvmLogExceptionStackTrace();
1745 }
1746
1747bail:
Bill Buzbee46cd5b62009-06-05 15:36:06 -07001748#if defined(WITH_JIT)
1749 /* Remove this thread's suspendCount from global suspendCount sum */
1750 lockThreadSuspendCount();
1751 dvmAddToThreadSuspendCount(&self->suspendCount, -self->suspendCount);
1752 unlockThreadSuspendCount();
1753#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001754 dvmReleaseTrackedAlloc(exception, self);
1755}
1756
1757
1758/*
1759 * Create an internal VM thread, for things like JDWP and finalizers.
1760 *
1761 * The easiest way to do this is create a new thread and then use the
1762 * JNI AttachCurrentThread implementation.
1763 *
1764 * This does not return until after the new thread has begun executing.
1765 */
1766bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
1767 InternalThreadStart func, void* funcArg)
1768{
1769 InternalStartArgs* pArgs;
1770 Object* systemGroup;
1771 pthread_attr_t threadAttr;
1772 volatile Thread* newThread = NULL;
1773 volatile int createStatus = 0;
1774
1775 systemGroup = dvmGetSystemThreadGroup();
1776 if (systemGroup == NULL)
1777 return false;
1778
1779 pArgs = (InternalStartArgs*) malloc(sizeof(*pArgs));
1780 pArgs->func = func;
1781 pArgs->funcArg = funcArg;
1782 pArgs->name = strdup(name); // storage will be owned by new thread
1783 pArgs->group = systemGroup;
1784 pArgs->isDaemon = true;
1785 pArgs->pThread = &newThread;
1786 pArgs->pCreateStatus = &createStatus;
1787
1788 pthread_attr_init(&threadAttr);
1789 //pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
1790
1791 if (pthread_create(pHandle, &threadAttr, internalThreadStart,
1792 pArgs) != 0)
1793 {
1794 LOGE("internal thread creation failed\n");
1795 free(pArgs->name);
1796 free(pArgs);
1797 return false;
1798 }
1799
1800 /*
1801 * Wait for the child to start. This gives us an opportunity to make
1802 * sure that the thread started correctly, and allows our caller to
1803 * assume that the thread has started running.
1804 *
1805 * Because we aren't holding a lock across the thread creation, it's
1806 * possible that the child will already have completed its
1807 * initialization. Because the child only adjusts "createStatus" while
1808 * holding the thread list lock, the initial condition on the "while"
1809 * loop will correctly avoid the wait if this occurs.
1810 *
1811 * It's also possible that we'll have to wait for the thread to finish
1812 * being created, and as part of allocating a Thread object it might
1813 * need to initiate a GC. We switch to VMWAIT while we pause.
1814 */
1815 Thread* self = dvmThreadSelf();
1816 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
1817 dvmLockThreadList(self);
1818 while (createStatus == 0)
1819 pthread_cond_wait(&gDvm.threadStartCond, &gDvm.threadListLock);
1820
1821 if (newThread == NULL) {
1822 LOGW("internal thread create failed (createStatus=%d)\n", createStatus);
1823 assert(createStatus < 0);
1824 /* don't free pArgs -- if pthread_create succeeded, child owns it */
1825 dvmUnlockThreadList();
1826 dvmChangeStatus(self, oldStatus);
1827 return false;
1828 }
1829
1830 /* thread could be in any state now (except early init states) */
1831 //assert(newThread->status == THREAD_RUNNING);
1832
1833 dvmUnlockThreadList();
1834 dvmChangeStatus(self, oldStatus);
1835
1836 return true;
1837}
1838
1839/*
1840 * pthread entry function for internally-created threads.
1841 *
1842 * We are expected to free "arg" and its contents. If we're a daemon
1843 * thread, and we get cancelled abruptly when the VM shuts down, the
1844 * storage won't be freed. If this becomes a concern we can make a copy
1845 * on the stack.
1846 */
1847static void* internalThreadStart(void* arg)
1848{
1849 InternalStartArgs* pArgs = (InternalStartArgs*) arg;
1850 JavaVMAttachArgs jniArgs;
1851
1852 jniArgs.version = JNI_VERSION_1_2;
1853 jniArgs.name = pArgs->name;
1854 jniArgs.group = pArgs->group;
1855
1856 setThreadName(pArgs->name);
1857
1858 /* use local jniArgs as stack top */
1859 if (dvmAttachCurrentThread(&jniArgs, pArgs->isDaemon)) {
1860 /*
1861 * Tell the parent of our success.
1862 *
1863 * threadListLock is the mutex for threadStartCond.
1864 */
1865 dvmLockThreadList(dvmThreadSelf());
1866 *pArgs->pCreateStatus = 1;
1867 *pArgs->pThread = dvmThreadSelf();
1868 pthread_cond_broadcast(&gDvm.threadStartCond);
1869 dvmUnlockThreadList();
1870
1871 LOG_THREAD("threadid=%d: internal '%s'\n",
1872 dvmThreadSelf()->threadId, pArgs->name);
1873
1874 /* execute */
1875 (*pArgs->func)(pArgs->funcArg);
1876
1877 /* detach ourselves */
1878 dvmDetachCurrentThread();
1879 } else {
1880 /*
1881 * Tell the parent of our failure. We don't have a Thread struct,
1882 * so we can't be suspended, so we don't need to enter a critical
1883 * section.
1884 */
1885 dvmLockThreadList(dvmThreadSelf());
1886 *pArgs->pCreateStatus = -1;
1887 assert(*pArgs->pThread == NULL);
1888 pthread_cond_broadcast(&gDvm.threadStartCond);
1889 dvmUnlockThreadList();
1890
1891 assert(*pArgs->pThread == NULL);
1892 }
1893
1894 free(pArgs->name);
1895 free(pArgs);
1896 return NULL;
1897}
1898
1899/*
1900 * Attach the current thread to the VM.
1901 *
1902 * Used for internally-created threads and JNI's AttachCurrentThread.
1903 */
1904bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
1905{
1906 Thread* self = NULL;
1907 Object* threadObj = NULL;
1908 Object* vmThreadObj = NULL;
1909 StringObject* threadNameStr = NULL;
1910 Method* init;
1911 bool ok, ret;
1912
1913 /* establish a basic sense of self */
1914 self = allocThread(gDvm.stackSize);
1915 if (self == NULL)
1916 goto fail;
1917 setThreadSelf(self);
1918
1919 /*
1920 * Create Thread and VMThread objects. We have to use ALLOC_NO_GC
1921 * because this thread is not yet visible to the VM. We could also
1922 * just grab the GC lock earlier, but that leaves us executing
1923 * interpreted code with the lock held, which is not prudent.
1924 *
1925 * The alloc calls will block if a GC is in progress, so we don't need
1926 * to check for global suspension here.
1927 *
1928 * It's also possible for the allocation calls to *cause* a GC.
1929 */
1930 //BUG: deadlock if a GC happens here during HeapWorker creation
1931 threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_NO_GC);
1932 if (threadObj == NULL)
1933 goto fail;
1934 vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_NO_GC);
1935 if (vmThreadObj == NULL)
1936 goto fail;
1937
1938 self->threadObj = threadObj;
1939 dvmSetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData, (u4)self);
1940
1941 /*
1942 * Do some java.lang.Thread constructor prep before we lock stuff down.
1943 */
1944 if (pArgs->name != NULL) {
1945 threadNameStr = dvmCreateStringFromCstr(pArgs->name, ALLOC_NO_GC);
1946 if (threadNameStr == NULL) {
1947 assert(dvmCheckException(dvmThreadSelf()));
1948 goto fail;
1949 }
1950 }
1951
1952 init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangThread, "<init>",
1953 "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
1954 if (init == NULL) {
1955 assert(dvmCheckException(dvmThreadSelf()));
1956 goto fail;
1957 }
1958
1959 /*
1960 * Finish our thread prep. We need to do this before invoking any
1961 * interpreted code. prepareThread() requires that we hold the thread
1962 * list lock.
1963 */
1964 dvmLockThreadList(self);
1965 ok = prepareThread(self);
1966 dvmUnlockThreadList();
1967 if (!ok)
1968 goto fail;
1969
1970 self->jniEnv = dvmCreateJNIEnv(self);
1971 if (self->jniEnv == NULL)
1972 goto fail;
1973
1974 /*
1975 * Create a "fake" JNI frame at the top of the main thread interp stack.
1976 * It isn't really necessary for the internal threads, but it gives
1977 * the debugger something to show. It is essential for the JNI-attached
1978 * threads.
1979 */
1980 if (!createFakeRunFrame(self))
1981 goto fail;
1982
1983 /*
1984 * The native side of the thread is ready; add it to the list.
1985 */
1986 LOG_THREAD("threadid=%d: adding to list (attached)\n", self->threadId);
1987
1988 /* Start off in VMWAIT, because we may be about to block
1989 * on the heap lock, and we don't want any suspensions
1990 * to wait for us.
1991 */
1992 self->status = THREAD_VMWAIT;
1993
1994 /*
1995 * Add ourselves to the thread list. Once we finish here we are
1996 * visible to the debugger and the GC.
1997 */
1998 dvmLockThreadList(self);
1999
2000 self->next = gDvm.threadList->next;
2001 if (self->next != NULL)
2002 self->next->prev = self;
2003 self->prev = gDvm.threadList;
2004 gDvm.threadList->next = self;
2005 if (!isDaemon)
2006 gDvm.nonDaemonThreadCount++;
2007
2008 dvmUnlockThreadList();
2009
2010 /*
2011 * It's possible that a GC is currently running. Our thread
2012 * wasn't in the list when the GC started, so it's not properly
2013 * suspended in that case. Synchronize on the heap lock (held
2014 * when a GC is happening) to guarantee that any GCs from here
2015 * on will see this thread in the list.
2016 */
2017 dvmLockMutex(&gDvm.gcHeapLock);
2018 dvmUnlockMutex(&gDvm.gcHeapLock);
2019
2020 /*
2021 * Switch to the running state now that we're ready for
2022 * suspensions. This call may suspend.
2023 */
2024 dvmChangeStatus(self, THREAD_RUNNING);
2025
2026 /*
2027 * Now we're ready to run some interpreted code.
2028 *
2029 * We need to construct the Thread object and set the VMThread field.
2030 * Setting VMThread tells interpreted code that we're alive.
2031 *
2032 * Call the (group, name, priority, daemon) constructor on the Thread.
2033 * This sets the thread's name and adds it to the specified group, and
2034 * provides values for priority and daemon (which are normally inherited
2035 * from the current thread).
2036 */
2037 JValue unused;
2038 dvmCallMethod(self, init, threadObj, &unused, (Object*)pArgs->group,
2039 threadNameStr, getThreadPriorityFromSystem(), isDaemon);
2040 if (dvmCheckException(self)) {
2041 LOGE("exception thrown while constructing attached thread object\n");
2042 goto fail_unlink;
2043 }
2044 //if (isDaemon)
2045 // dvmSetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon, true);
2046
2047 /*
2048 * Set the VMThread field, which tells interpreted code that we're alive.
2049 *
2050 * The risk of a thread start collision here is very low; somebody
2051 * would have to be deliberately polling the ThreadGroup list and
2052 * trying to start threads against anything it sees, which would
2053 * generally cause problems for all thread creation. However, for
2054 * correctness we test "vmThread" before setting it.
2055 */
2056 if (dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread) != NULL) {
2057 dvmThrowException("Ljava/lang/IllegalThreadStateException;",
2058 "thread has already been started");
2059 /* We don't want to free anything associated with the thread
2060 * because someone is obviously interested in it. Just let
2061 * it go and hope it will clean itself up when its finished.
2062 * This case should never happen anyway.
2063 *
2064 * Since we're letting it live, we need to finish setting it up.
2065 * We just have to let the caller know that the intended operation
2066 * has failed.
2067 *
2068 * [ This seems strange -- stepping on the vmThread object that's
2069 * already present seems like a bad idea. TODO: figure this out. ]
2070 */
2071 ret = false;
2072 } else
2073 ret = true;
2074 dvmSetFieldObject(threadObj, gDvm.offJavaLangThread_vmThread, vmThreadObj);
2075
2076 /* These are now reachable from the thread groups. */
2077 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
2078 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
2079
2080 /*
2081 * The thread is ready to go; let the debugger see it.
2082 */
2083 self->threadObj = threadObj;
2084
2085 LOG_THREAD("threadid=%d: attached from native, name=%s\n",
2086 self->threadId, pArgs->name);
2087
2088 /* tell the debugger & DDM */
2089 if (gDvm.debuggerConnected)
2090 dvmDbgPostThreadStart(self);
2091
2092 return ret;
2093
2094fail_unlink:
2095 dvmLockThreadList(self);
2096 unlinkThread(self);
2097 if (!isDaemon)
2098 gDvm.nonDaemonThreadCount--;
2099 dvmUnlockThreadList();
2100 /* fall through to "fail" */
2101fail:
2102 dvmClearAllocFlags(threadObj, ALLOC_NO_GC);
2103 dvmClearAllocFlags(vmThreadObj, ALLOC_NO_GC);
2104 if (self != NULL) {
2105 if (self->jniEnv != NULL) {
2106 dvmDestroyJNIEnv(self->jniEnv);
2107 self->jniEnv = NULL;
2108 }
2109 freeThread(self);
2110 }
2111 setThreadSelf(NULL);
2112 return false;
2113}
2114
2115/*
2116 * Detach the thread from the various data structures, notify other threads
2117 * that are waiting to "join" it, and free up all heap-allocated storage.
2118 *
2119 * Used for all threads.
2120 *
2121 * When we get here the interpreted stack should be empty. The JNI 1.6 spec
2122 * requires us to enforce this for the DetachCurrentThread call, probably
2123 * because it also says that DetachCurrentThread causes all monitors
2124 * associated with the thread to be released. (Because the stack is empty,
2125 * we only have to worry about explicit JNI calls to MonitorEnter.)
2126 *
2127 * THOUGHT:
2128 * We might want to avoid freeing our internal Thread structure until the
2129 * associated Thread/VMThread objects get GCed. Our Thread is impossible to
2130 * get to once the thread shuts down, but there is a small possibility of
2131 * an operation starting in another thread before this thread halts, and
2132 * finishing much later (perhaps the thread got stalled by a weird OS bug).
2133 * We don't want something like Thread.isInterrupted() crawling through
2134 * freed storage. Can do with a Thread finalizer, or by creating a
2135 * dedicated ThreadObject class for java/lang/Thread and moving all of our
2136 * state into that.
2137 */
2138void dvmDetachCurrentThread(void)
2139{
2140 Thread* self = dvmThreadSelf();
2141 Object* vmThread;
2142 Object* group;
2143
2144 /*
2145 * Make sure we're not detaching a thread that's still running. (This
2146 * could happen with an explicit JNI detach call.)
2147 *
2148 * A thread created by interpreted code will finish with a depth of
2149 * zero, while a JNI-attached thread will have the synthetic "stack
2150 * starter" native method at the top.
2151 */
2152 int curDepth = dvmComputeExactFrameDepth(self->curFrame);
2153 if (curDepth != 0) {
2154 bool topIsNative = false;
2155
2156 if (curDepth == 1) {
2157 /* not expecting a lingering break frame; just look at curFrame */
2158 assert(!dvmIsBreakFrame(self->curFrame));
2159 StackSaveArea* ssa = SAVEAREA_FROM_FP(self->curFrame);
2160 if (dvmIsNativeMethod(ssa->method))
2161 topIsNative = true;
2162 }
2163
2164 if (!topIsNative) {
2165 LOGE("ERROR: detaching thread with interp frames (count=%d)\n",
2166 curDepth);
2167 dvmDumpThread(self, false);
2168 dvmAbort();
2169 }
2170 }
2171
2172 group = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_group);
2173 LOG_THREAD("threadid=%d: detach (group=%p)\n", self->threadId, group);
2174
2175 /*
2176 * Release any held monitors. Since there are no interpreted stack
2177 * frames, the only thing left are the monitors held by JNI MonitorEnter
2178 * calls.
2179 */
2180 dvmReleaseJniMonitors(self);
2181
2182 /*
2183 * Do some thread-exit uncaught exception processing if necessary.
2184 */
2185 if (dvmCheckException(self))
2186 threadExitUncaughtException(self, group);
2187
2188 /*
2189 * Remove the thread from the thread group.
2190 */
2191 if (group != NULL) {
2192 Method* removeThread =
2193 group->clazz->vtable[gDvm.voffJavaLangThreadGroup_removeThread];
2194 JValue unused;
2195 dvmCallMethod(self, removeThread, group, &unused, self->threadObj);
2196 }
2197
2198 /*
2199 * Clear the vmThread reference in the Thread object. Interpreted code
2200 * will now see that this Thread is not running. As this may be the
2201 * only reference to the VMThread object that the VM knows about, we
2202 * have to create an internal reference to it first.
2203 */
2204 vmThread = dvmGetFieldObject(self->threadObj,
2205 gDvm.offJavaLangThread_vmThread);
2206 dvmAddTrackedAlloc(vmThread, self);
2207 dvmSetFieldObject(self->threadObj, gDvm.offJavaLangThread_vmThread, NULL);
2208
2209 /* clear out our struct Thread pointer, since it's going away */
2210 dvmSetFieldObject(vmThread, gDvm.offJavaLangVMThread_vmData, NULL);
2211
2212 /*
2213 * Tell the debugger & DDM. This may cause the current thread or all
2214 * threads to suspend.
2215 *
2216 * The JDWP spec is somewhat vague about when this happens, other than
2217 * that it's issued by the dying thread, which may still appear in
2218 * an "all threads" listing.
2219 */
2220 if (gDvm.debuggerConnected)
2221 dvmDbgPostThreadDeath(self);
2222
2223 /*
2224 * Thread.join() is implemented as an Object.wait() on the VMThread
2225 * object. Signal anyone who is waiting.
2226 */
2227 dvmLockObject(self, vmThread);
2228 dvmObjectNotifyAll(self, vmThread);
2229 dvmUnlockObject(self, vmThread);
2230
2231 dvmReleaseTrackedAlloc(vmThread, self);
2232 vmThread = NULL;
2233
2234 /*
2235 * We're done manipulating objects, so it's okay if the GC runs in
2236 * parallel with us from here out. It's important to do this if
2237 * profiling is enabled, since we can wait indefinitely.
2238 */
2239 self->status = THREAD_VMWAIT;
2240
2241#ifdef WITH_PROFILER
2242 /*
2243 * If we're doing method trace profiling, we don't want threads to exit,
2244 * because if they do we'll end up reusing thread IDs. This complicates
2245 * analysis and makes it impossible to have reasonable output in the
2246 * "threads" section of the "key" file.
2247 *
2248 * We need to do this after Thread.join() completes, or other threads
2249 * could get wedged. Since self->threadObj is still valid, the Thread
2250 * object will not get GCed even though we're no longer in the ThreadGroup
2251 * list (which is important since the profiling thread needs to get
2252 * the thread's name).
2253 */
2254 MethodTraceState* traceState = &gDvm.methodTrace;
2255
2256 dvmLockMutex(&traceState->startStopLock);
2257 if (traceState->traceEnabled) {
2258 LOGI("threadid=%d: waiting for method trace to finish\n",
2259 self->threadId);
2260 while (traceState->traceEnabled) {
2261 int cc;
2262 cc = pthread_cond_wait(&traceState->threadExitCond,
2263 &traceState->startStopLock);
2264 assert(cc == 0);
2265 }
2266 }
2267 dvmUnlockMutex(&traceState->startStopLock);
2268#endif
2269
2270 dvmLockThreadList(self);
2271
2272 /*
2273 * Lose the JNI context.
2274 */
2275 dvmDestroyJNIEnv(self->jniEnv);
2276 self->jniEnv = NULL;
2277
2278 self->status = THREAD_ZOMBIE;
2279
2280 /*
2281 * Remove ourselves from the internal thread list.
2282 */
2283 unlinkThread(self);
2284
2285 /*
2286 * If we're the last one standing, signal anybody waiting in
2287 * DestroyJavaVM that it's okay to exit.
2288 */
2289 if (!dvmGetFieldBoolean(self->threadObj, gDvm.offJavaLangThread_daemon)) {
2290 gDvm.nonDaemonThreadCount--; // guarded by thread list lock
2291
2292 if (gDvm.nonDaemonThreadCount == 0) {
2293 int cc;
2294
2295 LOGV("threadid=%d: last non-daemon thread\n", self->threadId);
2296 //dvmDumpAllThreads(false);
2297 // cond var guarded by threadListLock, which we already hold
2298 cc = pthread_cond_signal(&gDvm.vmExitCond);
2299 assert(cc == 0);
2300 }
2301 }
2302
2303 LOGV("threadid=%d: bye!\n", self->threadId);
2304 releaseThreadId(self);
2305 dvmUnlockThreadList();
2306
2307 setThreadSelf(NULL);
Bob Lee9dc72a32009-09-04 18:28:16 -07002308
Bob Lee2fe146a2009-09-10 00:36:29 +02002309 dvmDetachSystemThread(self);
Bob Lee9dc72a32009-09-04 18:28:16 -07002310
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002311 freeThread(self);
2312}
2313
2314
2315/*
2316 * Suspend a single thread. Do not use to suspend yourself.
2317 *
2318 * This is used primarily for debugger/DDMS activity. Does not return
2319 * until the thread has suspended or is in a "safe" state (e.g. executing
2320 * native code outside the VM).
2321 *
2322 * The thread list lock should be held before calling here -- it's not
2323 * entirely safe to hang on to a Thread* from another thread otherwise.
2324 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2325 */
2326void dvmSuspendThread(Thread* thread)
2327{
2328 assert(thread != NULL);
2329 assert(thread != dvmThreadSelf());
2330 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2331
2332 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002333 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002334 thread->dbgSuspendCount++;
2335
2336 LOG_THREAD("threadid=%d: suspend++, now=%d\n",
2337 thread->threadId, thread->suspendCount);
2338 unlockThreadSuspendCount();
2339
2340 waitForThreadSuspend(dvmThreadSelf(), thread);
2341}
2342
2343/*
2344 * Reduce the suspend count of a thread. If it hits zero, tell it to
2345 * resume.
2346 *
2347 * Used primarily for debugger/DDMS activity. The thread in question
2348 * might have been suspended singly or as part of a suspend-all operation.
2349 *
2350 * The thread list lock should be held before calling here -- it's not
2351 * entirely safe to hang on to a Thread* from another thread otherwise.
2352 * (We'd need to grab it here anyway to avoid clashing with a suspend-all.)
2353 */
2354void dvmResumeThread(Thread* thread)
2355{
2356 assert(thread != NULL);
2357 assert(thread != dvmThreadSelf());
2358 //assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2359
2360 lockThreadSuspendCount();
2361 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002362 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002363 thread->dbgSuspendCount--;
2364 } else {
2365 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2366 thread->threadId);
2367 }
2368
2369 LOG_THREAD("threadid=%d: suspend--, now=%d\n",
2370 thread->threadId, thread->suspendCount);
2371
2372 if (thread->suspendCount == 0) {
2373 int cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2374 assert(cc == 0);
2375 }
2376
2377 unlockThreadSuspendCount();
2378}
2379
2380/*
2381 * Suspend yourself, as a result of debugger activity.
2382 */
2383void dvmSuspendSelf(bool jdwpActivity)
2384{
2385 Thread* self = dvmThreadSelf();
2386
2387 /* debugger thread may not suspend itself due to debugger activity! */
2388 assert(gDvm.jdwpState != NULL);
2389 if (self->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2390 assert(false);
2391 return;
2392 }
2393
2394 /*
2395 * Collisions with other suspends aren't really interesting. We want
2396 * to ensure that we're the only one fiddling with the suspend count
2397 * though.
2398 */
2399 lockThreadSuspendCount();
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002400 dvmAddToThreadSuspendCount(&self->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002401 self->dbgSuspendCount++;
2402
2403 /*
2404 * Suspend ourselves.
2405 */
2406 assert(self->suspendCount > 0);
2407 self->isSuspended = true;
2408 LOG_THREAD("threadid=%d: self-suspending (dbg)\n", self->threadId);
2409
2410 /*
2411 * Tell JDWP that we've completed suspension. The JDWP thread can't
2412 * tell us to resume before we're fully asleep because we hold the
2413 * suspend count lock.
2414 *
2415 * If we got here via waitForDebugger(), don't do this part.
2416 */
2417 if (jdwpActivity) {
2418 //LOGI("threadid=%d: clearing wait-for-event (my handle=%08x)\n",
2419 // self->threadId, (int) self->handle);
2420 dvmJdwpClearWaitForEventThread(gDvm.jdwpState);
2421 }
2422
2423 while (self->suspendCount != 0) {
2424 int cc;
2425 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
2426 &gDvm.threadSuspendCountLock);
2427 assert(cc == 0);
2428 if (self->suspendCount != 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -07002429 /*
2430 * The condition was signaled but we're still suspended. This
2431 * can happen if the debugger lets go while a SIGQUIT thread
2432 * dump event is pending (assuming SignalCatcher was resumed for
2433 * just long enough to try to grab the thread-suspend lock).
2434 */
2435 LOGD("threadid=%d: still suspended after undo (sc=%d dc=%d s=%c)\n",
2436 self->threadId, self->suspendCount, self->dbgSuspendCount,
2437 self->isSuspended ? 'Y' : 'N');
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002438 }
2439 }
2440 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
2441 self->isSuspended = false;
2442 LOG_THREAD("threadid=%d: self-reviving (dbg), status=%d\n",
2443 self->threadId, self->status);
2444
2445 unlockThreadSuspendCount();
2446}
2447
2448
2449#ifdef HAVE_GLIBC
2450# define NUM_FRAMES 20
2451# include <execinfo.h>
2452/*
2453 * glibc-only stack dump function. Requires link with "--export-dynamic".
2454 *
2455 * TODO: move this into libs/cutils and make it work for all platforms.
2456 */
2457static void printBackTrace(void)
2458{
2459 void* array[NUM_FRAMES];
2460 size_t size;
2461 char** strings;
2462 size_t i;
2463
2464 size = backtrace(array, NUM_FRAMES);
2465 strings = backtrace_symbols(array, size);
2466
2467 LOGW("Obtained %zd stack frames.\n", size);
2468
2469 for (i = 0; i < size; i++)
2470 LOGW("%s\n", strings[i]);
2471
2472 free(strings);
2473}
2474#else
2475static void printBackTrace(void) {}
2476#endif
2477
2478/*
2479 * Dump the state of the current thread and that of another thread that
2480 * we think is wedged.
2481 */
2482static void dumpWedgedThread(Thread* thread)
2483{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002484 dvmDumpThread(dvmThreadSelf(), false);
2485 printBackTrace();
2486
2487 // dumping a running thread is risky, but could be useful
2488 dvmDumpThread(thread, true);
2489
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002490 // stop now and get a core dump
2491 //abort();
2492}
2493
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002494/* "change flags" values for next two functions */
2495enum { kChangedPriority = 0x01, kChangedPolicy = 0x02 };
2496
2497/*
2498 * If the thread is running at below-normal priority, temporarily elevate
2499 * it to "normal".
2500 *
2501 * Returns zero if no changes were made. Otherwise, returns bit flags
2502 * indicating what was changed, storing the previous values in the
2503 * provided locations.
2504 */
2505static int raiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
2506 SchedPolicy* pSavedThreadPolicy)
2507{
2508 errno = 0;
2509 *pSavedThreadPrio = getpriority(PRIO_PROCESS, thread->systemTid);
2510 if (errno != 0) {
2511 LOGW("Unable to get priority for threadid=%d sysTid=%d\n",
2512 thread->threadId, thread->systemTid);
2513 return 0;
2514 }
2515 if (get_sched_policy(thread->systemTid, pSavedThreadPolicy) != 0) {
2516 LOGW("Unable to get policy for threadid=%d sysTid=%d\n",
2517 thread->threadId, thread->systemTid);
2518 return 0;
2519 }
2520
2521 int changeFlags = 0;
2522
2523 /*
2524 * Change the priority if we're in the background group.
2525 */
2526 if (*pSavedThreadPolicy == SP_BACKGROUND) {
2527 if (set_sched_policy(thread->systemTid, SP_FOREGROUND) != 0) {
2528 LOGW("Couldn't set fg policy on tid %d\n", thread->systemTid);
2529 } else {
2530 changeFlags |= kChangedPolicy;
2531 LOGD("Temporarily moving tid %d to fg (was %d)\n",
2532 thread->systemTid, *pSavedThreadPolicy);
2533 }
2534 }
2535
2536 /*
2537 * getpriority() returns the "nice" value, so larger numbers indicate
2538 * lower priority, with 0 being normal.
2539 */
2540 if (*pSavedThreadPrio > 0) {
2541 const int kHigher = 0;
2542 if (setpriority(PRIO_PROCESS, thread->systemTid, kHigher) != 0) {
2543 LOGW("Couldn't raise priority on tid %d to %d\n",
2544 thread->systemTid, kHigher);
2545 } else {
2546 changeFlags |= kChangedPriority;
2547 LOGD("Temporarily raised priority on tid %d (%d -> %d)\n",
2548 thread->systemTid, *pSavedThreadPrio, kHigher);
2549 }
2550 }
2551
2552 return changeFlags;
2553}
2554
2555/*
2556 * Reset the priority values for the thread in question.
2557 */
2558static void resetThreadPriority(Thread* thread, int changeFlags,
2559 int savedThreadPrio, SchedPolicy savedThreadPolicy)
2560{
2561 if ((changeFlags & kChangedPolicy) != 0) {
2562 if (set_sched_policy(thread->systemTid, savedThreadPolicy) != 0) {
2563 LOGW("NOTE: couldn't reset tid %d to (%d)\n",
2564 thread->systemTid, savedThreadPolicy);
2565 } else {
2566 LOGD("Restored policy of %d to %d\n",
2567 thread->systemTid, savedThreadPolicy);
2568 }
2569 }
2570
2571 if ((changeFlags & kChangedPriority) != 0) {
2572 if (setpriority(PRIO_PROCESS, thread->systemTid, savedThreadPrio) != 0)
2573 {
2574 LOGW("NOTE: couldn't reset priority on thread %d to %d\n",
2575 thread->systemTid, savedThreadPrio);
2576 } else {
2577 LOGD("Restored priority on %d to %d\n",
2578 thread->systemTid, savedThreadPrio);
2579 }
2580 }
2581}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002582
2583/*
2584 * Wait for another thread to see the pending suspension and stop running.
2585 * It can either suspend itself or go into a non-running state such as
2586 * VMWAIT or NATIVE in which it cannot interact with the GC.
2587 *
2588 * If we're running at a higher priority, sched_yield() may not do anything,
2589 * so we need to sleep for "long enough" to guarantee that the other
2590 * thread has a chance to finish what it's doing. Sleeping for too short
2591 * a period (e.g. less than the resolution of the sleep clock) might cause
2592 * the scheduler to return immediately, so we want to start with a
2593 * "reasonable" value and expand.
2594 *
2595 * This does not return until the other thread has stopped running.
2596 * Eventually we time out and the VM aborts.
2597 *
2598 * This does not try to detect the situation where two threads are
2599 * waiting for each other to suspend. In normal use this is part of a
2600 * suspend-all, which implies that the suspend-all lock is held, or as
2601 * part of a debugger action in which the JDWP thread is always the one
2602 * doing the suspending. (We may need to re-evaluate this now that
2603 * getThreadStackTrace is implemented as suspend-snapshot-resume.)
2604 *
2605 * TODO: track basic stats about time required to suspend VM.
2606 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002607#define FIRST_SLEEP (250*1000) /* 0.25s */
2608#define MORE_SLEEP (750*1000) /* 0.75s */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002609static void waitForThreadSuspend(Thread* self, Thread* thread)
2610{
2611 const int kMaxRetries = 10;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002612 int spinSleepTime = FIRST_SLEEP;
Andy McFadden2aa43612009-06-17 16:29:30 -07002613 bool complained = false;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002614 int priChangeFlags = 0;
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002615 int savedThreadPrio = -500;
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002616 SchedPolicy savedThreadPolicy = SP_FOREGROUND;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002617
2618 int sleepIter = 0;
2619 int retryCount = 0;
2620 u8 startWhen = 0; // init req'd to placate gcc
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002621 u8 firstStartWhen = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002622
2623 while (thread->status == THREAD_RUNNING && !thread->isSuspended) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002624 if (sleepIter == 0) { // get current time on first iteration
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002625 startWhen = dvmGetRelativeTimeUsec();
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002626 if (firstStartWhen == 0) // first iteration of first attempt
2627 firstStartWhen = startWhen;
2628
2629 /*
2630 * After waiting for a bit, check to see if the target thread is
2631 * running at a reduced priority. If so, bump it up temporarily
2632 * to give it more CPU time.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002633 */
2634 if (retryCount == 2) {
2635 assert(thread->systemTid != 0);
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002636 priChangeFlags = raiseThreadPriorityIfNeeded(thread,
2637 &savedThreadPrio, &savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002638 }
2639 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002640
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002641#if defined (WITH_JIT)
2642 /*
Ben Cheng6999d842010-01-26 16:46:15 -08002643 * If we're still waiting after the first timeout, unchain all
2644 * translations iff:
2645 * 1) There are new chains formed since the last unchain
2646 * 2) The top VM frame of the running thread is running JIT'ed code
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002647 */
Ben Cheng6999d842010-01-26 16:46:15 -08002648 if (gDvmJit.pJitEntryTable && retryCount > 0 &&
2649 gDvmJit.hasNewChain && thread->inJitCodeCache) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002650 LOGD("JIT unchain all for threadid=%d", thread->threadId);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002651 dvmJitUnchainAll();
2652 }
2653#endif
2654
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002655 /*
Andy McFadden1ede83b2009-12-02 17:03:41 -08002656 * Sleep briefly. The iterative sleep call returns false if we've
2657 * exceeded the total time limit for this round of sleeping.
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002658 */
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002659 if (!dvmIterativeSleep(sleepIter++, spinSleepTime, startWhen)) {
Andy McFadden1ede83b2009-12-02 17:03:41 -08002660 if (spinSleepTime != FIRST_SLEEP) {
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002661 LOGW("threadid=%d: spin on suspend #%d threadid=%d (pcf=%d)\n",
Andy McFadden1ede83b2009-12-02 17:03:41 -08002662 self->threadId, retryCount,
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002663 thread->threadId, priChangeFlags);
2664 if (retryCount > 1) {
2665 /* stack trace logging is slow; skip on first iter */
2666 dumpWedgedThread(thread);
2667 }
Andy McFadden1ede83b2009-12-02 17:03:41 -08002668 complained = true;
2669 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002670
2671 // keep going; could be slow due to valgrind
2672 sleepIter = 0;
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002673 spinSleepTime = MORE_SLEEP;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002674
2675 if (retryCount++ == kMaxRetries) {
2676 LOGE("threadid=%d: stuck on threadid=%d, giving up\n",
2677 self->threadId, thread->threadId);
2678 dvmDumpAllThreads(false);
2679 dvmAbort();
2680 }
2681 }
2682 }
Andy McFadden2aa43612009-06-17 16:29:30 -07002683
2684 if (complained) {
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002685 LOGW("threadid=%d: spin on suspend resolved in %lld msec\n",
2686 self->threadId,
2687 (dvmGetRelativeTimeUsec() - firstStartWhen) / 1000);
Andy McFadden2aa43612009-06-17 16:29:30 -07002688 //dvmDumpThread(thread, false); /* suspended, so dump is safe */
2689 }
Andy McFaddend2afbcf2010-03-02 14:23:04 -08002690 if (priChangeFlags != 0) {
2691 resetThreadPriority(thread, priChangeFlags, savedThreadPrio,
2692 savedThreadPolicy);
Andy McFadden7ce9bd72009-08-07 11:41:35 -07002693 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002694}
2695
2696/*
2697 * Suspend all threads except the current one. This is used by the GC,
2698 * the debugger, and by any thread that hits a "suspend all threads"
2699 * debugger event (e.g. breakpoint or exception).
2700 *
2701 * If thread N hits a "suspend all threads" breakpoint, we don't want it
2702 * to suspend the JDWP thread. For the GC, we do, because the debugger can
2703 * create objects and even execute arbitrary code. The "why" argument
2704 * allows the caller to say why the suspension is taking place.
2705 *
2706 * This can be called when a global suspend has already happened, due to
2707 * various debugger gymnastics, so keeping an "everybody is suspended" flag
2708 * doesn't work.
2709 *
2710 * DO NOT grab any locks before calling here. We grab & release the thread
2711 * lock and suspend lock here (and we're not using recursive threads), and
2712 * we might have to self-suspend if somebody else beats us here.
2713 *
2714 * The current thread may not be attached to the VM. This can happen if
2715 * we happen to GC as the result of an allocation of a Thread object.
2716 */
2717void dvmSuspendAllThreads(SuspendCause why)
2718{
2719 Thread* self = dvmThreadSelf();
2720 Thread* thread;
2721
2722 assert(why != 0);
2723
2724 /*
2725 * Start by grabbing the thread suspend lock. If we can't get it, most
2726 * likely somebody else is in the process of performing a suspend or
2727 * resume, so lockThreadSuspend() will cause us to self-suspend.
2728 *
2729 * We keep the lock until all other threads are suspended.
2730 */
2731 lockThreadSuspend("susp-all", why);
2732
2733 LOG_THREAD("threadid=%d: SuspendAll starting\n", self->threadId);
2734
2735 /*
2736 * This is possible if the current thread was in VMWAIT mode when a
2737 * suspend-all happened, and then decided to do its own suspend-all.
2738 * This can happen when a couple of threads have simultaneous events
2739 * of interest to the debugger.
2740 */
2741 //assert(self->suspendCount == 0);
2742
2743 /*
2744 * Increment everybody's suspend count (except our own).
2745 */
2746 dvmLockThreadList(self);
2747
2748 lockThreadSuspendCount();
2749 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2750 if (thread == self)
2751 continue;
2752
2753 /* debugger events don't suspend JDWP thread */
2754 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2755 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2756 continue;
2757
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002758 dvmAddToThreadSuspendCount(&thread->suspendCount, 1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002759 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2760 thread->dbgSuspendCount++;
2761 }
2762 unlockThreadSuspendCount();
2763
2764 /*
2765 * Wait for everybody in THREAD_RUNNING state to stop. Other states
2766 * indicate the code is either running natively or sleeping quietly.
2767 * Any attempt to transition back to THREAD_RUNNING will cause a check
2768 * for suspension, so it should be impossible for anything to execute
2769 * interpreted code or modify objects (assuming native code plays nicely).
2770 *
2771 * It's also okay if the thread transitions to a non-RUNNING state.
2772 *
2773 * Note we released the threadSuspendCountLock before getting here,
2774 * so if another thread is fiddling with its suspend count (perhaps
2775 * self-suspending for the debugger) it won't block while we're waiting
2776 * in here.
2777 */
2778 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2779 if (thread == self)
2780 continue;
2781
2782 /* debugger events don't suspend JDWP thread */
2783 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2784 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
2785 continue;
2786
2787 /* wait for the other thread to see the pending suspend */
2788 waitForThreadSuspend(self, thread);
2789
Jeff Hao97319a82009-08-12 16:57:15 -07002790 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 -08002791 self->threadId,
2792 thread->threadId, thread->status, thread->suspendCount,
2793 thread->dbgSuspendCount, thread->isSuspended);
2794 }
2795
2796 dvmUnlockThreadList();
2797 unlockThreadSuspend();
2798
2799 LOG_THREAD("threadid=%d: SuspendAll complete\n", self->threadId);
2800}
2801
2802/*
2803 * Resume all threads that are currently suspended.
2804 *
2805 * The "why" must match with the previous suspend.
2806 */
2807void dvmResumeAllThreads(SuspendCause why)
2808{
2809 Thread* self = dvmThreadSelf();
2810 Thread* thread;
2811 int cc;
2812
2813 lockThreadSuspend("res-all", why); /* one suspend/resume at a time */
2814 LOG_THREAD("threadid=%d: ResumeAll starting\n", self->threadId);
2815
2816 /*
2817 * Decrement the suspend counts for all threads. No need for atomic
2818 * writes, since nobody should be moving until we decrement the count.
2819 * We do need to hold the thread list because of JNI attaches.
2820 */
2821 dvmLockThreadList(self);
2822 lockThreadSuspendCount();
2823 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2824 if (thread == self)
2825 continue;
2826
2827 /* debugger events don't suspend JDWP thread */
2828 if ((why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT) &&
2829 thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState))
Andy McFadden2aa43612009-06-17 16:29:30 -07002830 {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002831 continue;
Andy McFadden2aa43612009-06-17 16:29:30 -07002832 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002833
2834 if (thread->suspendCount > 0) {
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002835 dvmAddToThreadSuspendCount(&thread->suspendCount, -1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002836 if (why == SUSPEND_FOR_DEBUG || why == SUSPEND_FOR_DEBUG_EVENT)
2837 thread->dbgSuspendCount--;
2838 } else {
2839 LOG_THREAD("threadid=%d: suspendCount already zero\n",
2840 thread->threadId);
2841 }
2842 }
2843 unlockThreadSuspendCount();
2844 dvmUnlockThreadList();
2845
2846 /*
Andy McFadden2aa43612009-06-17 16:29:30 -07002847 * In some ways it makes sense to continue to hold the thread-suspend
2848 * lock while we issue the wakeup broadcast. It allows us to complete
2849 * one operation before moving on to the next, which simplifies the
2850 * thread activity debug traces.
2851 *
2852 * This approach caused us some difficulty under Linux, because the
2853 * condition variable broadcast not only made the threads runnable,
2854 * but actually caused them to execute, and it was a while before
2855 * the thread performing the wakeup had an opportunity to release the
2856 * thread-suspend lock.
2857 *
2858 * This is a problem because, when a thread tries to acquire that
2859 * lock, it times out after 3 seconds. If at some point the thread
2860 * is told to suspend, the clock resets; but since the VM is still
2861 * theoretically mid-resume, there's no suspend pending. If, for
2862 * example, the GC was waking threads up while the SIGQUIT handler
2863 * was trying to acquire the lock, we would occasionally time out on
2864 * a busy system and SignalCatcher would abort.
2865 *
2866 * We now perform the unlock before the wakeup broadcast. The next
2867 * suspend can't actually start until the broadcast completes and
2868 * returns, because we're holding the thread-suspend-count lock, but the
2869 * suspending thread is now able to make progress and we avoid the abort.
2870 *
2871 * (Technically there is a narrow window between when we release
2872 * the thread-suspend lock and grab the thread-suspend-count lock.
2873 * This could cause us to send a broadcast to threads with nonzero
2874 * suspend counts, but this is expected and they'll all just fall
2875 * right back to sleep. It's probably safe to grab the suspend-count
2876 * lock before releasing thread-suspend, since we're still following
2877 * the correct order of acquisition, but it feels weird.)
2878 */
2879
2880 LOG_THREAD("threadid=%d: ResumeAll waking others\n", self->threadId);
2881 unlockThreadSuspend();
2882
2883 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002884 * Broadcast a notification to all suspended threads, some or all of
2885 * which may choose to wake up. No need to wait for them.
2886 */
2887 lockThreadSuspendCount();
2888 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2889 assert(cc == 0);
2890 unlockThreadSuspendCount();
2891
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002892 LOG_THREAD("threadid=%d: ResumeAll complete\n", self->threadId);
2893}
2894
2895/*
2896 * Undo any debugger suspensions. This is called when the debugger
2897 * disconnects.
2898 */
2899void dvmUndoDebuggerSuspensions(void)
2900{
2901 Thread* self = dvmThreadSelf();
2902 Thread* thread;
2903 int cc;
2904
2905 lockThreadSuspend("undo", SUSPEND_FOR_DEBUG);
2906 LOG_THREAD("threadid=%d: UndoDebuggerSusp starting\n", self->threadId);
2907
2908 /*
2909 * Decrement the suspend counts for all threads. No need for atomic
2910 * writes, since nobody should be moving until we decrement the count.
2911 * We do need to hold the thread list because of JNI attaches.
2912 */
2913 dvmLockThreadList(self);
2914 lockThreadSuspendCount();
2915 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
2916 if (thread == self)
2917 continue;
2918
2919 /* debugger events don't suspend JDWP thread */
2920 if (thread->handle == dvmJdwpGetDebugThread(gDvm.jdwpState)) {
2921 assert(thread->dbgSuspendCount == 0);
2922 continue;
2923 }
2924
2925 assert(thread->suspendCount >= thread->dbgSuspendCount);
Bill Buzbee46cd5b62009-06-05 15:36:06 -07002926 dvmAddToThreadSuspendCount(&thread->suspendCount,
2927 -thread->dbgSuspendCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002928 thread->dbgSuspendCount = 0;
2929 }
2930 unlockThreadSuspendCount();
2931 dvmUnlockThreadList();
2932
2933 /*
2934 * Broadcast a notification to all suspended threads, some or all of
2935 * which may choose to wake up. No need to wait for them.
2936 */
2937 lockThreadSuspendCount();
2938 cc = pthread_cond_broadcast(&gDvm.threadSuspendCountCond);
2939 assert(cc == 0);
2940 unlockThreadSuspendCount();
2941
2942 unlockThreadSuspend();
2943
2944 LOG_THREAD("threadid=%d: UndoDebuggerSusp complete\n", self->threadId);
2945}
2946
2947/*
2948 * Determine if a thread is suspended.
2949 *
2950 * As with all operations on foreign threads, the caller should hold
2951 * the thread list lock before calling.
2952 */
2953bool dvmIsSuspended(Thread* thread)
2954{
2955 /*
2956 * The thread could be:
2957 * (1) Running happily. status is RUNNING, isSuspended is false,
2958 * suspendCount is zero. Return "false".
2959 * (2) Pending suspend. status is RUNNING, isSuspended is false,
2960 * suspendCount is nonzero. Return "false".
2961 * (3) Suspended. suspendCount is nonzero, and either (status is
2962 * RUNNING and isSuspended is true) OR (status is !RUNNING).
2963 * Return "true".
2964 * (4) Waking up. suspendCount is zero, status is RUNNING and
2965 * isSuspended is true. Return "false" (since it could change
2966 * out from under us, unless we hold suspendCountLock).
2967 */
2968
2969 return (thread->suspendCount != 0 &&
2970 ((thread->status == THREAD_RUNNING && thread->isSuspended) ||
2971 (thread->status != THREAD_RUNNING)));
2972}
2973
2974/*
2975 * Wait until another thread self-suspends. This is specifically for
2976 * synchronization between the JDWP thread and a thread that has decided
2977 * to suspend itself after sending an event to the debugger.
2978 *
2979 * Threads that encounter "suspend all" events work as well -- the thread
2980 * in question suspends everybody else and then itself.
2981 *
2982 * We can't hold a thread lock here or in the caller, because we could
2983 * get here just before the to-be-waited-for-thread issues a "suspend all".
2984 * There's an opportunity for badness if the thread we're waiting for exits
2985 * and gets cleaned up, but since the thread in question is processing a
2986 * debugger event, that's not really a possibility. (To avoid deadlock,
2987 * it's important that we not be in THREAD_RUNNING while we wait.)
2988 */
2989void dvmWaitForSuspend(Thread* thread)
2990{
2991 Thread* self = dvmThreadSelf();
2992
2993 LOG_THREAD("threadid=%d: waiting for threadid=%d to sleep\n",
2994 self->threadId, thread->threadId);
2995
2996 assert(thread->handle != dvmJdwpGetDebugThread(gDvm.jdwpState));
2997 assert(thread != self);
2998 assert(self->status != THREAD_RUNNING);
2999
3000 waitForThreadSuspend(self, thread);
3001
3002 LOG_THREAD("threadid=%d: threadid=%d is now asleep\n",
3003 self->threadId, thread->threadId);
3004}
3005
3006/*
3007 * Check to see if we need to suspend ourselves. If so, go to sleep on
3008 * a condition variable.
3009 *
3010 * Takes "self" as an argument as an optimization. Pass in NULL to have
3011 * it do the lookup.
3012 *
3013 * Returns "true" if we suspended ourselves.
3014 */
3015bool dvmCheckSuspendPending(Thread* self)
3016{
3017 bool didSuspend;
3018
3019 if (self == NULL)
3020 self = dvmThreadSelf();
3021
3022 /* fast path: if count is zero, bail immediately */
3023 if (self->suspendCount == 0)
3024 return false;
3025
3026 lockThreadSuspendCount(); /* grab gDvm.threadSuspendCountLock */
3027
3028 assert(self->suspendCount >= 0); /* XXX: valid? useful? */
3029
3030 didSuspend = (self->suspendCount != 0);
3031 self->isSuspended = true;
3032 LOG_THREAD("threadid=%d: self-suspending\n", self->threadId);
3033 while (self->suspendCount != 0) {
3034 /* wait for wakeup signal; releases lock */
3035 int cc;
3036 cc = pthread_cond_wait(&gDvm.threadSuspendCountCond,
3037 &gDvm.threadSuspendCountLock);
3038 assert(cc == 0);
3039 }
3040 assert(self->suspendCount == 0 && self->dbgSuspendCount == 0);
3041 self->isSuspended = false;
3042 LOG_THREAD("threadid=%d: self-reviving, status=%d\n",
3043 self->threadId, self->status);
3044
3045 unlockThreadSuspendCount();
3046
3047 return didSuspend;
3048}
3049
3050/*
3051 * Update our status.
3052 *
3053 * The "self" argument, which may be NULL, is accepted as an optimization.
3054 *
3055 * Returns the old status.
3056 */
3057ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus)
3058{
3059 ThreadStatus oldStatus;
3060
3061 if (self == NULL)
3062 self = dvmThreadSelf();
3063
3064 LOGVV("threadid=%d: (status %d -> %d)\n",
3065 self->threadId, self->status, newStatus);
3066
3067 oldStatus = self->status;
3068
3069 if (newStatus == THREAD_RUNNING) {
3070 /*
3071 * Change our status to THREAD_RUNNING. The transition requires
3072 * that we check for pending suspension, because the VM considers
3073 * us to be "asleep" in all other states.
3074 *
3075 * We need to do the "suspend pending" check FIRST, because it grabs
3076 * a lock that could be held by something that wants us to suspend.
3077 * If we're in RUNNING it will wait for us, and we'll be waiting
3078 * for the lock it holds.
3079 */
3080 assert(self->status != THREAD_RUNNING);
3081
3082 dvmCheckSuspendPending(self);
3083 self->status = THREAD_RUNNING;
3084 } else {
3085 /*
3086 * Change from one state to another, neither of which is
3087 * THREAD_RUNNING. This is most common during system or thread
3088 * initialization.
3089 */
3090 self->status = newStatus;
3091 }
3092
3093 return oldStatus;
3094}
3095
3096/*
3097 * Get a statically defined thread group from a field in the ThreadGroup
3098 * Class object. Expected arguments are "mMain" and "mSystem".
3099 */
3100static Object* getStaticThreadGroup(const char* fieldName)
3101{
3102 StaticField* groupField;
3103 Object* groupObj;
3104
3105 groupField = dvmFindStaticField(gDvm.classJavaLangThreadGroup,
3106 fieldName, "Ljava/lang/ThreadGroup;");
3107 if (groupField == NULL) {
3108 LOGE("java.lang.ThreadGroup does not have an '%s' field\n", fieldName);
3109 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;", NULL);
3110 return NULL;
3111 }
3112 groupObj = dvmGetStaticFieldObject(groupField);
3113 if (groupObj == NULL) {
3114 LOGE("java.lang.ThreadGroup.%s not initialized\n", fieldName);
3115 dvmThrowException("Ljava/lang/InternalError;", NULL);
3116 return NULL;
3117 }
3118
3119 return groupObj;
3120}
3121Object* dvmGetSystemThreadGroup(void)
3122{
3123 return getStaticThreadGroup("mSystem");
3124}
3125Object* dvmGetMainThreadGroup(void)
3126{
3127 return getStaticThreadGroup("mMain");
3128}
3129
3130/*
3131 * Given a VMThread object, return the associated Thread*.
3132 *
3133 * NOTE: if the thread detaches, the struct Thread will disappear, and
3134 * we will be touching invalid data. For safety, lock the thread list
3135 * before calling this.
3136 */
3137Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj)
3138{
3139 int vmData;
3140
3141 vmData = dvmGetFieldInt(vmThreadObj, gDvm.offJavaLangVMThread_vmData);
Andy McFadden44860362009-08-06 17:56:14 -07003142
3143 if (false) {
3144 Thread* thread = gDvm.threadList;
3145 while (thread != NULL) {
3146 if ((Thread*)vmData == thread)
3147 break;
3148
3149 thread = thread->next;
3150 }
3151
3152 if (thread == NULL) {
3153 LOGW("WARNING: vmThreadObj=%p has thread=%p, not in thread list\n",
3154 vmThreadObj, (Thread*)vmData);
3155 vmData = 0;
3156 }
3157 }
3158
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003159 return (Thread*) vmData;
3160}
3161
3162
3163/*
3164 * Conversion map for "nice" values.
3165 *
3166 * We use Android thread priority constants to be consistent with the rest
3167 * of the system. In some cases adjacent entries may overlap.
3168 */
3169static const int kNiceValues[10] = {
3170 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
3171 ANDROID_PRIORITY_BACKGROUND + 6,
3172 ANDROID_PRIORITY_BACKGROUND + 3,
3173 ANDROID_PRIORITY_BACKGROUND,
3174 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
3175 ANDROID_PRIORITY_NORMAL - 2,
3176 ANDROID_PRIORITY_NORMAL - 4,
3177 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
3178 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
3179 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
3180};
3181
3182/*
3183 * Change the priority of a system thread to match that of the Thread object.
3184 *
3185 * We map a priority value from 1-10 to Linux "nice" values, where lower
3186 * numbers indicate higher priority.
3187 */
3188void dvmChangeThreadPriority(Thread* thread, int newPriority)
3189{
3190 pid_t pid = thread->systemTid;
3191 int newNice;
3192
3193 if (newPriority < 1 || newPriority > 10) {
3194 LOGW("bad priority %d\n", newPriority);
3195 newPriority = 5;
3196 }
3197 newNice = kNiceValues[newPriority-1];
3198
Andy McFaddend62c0b52009-08-04 15:02:12 -07003199 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003200 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat3e371e22009-06-26 08:36:16 -07003201 } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07003202 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -07003203 }
3204
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003205 if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
3206 char* str = dvmGetThreadName(thread);
3207 LOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s\n",
3208 pid, str, newPriority, newNice, strerror(errno));
3209 free(str);
3210 } else {
3211 LOGV("setPriority(%d) to prio=%d(n=%d)\n",
3212 pid, newPriority, newNice);
3213 }
3214}
3215
3216/*
3217 * Get the thread priority for the current thread by querying the system.
3218 * This is useful when attaching a thread through JNI.
3219 *
3220 * Returns a value from 1 to 10 (compatible with java.lang.Thread values).
3221 */
3222static int getThreadPriorityFromSystem(void)
3223{
3224 int i, sysprio, jprio;
3225
3226 errno = 0;
3227 sysprio = getpriority(PRIO_PROCESS, 0);
3228 if (sysprio == -1 && errno != 0) {
3229 LOGW("getpriority() failed: %s\n", strerror(errno));
3230 return THREAD_NORM_PRIORITY;
3231 }
3232
3233 jprio = THREAD_MIN_PRIORITY;
3234 for (i = 0; i < NELEM(kNiceValues); i++) {
3235 if (sysprio >= kNiceValues[i])
3236 break;
3237 jprio++;
3238 }
3239 if (jprio > THREAD_MAX_PRIORITY)
3240 jprio = THREAD_MAX_PRIORITY;
3241
3242 return jprio;
3243}
3244
3245
3246/*
3247 * Return true if the thread is on gDvm.threadList.
3248 * Caller should not hold gDvm.threadListLock.
3249 */
3250bool dvmIsOnThreadList(const Thread* thread)
3251{
3252 bool ret = false;
3253
3254 dvmLockThreadList(NULL);
3255 if (thread == gDvm.threadList) {
3256 ret = true;
3257 } else {
3258 ret = thread->prev != NULL || thread->next != NULL;
3259 }
3260 dvmUnlockThreadList();
3261
3262 return ret;
3263}
3264
3265/*
3266 * Dump a thread to the log file -- just calls dvmDumpThreadEx() with an
3267 * output target.
3268 */
3269void dvmDumpThread(Thread* thread, bool isRunning)
3270{
3271 DebugOutputTarget target;
3272
3273 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3274 dvmDumpThreadEx(&target, thread, isRunning);
3275}
3276
3277/*
Andy McFaddend62c0b52009-08-04 15:02:12 -07003278 * Try to get the scheduler group.
3279 *
Andy McFadden7f64ede2010-03-03 15:37:10 -08003280 * The data from /proc/<pid>/cgroup looks (something) like:
Andy McFaddend62c0b52009-08-04 15:02:12 -07003281 * 2:cpu:/bg_non_interactive
Andy McFadden7f64ede2010-03-03 15:37:10 -08003282 * 1:cpuacct:/
Andy McFaddend62c0b52009-08-04 15:02:12 -07003283 *
3284 * We return the part after the "/", which will be an empty string for
3285 * the default cgroup. If the string is longer than "bufLen", the string
3286 * will be truncated.
Andy McFadden7f64ede2010-03-03 15:37:10 -08003287 *
3288 * TODO: this is cloned from a static function in libcutils; expose that?
Andy McFaddend62c0b52009-08-04 15:02:12 -07003289 */
Andy McFadden7f64ede2010-03-03 15:37:10 -08003290static int getSchedulerGroup(int tid, char* buf, size_t bufLen)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003291{
3292#ifdef HAVE_ANDROID_OS
3293 char pathBuf[32];
Andy McFadden7f64ede2010-03-03 15:37:10 -08003294 char lineBuf[256];
3295 FILE *fp;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003296
Andy McFadden7f64ede2010-03-03 15:37:10 -08003297 snprintf(pathBuf, sizeof(pathBuf), "/proc/%d/cgroup", tid);
3298 if (!(fp = fopen(pathBuf, "r"))) {
3299 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003300 }
3301
Andy McFadden7f64ede2010-03-03 15:37:10 -08003302 while(fgets(lineBuf, sizeof(lineBuf) -1, fp)) {
3303 char *next = lineBuf;
3304 char *subsys;
3305 char *grp;
3306 size_t len;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003307
Andy McFadden7f64ede2010-03-03 15:37:10 -08003308 /* Junk the first field */
3309 if (!strsep(&next, ":")) {
3310 goto out_bad_data;
3311 }
Andy McFaddend62c0b52009-08-04 15:02:12 -07003312
Andy McFadden7f64ede2010-03-03 15:37:10 -08003313 if (!(subsys = strsep(&next, ":"))) {
3314 goto out_bad_data;
3315 }
3316
3317 if (strcmp(subsys, "cpu")) {
3318 /* Not the subsys we're looking for */
3319 continue;
3320 }
3321
3322 if (!(grp = strsep(&next, ":"))) {
3323 goto out_bad_data;
3324 }
3325 grp++; /* Drop the leading '/' */
3326 len = strlen(grp);
3327 grp[len-1] = '\0'; /* Drop the trailing '\n' */
3328
3329 if (bufLen <= len) {
3330 len = bufLen - 1;
3331 }
3332 strncpy(buf, grp, len);
3333 buf[len] = '\0';
3334 fclose(fp);
3335 return 0;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003336 }
3337
Andy McFadden7f64ede2010-03-03 15:37:10 -08003338 LOGE("Failed to find cpu subsys");
3339 fclose(fp);
3340 return -1;
3341 out_bad_data:
3342 LOGE("Bad cgroup data {%s}", lineBuf);
3343 fclose(fp);
3344 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003345#else
Andy McFadden7f64ede2010-03-03 15:37:10 -08003346 errno = ENOSYS;
3347 return -1;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003348#endif
3349}
3350
3351/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -08003352 * Convert ThreadStatus to a string.
3353 */
3354const char* dvmGetThreadStatusStr(ThreadStatus status)
3355{
3356 switch (status) {
3357 case THREAD_ZOMBIE: return "ZOMBIE";
3358 case THREAD_RUNNING: return "RUNNABLE";
3359 case THREAD_TIMED_WAIT: return "TIMED_WAIT";
3360 case THREAD_MONITOR: return "MONITOR";
3361 case THREAD_WAIT: return "WAIT";
3362 case THREAD_INITIALIZING: return "INITIALIZING";
3363 case THREAD_STARTING: return "STARTING";
3364 case THREAD_NATIVE: return "NATIVE";
3365 case THREAD_VMWAIT: return "VMWAIT";
3366 default: return "UNKNOWN";
3367 }
3368}
3369
3370/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003371 * Print information about the specified thread.
3372 *
3373 * Works best when the thread in question is "self" or has been suspended.
3374 * When dumping a separate thread that's still running, set "isRunning" to
3375 * use a more cautious thread dump function.
3376 */
3377void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
3378 bool isRunning)
3379{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003380 Object* threadObj;
3381 Object* groupObj;
3382 StringObject* nameStr;
3383 char* threadName = NULL;
3384 char* groupName = NULL;
Andy McFaddend62c0b52009-08-04 15:02:12 -07003385 char schedulerGroupBuf[32];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003386 bool isDaemon;
3387 int priority; // java.lang.Thread priority
3388 int policy; // pthread policy
3389 struct sched_param sp; // pthread scheduling parameters
3390
3391 threadObj = thread->threadObj;
3392 if (threadObj == NULL) {
3393 LOGW("Can't dump thread %d: threadObj not set\n", thread->threadId);
3394 return;
3395 }
3396 nameStr = (StringObject*) dvmGetFieldObject(threadObj,
3397 gDvm.offJavaLangThread_name);
3398 threadName = dvmCreateCstrFromString(nameStr);
3399
3400 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
3401 isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
3402
3403 if (pthread_getschedparam(pthread_self(), &policy, &sp) != 0) {
3404 LOGW("Warning: pthread_getschedparam failed\n");
3405 policy = -1;
3406 sp.sched_priority = -1;
3407 }
Andy McFadden7f64ede2010-03-03 15:37:10 -08003408 if (getSchedulerGroup(thread->systemTid, schedulerGroupBuf,
3409 sizeof(schedulerGroupBuf)) != 0)
Andy McFaddend62c0b52009-08-04 15:02:12 -07003410 {
3411 strcpy(schedulerGroupBuf, "unknown");
3412 } else if (schedulerGroupBuf[0] == '\0') {
3413 strcpy(schedulerGroupBuf, "default");
3414 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003415
3416 /* a null value for group is not expected, but deal with it anyway */
3417 groupObj = (Object*) dvmGetFieldObject(threadObj,
3418 gDvm.offJavaLangThread_group);
3419 if (groupObj != NULL) {
3420 int offset = dvmFindFieldOffset(gDvm.classJavaLangThreadGroup,
3421 "name", "Ljava/lang/String;");
3422 if (offset < 0) {
3423 LOGW("Unable to find 'name' field in ThreadGroup\n");
3424 } else {
3425 nameStr = (StringObject*) dvmGetFieldObject(groupObj, offset);
3426 groupName = dvmCreateCstrFromString(nameStr);
3427 }
3428 }
3429 if (groupName == NULL)
3430 groupName = strdup("(BOGUS GROUP)");
3431
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003432 dvmPrintDebugMessage(target,
Ben Chengdc4a9282010-02-24 17:27:01 -08003433 "\"%s\"%s prio=%d tid=%d %s%s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003434 threadName, isDaemon ? " daemon" : "",
Ben Chengdc4a9282010-02-24 17:27:01 -08003435 priority, thread->threadId, dvmGetThreadStatusStr(thread->status),
3436#if defined(WITH_JIT)
3437 thread->inJitCodeCache ? " JIT" : ""
3438#else
3439 ""
3440#endif
3441 );
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003442 dvmPrintDebugMessage(target,
Andy McFadden2aa43612009-06-17 16:29:30 -07003443 " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p self=%p\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003444 groupName, thread->suspendCount, thread->dbgSuspendCount,
Andy McFadden2aa43612009-06-17 16:29:30 -07003445 thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003446 dvmPrintDebugMessage(target,
Andy McFaddend62c0b52009-08-04 15:02:12 -07003447 " | sysTid=%d nice=%d sched=%d/%d cgrp=%s handle=%d\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003448 thread->systemTid, getpriority(PRIO_PROCESS, thread->systemTid),
Andy McFaddend62c0b52009-08-04 15:02:12 -07003449 policy, sp.sched_priority, schedulerGroupBuf, (int)thread->handle);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003450
3451#ifdef WITH_MONITOR_TRACKING
3452 if (!isRunning) {
3453 LockedObjectData* lod = thread->pLockedObjects;
3454 if (lod != NULL)
3455 dvmPrintDebugMessage(target, " | monitors held:\n");
3456 else
3457 dvmPrintDebugMessage(target, " | monitors held: <none>\n");
3458 while (lod != NULL) {
Elliott Hughesbeea0b72009-11-13 11:20:15 -08003459 Object* obj = lod->obj;
3460 if (obj->clazz == gDvm.classJavaLangClass) {
3461 ClassObject* clazz = (ClassObject*) obj;
3462 dvmPrintDebugMessage(target, " > %p[%d] (%s object for class %s)\n",
3463 obj, lod->recursionCount, obj->clazz->descriptor,
3464 clazz->descriptor);
3465 } else {
3466 dvmPrintDebugMessage(target, " > %p[%d] (%s)\n",
3467 obj, lod->recursionCount, obj->clazz->descriptor);
3468 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003469 lod = lod->next;
3470 }
3471 }
3472#endif
3473
3474 if (isRunning)
3475 dvmDumpRunningThreadStack(target, thread);
3476 else
3477 dvmDumpThreadStack(target, thread);
3478
3479 free(threadName);
3480 free(groupName);
3481
3482}
3483
3484/*
3485 * Get the name of a thread.
3486 *
3487 * For correctness, the caller should hold the thread list lock to ensure
3488 * that the thread doesn't go away mid-call.
3489 *
3490 * Returns a newly-allocated string, or NULL if the Thread doesn't have a name.
3491 */
3492char* dvmGetThreadName(Thread* thread)
3493{
3494 StringObject* nameObj;
3495
3496 if (thread->threadObj == NULL) {
3497 LOGW("threadObj is NULL, name not available\n");
3498 return strdup("-unknown-");
3499 }
3500
3501 nameObj = (StringObject*)
3502 dvmGetFieldObject(thread->threadObj, gDvm.offJavaLangThread_name);
3503 return dvmCreateCstrFromString(nameObj);
3504}
3505
3506/*
3507 * Dump all threads to the log file -- just calls dvmDumpAllThreadsEx() with
3508 * an output target.
3509 */
3510void dvmDumpAllThreads(bool grabLock)
3511{
3512 DebugOutputTarget target;
3513
3514 dvmCreateLogOutputTarget(&target, ANDROID_LOG_INFO, LOG_TAG);
3515 dvmDumpAllThreadsEx(&target, grabLock);
3516}
3517
3518/*
3519 * Print information about all known threads. Assumes they have been
3520 * suspended (or are in a non-interpreting state, e.g. WAIT or NATIVE).
3521 *
3522 * If "grabLock" is true, we grab the thread lock list. This is important
3523 * to do unless the caller already holds the lock.
3524 */
3525void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock)
3526{
3527 Thread* thread;
3528
3529 dvmPrintDebugMessage(target, "DALVIK THREADS:\n");
3530
3531 if (grabLock)
3532 dvmLockThreadList(dvmThreadSelf());
3533
3534 thread = gDvm.threadList;
3535 while (thread != NULL) {
3536 dvmDumpThreadEx(target, thread, false);
3537
3538 /* verify link */
3539 assert(thread->next == NULL || thread->next->prev == thread);
3540
3541 thread = thread->next;
3542 }
3543
3544 if (grabLock)
3545 dvmUnlockThreadList();
3546}
3547
3548#ifdef WITH_MONITOR_TRACKING
3549/*
3550 * Count up the #of locked objects in the current thread.
3551 */
3552static int getThreadObjectCount(const Thread* self)
3553{
3554 LockedObjectData* lod;
3555 int count = 0;
3556
3557 lod = self->pLockedObjects;
3558 while (lod != NULL) {
3559 count++;
3560 lod = lod->next;
3561 }
3562 return count;
3563}
3564
3565/*
3566 * Add the object to the thread's locked object list if it doesn't already
3567 * exist. The most recently added object is the most likely to be released
3568 * next, so we insert at the head of the list.
3569 *
3570 * If it already exists, we increase the recursive lock count.
3571 *
3572 * The object's lock may be thin or fat.
3573 */
3574void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace)
3575{
3576 LockedObjectData* newLod;
3577 LockedObjectData* lod;
3578 int* trace;
3579 int depth;
3580
3581 lod = self->pLockedObjects;
3582 while (lod != NULL) {
3583 if (lod->obj == obj) {
3584 lod->recursionCount++;
3585 LOGV("+++ +recursive lock %p -> %d\n", obj, lod->recursionCount);
3586 return;
3587 }
3588 lod = lod->next;
3589 }
3590
3591 newLod = (LockedObjectData*) calloc(1, sizeof(LockedObjectData));
3592 if (newLod == NULL) {
3593 LOGE("malloc failed on %d bytes\n", sizeof(LockedObjectData));
3594 return;
3595 }
3596 newLod->obj = obj;
3597 newLod->recursionCount = 0;
3598
3599 if (withTrace) {
3600 trace = dvmFillInStackTraceRaw(self, &depth);
3601 newLod->rawStackTrace = trace;
3602 newLod->stackDepth = depth;
3603 }
3604
3605 newLod->next = self->pLockedObjects;
3606 self->pLockedObjects = newLod;
3607
3608 LOGV("+++ threadid=%d: added %p, now %d\n",
3609 self->threadId, newLod, getThreadObjectCount(self));
3610}
3611
3612/*
3613 * Remove the object from the thread's locked object list. If the entry
3614 * has a nonzero recursion count, we just decrement the count instead.
3615 */
3616void dvmRemoveFromMonitorList(Thread* self, Object* obj)
3617{
3618 LockedObjectData* lod;
3619 LockedObjectData* prevLod;
3620
3621 lod = self->pLockedObjects;
3622 prevLod = NULL;
3623 while (lod != NULL) {
3624 if (lod->obj == obj) {
3625 if (lod->recursionCount > 0) {
3626 lod->recursionCount--;
3627 LOGV("+++ -recursive lock %p -> %d\n",
3628 obj, lod->recursionCount);
3629 return;
3630 } else {
3631 break;
3632 }
3633 }
3634 prevLod = lod;
3635 lod = lod->next;
3636 }
3637
3638 if (lod == NULL) {
3639 LOGW("BUG: object %p not found in thread's lock list\n", obj);
3640 return;
3641 }
3642 if (prevLod == NULL) {
3643 /* first item in list */
3644 assert(self->pLockedObjects == lod);
3645 self->pLockedObjects = lod->next;
3646 } else {
3647 /* middle/end of list */
3648 prevLod->next = lod->next;
3649 }
3650
3651 LOGV("+++ threadid=%d: removed %p, now %d\n",
3652 self->threadId, lod, getThreadObjectCount(self));
3653 free(lod->rawStackTrace);
3654 free(lod);
3655}
3656
3657/*
3658 * If the specified object is already in the thread's locked object list,
3659 * return the LockedObjectData struct. Otherwise return NULL.
3660 */
3661LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj)
3662{
3663 LockedObjectData* lod;
3664
3665 lod = self->pLockedObjects;
3666 while (lod != NULL) {
3667 if (lod->obj == obj)
3668 return lod;
3669 lod = lod->next;
3670 }
3671 return NULL;
3672}
3673#endif /*WITH_MONITOR_TRACKING*/
3674
3675
3676/*
3677 * GC helper functions
3678 */
3679
The Android Open Source Project99409882009-03-18 22:20:24 -07003680/*
3681 * Add the contents of the registers from the interpreted call stack.
3682 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003683static void gcScanInterpStackReferences(Thread *thread)
3684{
3685 const u4 *framePtr;
The Android Open Source Project99409882009-03-18 22:20:24 -07003686#if WITH_EXTRA_GC_CHECKS > 1
3687 bool first = true;
3688#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003689
3690 framePtr = (const u4 *)thread->curFrame;
3691 while (framePtr != NULL) {
3692 const StackSaveArea *saveArea;
3693 const Method *method;
3694
3695 saveArea = SAVEAREA_FROM_FP(framePtr);
3696 method = saveArea->method;
The Android Open Source Project99409882009-03-18 22:20:24 -07003697 if (method != NULL && !dvmIsNativeMethod(method)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003698#ifdef COUNT_PRECISE_METHODS
3699 /* the GC is running, so no lock required */
The Android Open Source Project99409882009-03-18 22:20:24 -07003700 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
3701 LOGI("PGC: added %s.%s %p\n",
3702 method->clazz->descriptor, method->name, method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003703#endif
The Android Open Source Project99409882009-03-18 22:20:24 -07003704#if WITH_EXTRA_GC_CHECKS > 1
3705 /*
3706 * May also want to enable the memset() in the "invokeMethod"
3707 * goto target in the portable interpreter. That sets the stack
3708 * to a pattern that makes referring to uninitialized data
3709 * very obvious.
3710 */
3711
3712 if (first) {
3713 /*
3714 * First frame, isn't native, check the "alternate" saved PC
3715 * as a sanity check.
3716 *
3717 * It seems like we could check the second frame if the first
3718 * is native, since the PCs should be the same. It turns out
3719 * this doesn't always work. The problem is that we could
3720 * have calls in the sequence:
3721 * interp method #2
3722 * native method
3723 * interp method #1
3724 *
3725 * and then GC while in the native method after returning
3726 * from interp method #2. The currentPc on the stack is
3727 * for interp method #1, but thread->currentPc2 is still
3728 * set for the last thing interp method #2 did.
3729 *
3730 * This can also happen in normal execution:
3731 * - sget-object on not-yet-loaded class
3732 * - class init updates currentPc2
3733 * - static field init is handled by parsing annotations;
3734 * static String init requires creation of a String object,
3735 * which can cause a GC
3736 *
3737 * Essentially, any pattern that involves executing
3738 * interpreted code and then causes an allocation without
3739 * executing instructions in the original method will hit
3740 * this. These are rare enough that the test still has
3741 * some value.
3742 */
3743 if (saveArea->xtra.currentPc != thread->currentPc2) {
3744 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
3745 saveArea->xtra.currentPc, thread->currentPc2,
3746 method->clazz->descriptor, method->name, method->insns);
3747 if (saveArea->xtra.currentPc != NULL)
3748 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
3749 if (thread->currentPc2 != NULL)
3750 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
3751 dvmDumpThread(thread, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003752 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003753 } else {
3754 /*
3755 * It's unusual, but not impossible, for a non-first frame
3756 * to be at something other than a method invocation. For
3757 * example, if we do a new-instance on a nonexistent class,
3758 * we'll have a lot of class loader activity on the stack
3759 * above the frame with the "new" operation. Could also
3760 * happen while we initialize a Throwable when an instruction
3761 * fails.
3762 *
3763 * So there's not much we can do here to verify the PC,
3764 * except to verify that it's a GC point.
3765 */
3766 }
3767 assert(saveArea->xtra.currentPc != NULL);
3768#endif
3769
3770 const RegisterMap* pMap;
3771 const u1* regVector;
3772 int i;
3773
Andy McFaddencf8b55c2009-04-13 15:26:03 -07003774 Method* nonConstMethod = (Method*) method; // quiet gcc
3775 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
The Android Open Source Project99409882009-03-18 22:20:24 -07003776 if (pMap != NULL) {
3777 /* found map, get registers for this address */
3778 int addr = saveArea->xtra.currentPc - method->insns;
Andy McFaddend45a8872009-03-24 20:41:52 -07003779 regVector = dvmRegisterMapGetLine(pMap, addr);
The Android Open Source Project99409882009-03-18 22:20:24 -07003780 if (regVector == NULL) {
3781 LOGW("PGC: map but no entry for %s.%s addr=0x%04x\n",
3782 method->clazz->descriptor, method->name, addr);
3783 } else {
3784 LOGV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
3785 method->clazz->descriptor, method->name, addr,
3786 thread->threadId);
3787 }
3788 } else {
3789 /*
3790 * No map found. If precise GC is disabled this is
3791 * expected -- we don't create pointers to the map data even
3792 * if it's present -- but if it's enabled it means we're
3793 * unexpectedly falling back on a conservative scan, so it's
3794 * worth yelling a little.
The Android Open Source Project99409882009-03-18 22:20:24 -07003795 */
3796 if (gDvm.preciseGc) {
Andy McFaddena66a01a2009-08-18 15:11:35 -07003797 LOGVV("PGC: no map for %s.%s\n",
The Android Open Source Project99409882009-03-18 22:20:24 -07003798 method->clazz->descriptor, method->name);
3799 }
3800 regVector = NULL;
3801 }
3802
3803 if (regVector == NULL) {
3804 /* conservative scan */
3805 for (i = method->registersSize - 1; i >= 0; i--) {
3806 u4 rval = *framePtr++;
3807 if (rval != 0 && (rval & 0x3) == 0) {
3808 dvmMarkIfObject((Object *)rval);
3809 }
3810 }
3811 } else {
3812 /*
3813 * Precise scan. v0 is at the lowest address on the
3814 * interpreted stack, and is the first bit in the register
3815 * vector, so we can walk through the register map and
3816 * memory in the same direction.
3817 *
3818 * A '1' bit indicates a live reference.
3819 */
3820 u2 bits = 1 << 1;
3821 for (i = method->registersSize - 1; i >= 0; i--) {
3822 u4 rval = *framePtr++;
3823
3824 bits >>= 1;
3825 if (bits == 1) {
3826 /* set bit 9 so we can tell when we're empty */
3827 bits = *regVector++ | 0x0100;
3828 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
3829 }
3830
3831 if (rval != 0 && (bits & 0x01) != 0) {
3832 /*
3833 * Non-null, register marked as live reference. This
3834 * should always be a valid object.
3835 */
3836#if WITH_EXTRA_GC_CHECKS > 0
3837 if ((rval & 0x3) != 0 ||
3838 !dvmIsValidObject((Object*) rval))
3839 {
3840 /* this is very bad */
3841 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
3842 method->registersSize-1 - i, rval);
3843 } else
3844#endif
3845 {
3846 dvmMarkObjectNonNull((Object *)rval);
3847 }
3848 } else {
3849 /*
3850 * Null or non-reference, do nothing at all.
3851 */
3852#if WITH_EXTRA_GC_CHECKS > 1
3853 if (dvmIsValidObject((Object*) rval)) {
3854 /* this is normal, but we feel chatty */
3855 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
3856 method->registersSize-1 - i, rval);
3857 }
3858#endif
3859 }
3860 }
3861 dvmReleaseRegisterMapLine(pMap, regVector);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003862 }
3863 }
The Android Open Source Project99409882009-03-18 22:20:24 -07003864 /* else this is a break frame and there is nothing to mark, or
3865 * this is a native method and the registers are just the "ins",
3866 * copied from various registers in the caller's set.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003867 */
3868
The Android Open Source Project99409882009-03-18 22:20:24 -07003869#if WITH_EXTRA_GC_CHECKS > 1
3870 first = false;
3871#endif
3872
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003873 /* Don't fall into an infinite loop if things get corrupted.
3874 */
3875 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
3876 saveArea->prevFrame == NULL);
3877 framePtr = saveArea->prevFrame;
3878 }
3879}
3880
3881static void gcScanReferenceTable(ReferenceTable *refTable)
3882{
3883 Object **op;
3884
3885 //TODO: these asserts are overkill; turn them off when things stablize.
3886 assert(refTable != NULL);
3887 assert(refTable->table != NULL);
3888 assert(refTable->nextEntry != NULL);
3889 assert((uintptr_t)refTable->nextEntry >= (uintptr_t)refTable->table);
3890 assert(refTable->nextEntry - refTable->table <= refTable->maxEntries);
3891
3892 op = refTable->table;
3893 while ((uintptr_t)op < (uintptr_t)refTable->nextEntry) {
3894 dvmMarkObjectNonNull(*(op++));
3895 }
3896}
3897
Andy McFaddend5ab7262009-08-25 07:19:34 -07003898static void gcScanIndirectRefTable(IndirectRefTable* pRefTable)
3899{
3900 Object** op = pRefTable->table;
3901 int numEntries = dvmIndirectRefTableEntries(pRefTable);
3902 int i;
3903
3904 for (i = 0; i < numEntries; i++) {
3905 Object* obj = *op;
3906 if (obj != NULL)
3907 dvmMarkObjectNonNull(obj);
3908 op++;
3909 }
3910}
3911
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003912/*
3913 * Scan a Thread and mark any objects it references.
3914 */
3915static void gcScanThread(Thread *thread)
3916{
3917 assert(thread != NULL);
3918
3919 /*
3920 * The target thread must be suspended or in a state where it can't do
3921 * any harm (e.g. in Object.wait()). The only exception is the current
3922 * thread, which will still be active and in the "running" state.
3923 *
3924 * (Newly-created threads shouldn't be able to shift themselves to
3925 * RUNNING without a suspend-pending check, so this shouldn't cause
3926 * a false-positive.)
3927 */
Andy McFaddend40223e2009-12-07 15:35:51 -08003928 if (thread->status == THREAD_RUNNING && !thread->isSuspended &&
3929 thread != dvmThreadSelf())
3930 {
3931 Thread* self = dvmThreadSelf();
3932 LOGW("threadid=%d: BUG: GC scanning a running thread (%d)\n",
3933 self->threadId, thread->threadId);
3934 dvmDumpThread(thread, true);
3935 LOGW("Found by:\n");
3936 dvmDumpThread(self, false);
3937
3938 /* continue anyway? */
3939 dvmAbort();
3940 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003941
3942 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_THREAD_OBJECT, thread->threadId);
3943
3944 dvmMarkObject(thread->threadObj); // could be NULL, when constructing
3945
3946 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_NATIVE_STACK, thread->threadId);
3947
3948 dvmMarkObject(thread->exception); // usually NULL
3949 gcScanReferenceTable(&thread->internalLocalRefTable);
3950
3951 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_LOCAL, thread->threadId);
3952
Andy McFaddend5ab7262009-08-25 07:19:34 -07003953#ifdef USE_INDIRECT_REF
3954 gcScanIndirectRefTable(&thread->jniLocalRefTable);
3955#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003956 gcScanReferenceTable(&thread->jniLocalRefTable);
Andy McFaddend5ab7262009-08-25 07:19:34 -07003957#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08003958
3959 if (thread->jniMonitorRefTable.table != NULL) {
3960 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_MONITOR, thread->threadId);
3961
3962 gcScanReferenceTable(&thread->jniMonitorRefTable);
3963 }
3964
3965 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JAVA_FRAME, thread->threadId);
3966
3967 gcScanInterpStackReferences(thread);
3968
3969 HPROF_CLEAR_GC_SCAN_STATE();
3970}
3971
3972static void gcScanAllThreads()
3973{
3974 Thread *thread;
3975
3976 /* Lock the thread list so we can safely use the
3977 * next/prev pointers.
3978 */
3979 dvmLockThreadList(dvmThreadSelf());
3980
3981 for (thread = gDvm.threadList; thread != NULL;
3982 thread = thread->next)
3983 {
3984 /* We need to scan our own stack, so don't special-case
3985 * the current thread.
3986 */
3987 gcScanThread(thread);
3988 }
3989
3990 dvmUnlockThreadList();
3991}
3992
3993void dvmGcScanRootThreadGroups()
3994{
3995 /* We scan the VM's list of threads instead of going
3996 * through the actual ThreadGroups, but it should be
3997 * equivalent.
3998 *
Jeff Hao97319a82009-08-12 16:57:15 -07003999 * This assumes that the ThreadGroup class object is in
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08004000 * the root set, which should always be true; it's
4001 * loaded by the built-in class loader, which is part
4002 * of the root set.
4003 */
4004 gcScanAllThreads();
4005}