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