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