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