blob: bcd85a918947c5c67f2ca0a27c241c671483b6e3 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Andy McFadden0083d372009-08-21 14:44:04 -070016
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080017/*
18 * VM thread support.
19 */
20#ifndef _DALVIK_THREAD
21#define _DALVIK_THREAD
22
23#include "jni.h"
24
Carl Shapiro980ffb02010-03-13 22:34:01 -080025#include <errno.h>
Andy McFadden2b94b302010-03-09 16:38:36 -080026#include <cutils/sched_policy.h>
27
28
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080029#if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
Andy McFadden0083d372009-08-21 14:44:04 -070030/* glibc lacks this unless you #define __USE_UNIX98 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080031int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
32enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
33#endif
34
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080035/*
36 * Current status; these map to JDWP constants, so don't rearrange them.
37 * (If you do alter this, update the strings in dvmDumpThread and the
38 * conversion table in VMThread.java.)
39 *
40 * Note that "suspended" is orthogonal to these values (so says JDWP).
41 */
42typedef enum ThreadStatus {
Andy McFaddenb5f3c0b2010-08-23 16:45:24 -070043 THREAD_UNDEFINED = -1, /* makes enum compatible with int32_t */
Andy McFaddenab227f72010-04-06 12:37:48 -070044
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080045 /* these match up with JDWP values */
46 THREAD_ZOMBIE = 0, /* TERMINATED */
47 THREAD_RUNNING = 1, /* RUNNABLE or running now */
48 THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */
49 THREAD_MONITOR = 3, /* BLOCKED on a monitor */
50 THREAD_WAIT = 4, /* WAITING in Object.wait() */
51 /* non-JDWP states */
52 THREAD_INITIALIZING = 5, /* allocated, not yet running */
53 THREAD_STARTING = 6, /* started, not yet on thread list */
54 THREAD_NATIVE = 7, /* off in a JNI native method */
55 THREAD_VMWAIT = 8, /* waiting on a VM resource */
Andy McFaddenb5f3c0b2010-08-23 16:45:24 -070056 THREAD_SUSPENDED = 9, /* suspended, usually by GC or debugger */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080057} ThreadStatus;
58
59/* thread priorities, from java.lang.Thread */
60enum {
61 THREAD_MIN_PRIORITY = 1,
62 THREAD_NORM_PRIORITY = 5,
63 THREAD_MAX_PRIORITY = 10,
64};
65
66
67/* initialization */
68bool dvmThreadStartup(void);
69bool dvmThreadObjStartup(void);
70void dvmThreadShutdown(void);
71void dvmSlayDaemons(void);
72
73
Andy McFaddend5ab7262009-08-25 07:19:34 -070074#define kJniLocalRefMin 32
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080075#define kJniLocalRefMax 512 /* arbitrary; should be plenty */
76#define kInternalRefDefault 32 /* equally arbitrary */
77#define kInternalRefMax 4096 /* mainly a sanity check */
78
79#define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
Andy McFadden80e8d7f2011-01-25 12:26:41 -080080#define kDefaultStackSize (16*1024) /* four 4K pages */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080081#define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
82
83/*
84 * Our per-thread data.
85 *
86 * These are allocated on the system heap.
87 */
88typedef struct Thread {
89 /* small unique integer; useful for "thin" locks and debug messages */
90 u4 threadId;
91
92 /*
93 * Thread's current status. Can only be changed by the thread itself
94 * (i.e. don't mess with this from other threads).
95 */
Bob Lee9dc72a32009-09-04 18:28:16 -070096 volatile ThreadStatus status;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080097
98 /*
99 * This is the number of times the thread has been suspended. When the
100 * count drops to zero, the thread resumes.
101 *
102 * "dbgSuspendCount" is the portion of the suspend count that the
103 * debugger is responsible for. This has to be tracked separately so
104 * that we can recover correctly if the debugger abruptly disconnects
105 * (suspendCount -= dbgSuspendCount). The debugger should not be able
106 * to resume GC-suspended threads, because we ignore the debugger while
107 * a GC is in progress.
108 *
109 * Both of these are guarded by gDvm.threadSuspendCountLock.
110 *
111 * (We could store both of these in the same 32-bit, using 16-bit
112 * halves, to make atomic ops possible. In practice, you only need
113 * to read suspendCount, and we need to hold a mutex when making
114 * changes, so there's no need to merge them. Note the non-debug
115 * component will rarely be other than 1 or 0 -- not sure it's even
116 * possible with the way mutexes are currently used.)
117 */
118 int suspendCount;
119 int dbgSuspendCount;
120
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800121 /* thread handle, as reported by pthread_self() */
122 pthread_t handle;
123
124 /* thread ID, only useful under Linux */
125 pid_t systemTid;
126
127 /* start (high addr) of interp stack (subtract size to get malloc addr) */
128 u1* interpStackStart;
129
130 /* current limit of stack; flexes for StackOverflowError */
131 const u1* interpStackEnd;
132
133 /* interpreter stack size; our stacks are fixed-length */
134 int interpStackSize;
135 bool stackOverflowed;
136
137 /* FP of bottom-most (currently executing) stack frame on interp stack */
138 void* curFrame;
139
140 /* current exception, or NULL if nothing pending */
141 Object* exception;
142
143 /* the java/lang/Thread that we are associated with */
144 Object* threadObj;
145
146 /* the JNIEnv pointer associated with this thread */
147 JNIEnv* jniEnv;
148
149 /* internal reference tracking */
150 ReferenceTable internalLocalRefTable;
151
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800152#if defined(WITH_JIT)
153 /*
154 * Whether the current top VM frame is in the interpreter or JIT cache:
155 * NULL : in the interpreter
156 * non-NULL: entry address of the JIT'ed code (the actual value doesn't
157 * matter)
158 */
159 void* inJitCodeCache;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700160#if defined(WITH_SELF_VERIFICATION)
161 /* Buffer for register state during self verification */
162 struct ShadowSpace* shadowSpace;
163#endif
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800164#endif
165
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800166 /* JNI local reference tracking */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700167#ifdef USE_INDIRECT_REF
168 IndirectRefTable jniLocalRefTable;
169#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800170 ReferenceTable jniLocalRefTable;
Andy McFaddend5ab7262009-08-25 07:19:34 -0700171#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800172
173 /* JNI native monitor reference tracking (initialized on first use) */
174 ReferenceTable jniMonitorRefTable;
175
176 /* hack to make JNI_OnLoad work right */
177 Object* classLoaderOverride;
178
Carl Shapirob4539192010-01-04 16:50:00 -0800179 /* mutex to guard the interrupted and the waitMonitor members */
180 pthread_mutex_t waitMutex;
181
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800182 /* pointer to the monitor lock we're currently waiting on */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800183 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800184 /* TODO: consider changing this to Object* for better JDWP interaction */
185 Monitor* waitMonitor;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800186
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800187 /* thread "interrupted" status; stays raised until queried or thrown */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800188 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800189 bool interrupted;
190
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800191 /* links to the next thread in the wait set this thread is part of */
192 struct Thread* waitNext;
193
194 /* object to sleep on while we are waiting for a monitor */
195 pthread_cond_t waitCond;
196
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800197 /*
198 * Set to true when the thread is in the process of throwing an
199 * OutOfMemoryError.
200 */
201 bool throwingOOME;
202
203 /* links to rest of thread list; grab global lock before traversing */
204 struct Thread* prev;
205 struct Thread* next;
206
Andy McFadden909ce242009-12-10 16:38:30 -0800207 /* used by threadExitCheck when a thread exits without detaching */
208 int threadExitCheckCount;
209
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800210 /* JDWP invoke-during-breakpoint support */
211 DebugInvokeReq invokeReq;
212
Andy McFadden0d615c32010-08-18 12:19:51 -0700213 /* base time for per-thread CPU timing (used by method profiling) */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800214 bool cpuClockBaseSet;
215 u8 cpuClockBase;
216
217 /* memory allocation profiling state */
218 AllocProfState allocProf;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800219
220#ifdef WITH_JNI_STACK_CHECK
221 u4 stackCrc;
222#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700223
224#if WITH_EXTRA_GC_CHECKS > 1
225 /* PC, saved on every instruction; redundant with StackSaveArea */
226 const u2* currentPc2;
227#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800228} Thread;
229
230/* start point for an internal thread; mimics pthread args */
231typedef void* (*InternalThreadStart)(void* arg);
232
233/* args for internal thread creation */
234typedef struct InternalStartArgs {
235 /* inputs */
236 InternalThreadStart func;
237 void* funcArg;
238 char* name;
239 Object* group;
240 bool isDaemon;
241 /* result */
242 volatile Thread** pThread;
243 volatile int* pCreateStatus;
244} InternalStartArgs;
245
246/* finish init */
247bool dvmPrepMainForJni(JNIEnv* pEnv);
248bool dvmPrepMainThread(void);
249
250/* utility function to get the tid */
251pid_t dvmGetSysThreadId(void);
252
253/*
254 * Get our Thread* from TLS.
255 *
256 * Returns NULL if this isn't a thread that the VM is aware of.
257 */
258Thread* dvmThreadSelf(void);
259
260/* grab the thread list global lock */
261void dvmLockThreadList(Thread* self);
Andy McFaddend19988d2010-10-22 13:32:12 -0700262/* try to grab the thread list global lock */
263bool dvmTryLockThreadList(void);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800264/* release the thread list global lock */
265void dvmUnlockThreadList(void);
266
267/*
268 * Thread suspend/resume, used by the GC and debugger.
269 */
270typedef enum SuspendCause {
271 SUSPEND_NOT = 0,
272 SUSPEND_FOR_GC,
273 SUSPEND_FOR_DEBUG,
274 SUSPEND_FOR_DEBUG_EVENT,
275 SUSPEND_FOR_STACK_DUMP,
276 SUSPEND_FOR_DEX_OPT,
Carl Shapiro1e714bb2010-03-16 03:26:49 -0700277 SUSPEND_FOR_VERIFY,
Carl Shapiro07018e22010-10-26 21:07:41 -0700278 SUSPEND_FOR_HPROF,
Bill Buzbee27176222009-06-09 09:20:16 -0700279#if defined(WITH_JIT)
Ben Cheng60c24f42010-01-04 12:29:56 -0800280 SUSPEND_FOR_TBL_RESIZE, // jit-table resize
281 SUSPEND_FOR_IC_PATCH, // polymorphic callsite inline-cache patch
282 SUSPEND_FOR_CC_RESET, // code-cache reset
Bill Buzbee964a7b02010-01-28 12:54:19 -0800283 SUSPEND_FOR_REFRESH, // Reload data cached in interpState
Bill Buzbee27176222009-06-09 09:20:16 -0700284#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800285} SuspendCause;
286void dvmSuspendThread(Thread* thread);
287void dvmSuspendSelf(bool jdwpActivity);
288void dvmResumeThread(Thread* thread);
289void dvmSuspendAllThreads(SuspendCause why);
290void dvmResumeAllThreads(SuspendCause why);
291void dvmUndoDebuggerSuspensions(void);
292
293/*
294 * Check suspend state. Grab threadListLock before calling.
295 */
Andy McFadden3469a7e2010-08-04 16:09:10 -0700296bool dvmIsSuspended(const Thread* thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800297
298/*
299 * Wait until a thread has suspended. (Used by debugger support.)
300 */
301void dvmWaitForSuspend(Thread* thread);
302
303/*
304 * Check to see if we should be suspended now. If so, suspend ourselves
305 * by sleeping on a condition variable.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800306 */
307bool dvmCheckSuspendPending(Thread* self);
308
309/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700310 * Fast test for use in the interpreter. Returns "true" if our suspend
311 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800312 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700313INLINE bool dvmCheckSuspendQuick(Thread* self) {
314 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800315}
316
317/*
318 * Used when changing thread state. Threads may only change their own.
319 * The "self" argument, which may be NULL, is accepted as an optimization.
320 *
321 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
322 * or THREAD_MONITOR), do so in the same function as the wait -- this records
323 * the current stack depth for the GC.
324 *
325 * If you're changing to THREAD_RUNNING, this will check for suspension.
326 *
327 * Returns the old status.
328 */
329ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
330
331/*
332 * Initialize a mutex.
333 */
334INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
335{
336#ifdef CHECK_MUTEX
337 pthread_mutexattr_t attr;
338 int cc;
339
340 pthread_mutexattr_init(&attr);
341 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
342 assert(cc == 0);
343 pthread_mutex_init(pMutex, &attr);
344 pthread_mutexattr_destroy(&attr);
345#else
346 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
347#endif
348}
349
350/*
351 * Grab a plain mutex.
352 */
353INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
354{
Carl Shapirob31b3012010-05-25 18:35:37 -0700355 int cc __attribute__ ((__unused__)) = pthread_mutex_lock(pMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800356 assert(cc == 0);
357}
358
359/*
Bill Buzbee964a7b02010-01-28 12:54:19 -0800360 * Try grabbing a plain mutex. Returns 0 if successful.
361 */
362INLINE int dvmTryLockMutex(pthread_mutex_t* pMutex)
363{
Carl Shapiro980ffb02010-03-13 22:34:01 -0800364 int cc = pthread_mutex_trylock(pMutex);
365 assert(cc == 0 || cc == EBUSY);
366 return cc;
Bill Buzbee964a7b02010-01-28 12:54:19 -0800367}
368
369/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800370 * Unlock pthread mutex.
371 */
372INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
373{
Carl Shapirob31b3012010-05-25 18:35:37 -0700374 int cc __attribute__ ((__unused__)) = pthread_mutex_unlock(pMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800375 assert(cc == 0);
376}
377
378/*
379 * Destroy a mutex.
380 */
381INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
382{
Carl Shapirob31b3012010-05-25 18:35:37 -0700383 int cc __attribute__ ((__unused__)) = pthread_mutex_destroy(pMutex);
384 assert(cc == 0);
385}
386
387INLINE void dvmBroadcastCond(pthread_cond_t* pCond)
388{
389 int cc __attribute__ ((__unused__)) = pthread_cond_broadcast(pCond);
390 assert(cc == 0);
391}
392
393INLINE void dvmSignalCond(pthread_cond_t* pCond)
394{
395 int cc __attribute__ ((__unused__)) = pthread_cond_signal(pCond);
396 assert(cc == 0);
397}
398
399INLINE void dvmWaitCond(pthread_cond_t* pCond, pthread_mutex_t* pMutex)
400{
401 int cc __attribute__ ((__unused__)) = pthread_cond_wait(pCond, pMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800402 assert(cc == 0);
403}
404
405/*
406 * Create a thread as a result of java.lang.Thread.start().
407 */
408bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
409
410/*
411 * Create a thread internal to the VM. It's visible to interpreted code,
412 * but found in the "system" thread group rather than "main".
413 */
414bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
415 InternalThreadStart func, void* funcArg);
416
417/*
418 * Attach or detach the current thread from the VM.
419 */
420bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
421void dvmDetachCurrentThread(void);
422
423/*
424 * Get the "main" or "system" thread group.
425 */
426Object* dvmGetMainThreadGroup(void);
427Object* dvmGetSystemThreadGroup(void);
428
429/*
430 * Given a java/lang/VMThread object, return our Thread.
431 */
432Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
433
434/*
Andy McFadden2b94b302010-03-09 16:38:36 -0800435 * Given a pthread handle, return the associated Thread*.
Andy McFaddenfd542662010-03-12 13:39:59 -0800436 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -0800437 *
438 * Returns NULL if the thread was not found.
439 */
440Thread* dvmGetThreadByHandle(pthread_t handle);
441
442/*
Andy McFaddenfd542662010-03-12 13:39:59 -0800443 * Given a thread ID, return the associated Thread*.
444 * Caller must hold the thread list lock.
445 *
446 * Returns NULL if the thread was not found.
447 */
448Thread* dvmGetThreadByThreadId(u4 threadId);
449
450/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800451 * Sleep in a thread. Returns when the sleep timer returns or the thread
452 * is interrupted.
453 */
454void dvmThreadSleep(u8 msec, u4 nsec);
455
456/*
457 * Get the name of a thread. (For safety, hold the thread list lock.)
458 */
459char* dvmGetThreadName(Thread* thread);
460
461/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800462 * Convert ThreadStatus to a string.
463 */
464const char* dvmGetThreadStatusStr(ThreadStatus status);
465
466/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800467 * Return true if a thread is on the internal list. If it is, the
468 * thread is part of the GC's root set.
469 */
470bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700471
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800472/*
473 * Get/set the JNIEnv field.
474 */
475INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
476INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
477
478/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800479 * Update the priority value of the underlying pthread.
480 */
481void dvmChangeThreadPriority(Thread* thread, int newPriority);
482
Andy McFadden2b94b302010-03-09 16:38:36 -0800483/* "change flags" values for raise/reset thread priority calls */
484#define kChangedPriority 0x01
485#define kChangedPolicy 0x02
486
487/*
488 * If necessary, raise the thread's priority to nice=0 cgroup=fg.
489 *
490 * Returns bit flags indicating changes made (zero if nothing was done).
491 */
492int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
493 SchedPolicy* pSavedThreadPolicy);
494
495/*
496 * Drop the thread priority to what it was before an earlier call to
497 * dvmRaiseThreadPriorityIfNeeded().
498 */
499void dvmResetThreadPriority(Thread* thread, int changeFlags,
500 int savedThreadPrio, SchedPolicy savedThreadPolicy);
501
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800502/*
503 * Debug: dump information about a single thread.
504 */
505void dvmDumpThread(Thread* thread, bool isRunning);
506void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
507 bool isRunning);
508
509/*
510 * Debug: dump information about all threads.
511 */
512void dvmDumpAllThreads(bool grabLock);
513void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
514
Andy McFadden384ef6b2010-03-15 17:24:55 -0700515/*
516 * Debug: kill a thread to get a debuggerd stack trace. Leaves the VM
517 * in an uncertain state.
518 */
519void dvmNukeThread(Thread* thread);
520
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800521#endif /*_DALVIK_THREAD*/