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