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