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