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