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