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