2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #ifndef _DALVIK_THREAD
21 #define _DALVIK_THREAD
24 #include "interp/InterpState.h"
27 #include <cutils/sched_policy.h>
30 #if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
31 /* glibc lacks this unless you #define __USE_UNIX98 */
32 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
33 enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
37 * Current status; these map to JDWP constants, so don't rearrange them.
38 * (If you do alter this, update the strings in dvmDumpThread and the
39 * conversion table in VMThread.java.)
41 * Note that "suspended" is orthogonal to these values (so says JDWP).
43 typedef enum ThreadStatus {
44 THREAD_UNDEFINED = -1, /* makes enum compatible with int32_t */
46 /* these match up with JDWP values */
47 THREAD_ZOMBIE = 0, /* TERMINATED */
48 THREAD_RUNNING = 1, /* RUNNABLE or running now */
49 THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */
50 THREAD_MONITOR = 3, /* BLOCKED on a monitor */
51 THREAD_WAIT = 4, /* WAITING in Object.wait() */
53 THREAD_INITIALIZING = 5, /* allocated, not yet running */
54 THREAD_STARTING = 6, /* started, not yet on thread list */
55 THREAD_NATIVE = 7, /* off in a JNI native method */
56 THREAD_VMWAIT = 8, /* waiting on a VM resource */
57 THREAD_SUSPENDED = 9, /* suspended, usually by GC or debugger */
60 /* thread priorities, from java.lang.Thread */
62 THREAD_MIN_PRIORITY = 1,
63 THREAD_NORM_PRIORITY = 5,
64 THREAD_MAX_PRIORITY = 10,
69 bool dvmThreadStartup(void);
70 void dvmThreadShutdown(void);
71 void dvmSlayDaemons(void);
74 #define kJniLocalRefMin 32
75 #define kJniLocalRefMax 512 /* arbitrary; should be plenty */
76 #define kInternalRefDefault 32 /* equally arbitrary */
77 #define kInternalRefMax 4096 /* mainly a sanity check */
79 #define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
80 #define kDefaultStackSize (16*1024) /* four 4K pages */
81 #define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
84 * Interpreter control struction. Packed into a long long to enable
87 typedef union InterpBreak {
93 int8_t dbgSuspendCount;
94 #ifndef DVM_NO_ASM_INTERP
95 void* curHandlerTable;
103 * Our per-thread data.
105 * These are allocated on the system heap.
107 typedef struct Thread {
109 * Interpreter state which must be preserved across nested
110 * interpreter invocations (via JNI callbacks). Must be the first
113 InterpSaveState interpSave;
115 /* small unique integer; useful for "thin" locks and debug messages */
119 * Begin interpreter state which does not need to be preserved, but should
120 * be located towards the beginning of the Thread structure for
127 /* current limit of stack; flexes for StackOverflowError */
128 const u1* interpStackEnd;
130 /* FP of bottom-most (currently executing) stack frame on interp stack */
132 /* current exception, or NULL if nothing pending */
135 bool debugIsMethodEntry;
136 /* interpreter stack size; our stacks are fixed-length */
138 bool stackOverflowed;
140 /* thread handle, as reported by pthread_self() */
144 * interpBreak contains info about the interpreter mode, as well as
145 * a count of the number of times the thread has been suspended. When
146 * the count drops to zero, the thread resumes.
148 * "dbgSuspendCount" is the portion of the suspend count that the
149 * debugger is responsible for. This has to be tracked separately so
150 * that we can recover correctly if the debugger abruptly disconnects
151 * (suspendCount -= dbgSuspendCount). The debugger should not be able
152 * to resume GC-suspended threads, because we ignore the debugger while
153 * a GC is in progress.
155 * Both of these are guarded by gDvm.threadSuspendCountLock.
157 * Note the non-debug component will rarely be other than 1 or 0 -- (not
158 * sure it's even possible with the way mutexes are currently used.)
160 InterpBreak interpBreak;
163 /* Assembly interpreter handler tables */
164 #ifndef DVM_NO_ASM_INTERP
165 void* mainHandlerTable; // Table of actual instruction handler
166 void* altHandlerTable; // Table of breakout handlers
168 void* unused0; // Consume space to keep offsets
169 void* unused1; // the same between builds with
173 * singleStepCount is a countdown timer used with the breakFlag
174 * kInterpSingleStep. If kInterpSingleStep is set in breakFlags,
175 * singleStepCount will decremented each instruction execution.
176 * Once it reaches zero, the kInterpSingleStep flag in breakFlags
177 * will be cleared. This can be used to temporarily prevent
178 * execution from re-entering JIT'd code or force inter-instruction
179 * checks by delaying the reset of curHandlerTable to mainHandlerTable.
184 struct JitToInterpEntries jitToInterpEntries;
186 * Whether the current top VM frame is in the interpreter or JIT cache:
187 * NULL : in the interpreter
188 * non-NULL: entry address of the JIT'ed code (the actual value doesn't
191 void* inJitCodeCache;
192 unsigned char* pJitProfTable;
194 const void* jitResumeNPC; // Translation return point
195 const u4* jitResumeNSP; // Native SP at return point
196 const u2* jitResumeDPC; // Dalvik inst following single-step
199 const void* pProfileCountdown;
200 const ClassObject* callsiteClass;
201 const Method* methodToCall;
204 /* JNI local reference tracking */
205 IndirectRefTable jniLocalRefTable;
207 #if defined(WITH_JIT)
208 #if defined(WITH_SELF_VERIFICATION)
209 /* Buffer for register state during self verification */
210 struct ShadowSpace* shadowSpace;
213 int totalTraceLen; // Number of Dalvik insts in trace
214 const u2* currTraceHead; // Start of the trace we're building
215 const u2* currRunHead; // Start of run we're building
216 int currRunLen; // Length of run in 16-bit words
217 const u2* lastPC; // Stage the PC for the threaded interpreter
218 const Method* traceMethod; // Starting method of current trace
219 intptr_t threshFilter[JIT_TRACE_THRESH_FILTER_SIZE];
220 JitTraceRun trace[MAX_JIT_RUN_LEN];
224 * Thread's current status. Can only be changed by the thread itself
225 * (i.e. don't mess with this from other threads).
227 volatile ThreadStatus status;
229 /* thread ID, only useful under Linux */
232 /* start (high addr) of interp stack (subtract size to get malloc addr) */
233 u1* interpStackStart;
235 /* the java/lang/Thread that we are associated with */
238 /* the JNIEnv pointer associated with this thread */
241 /* internal reference tracking */
242 ReferenceTable internalLocalRefTable;
245 /* JNI native monitor reference tracking (initialized on first use) */
246 ReferenceTable jniMonitorRefTable;
248 /* hack to make JNI_OnLoad work right */
249 Object* classLoaderOverride;
251 /* mutex to guard the interrupted and the waitMonitor members */
252 pthread_mutex_t waitMutex;
254 /* pointer to the monitor lock we're currently waiting on */
255 /* guarded by waitMutex */
256 /* TODO: consider changing this to Object* for better JDWP interaction */
257 Monitor* waitMonitor;
259 /* thread "interrupted" status; stays raised until queried or thrown */
260 /* guarded by waitMutex */
263 /* links to the next thread in the wait set this thread is part of */
264 struct Thread* waitNext;
266 /* object to sleep on while we are waiting for a monitor */
267 pthread_cond_t waitCond;
270 * Set to true when the thread is in the process of throwing an
275 /* links to rest of thread list; grab global lock before traversing */
279 /* used by threadExitCheck when a thread exits without detaching */
280 int threadExitCheckCount;
282 /* JDWP invoke-during-breakpoint support */
283 DebugInvokeReq invokeReq;
285 /* base time for per-thread CPU timing (used by method profiling) */
286 bool cpuClockBaseSet;
289 /* memory allocation profiling state */
290 AllocProfState allocProf;
292 #ifdef WITH_JNI_STACK_CHECK
296 #if WITH_EXTRA_GC_CHECKS > 1
297 /* PC, saved on every instruction; redundant with StackSaveArea */
298 const u2* currentPc2;
301 /* Safepoint callback state */
302 pthread_mutex_t callbackMutex;
303 SafePointCallback callback;
307 /* start point for an internal thread; mimics pthread args */
308 typedef void* (*InternalThreadStart)(void* arg);
310 /* args for internal thread creation */
311 typedef struct InternalStartArgs {
313 InternalThreadStart func;
319 volatile Thread** pThread;
320 volatile int* pCreateStatus;
324 bool dvmPrepMainForJni(JNIEnv* pEnv);
325 bool dvmPrepMainThread(void);
327 /* utility function to get the tid */
328 pid_t dvmGetSysThreadId(void);
331 * Get our Thread* from TLS.
333 * Returns NULL if this isn't a thread that the VM is aware of.
335 Thread* dvmThreadSelf(void);
337 /* grab the thread list global lock */
338 void dvmLockThreadList(Thread* self);
339 /* try to grab the thread list global lock */
340 bool dvmTryLockThreadList(void);
341 /* release the thread list global lock */
342 void dvmUnlockThreadList(void);
345 * Thread suspend/resume, used by the GC and debugger.
347 typedef enum SuspendCause {
351 SUSPEND_FOR_DEBUG_EVENT,
352 SUSPEND_FOR_STACK_DUMP,
356 #if defined(WITH_JIT)
357 SUSPEND_FOR_TBL_RESIZE, // jit-table resize
358 SUSPEND_FOR_IC_PATCH, // polymorphic callsite inline-cache patch
359 SUSPEND_FOR_CC_RESET, // code-cache reset
360 SUSPEND_FOR_REFRESH, // Reload data cached in interpState
363 void dvmSuspendThread(Thread* thread);
364 void dvmSuspendSelf(bool jdwpActivity);
365 void dvmResumeThread(Thread* thread);
366 void dvmSuspendAllThreads(SuspendCause why);
367 void dvmResumeAllThreads(SuspendCause why);
368 void dvmUndoDebuggerSuspensions(void);
371 * Check suspend state. Grab threadListLock before calling.
373 bool dvmIsSuspended(const Thread* thread);
376 * Wait until a thread has suspended. (Used by debugger support.)
378 void dvmWaitForSuspend(Thread* thread);
381 * Check to see if we should be suspended now. If so, suspend ourselves
382 * by sleeping on a condition variable.
384 bool dvmCheckSuspendPending(Thread* self);
387 * Fast test for use in the interpreter. Returns "true" if our suspend
390 INLINE bool dvmCheckSuspendQuick(Thread* self) {
391 return (self->interpBreak.ctl.breakFlags & kInterpSuspendBreak);
395 * Used when changing thread state. Threads may only change their own.
396 * The "self" argument, which may be NULL, is accepted as an optimization.
398 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
399 * or THREAD_MONITOR), do so in the same function as the wait -- this records
400 * the current stack depth for the GC.
402 * If you're changing to THREAD_RUNNING, this will check for suspension.
404 * Returns the old status.
406 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
409 * Initialize a mutex.
411 INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
414 pthread_mutexattr_t attr;
417 pthread_mutexattr_init(&attr);
418 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
420 pthread_mutex_init(pMutex, &attr);
421 pthread_mutexattr_destroy(&attr);
423 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
428 * Grab a plain mutex.
430 INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
432 int cc __attribute__ ((__unused__)) = pthread_mutex_lock(pMutex);
437 * Try grabbing a plain mutex. Returns 0 if successful.
439 INLINE int dvmTryLockMutex(pthread_mutex_t* pMutex)
441 int cc = pthread_mutex_trylock(pMutex);
442 assert(cc == 0 || cc == EBUSY);
447 * Unlock pthread mutex.
449 INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
451 int cc __attribute__ ((__unused__)) = pthread_mutex_unlock(pMutex);
458 INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
460 int cc __attribute__ ((__unused__)) = pthread_mutex_destroy(pMutex);
464 INLINE void dvmBroadcastCond(pthread_cond_t* pCond)
466 int cc __attribute__ ((__unused__)) = pthread_cond_broadcast(pCond);
470 INLINE void dvmSignalCond(pthread_cond_t* pCond)
472 int cc __attribute__ ((__unused__)) = pthread_cond_signal(pCond);
476 INLINE void dvmWaitCond(pthread_cond_t* pCond, pthread_mutex_t* pMutex)
478 int cc __attribute__ ((__unused__)) = pthread_cond_wait(pCond, pMutex);
483 * Create a thread as a result of java.lang.Thread.start().
485 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
488 * Create a thread internal to the VM. It's visible to interpreted code,
489 * but found in the "system" thread group rather than "main".
491 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
492 InternalThreadStart func, void* funcArg);
495 * Attach or detach the current thread from the VM.
497 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
498 void dvmDetachCurrentThread(void);
501 * Get the "main" or "system" thread group.
503 Object* dvmGetMainThreadGroup(void);
504 Object* dvmGetSystemThreadGroup(void);
507 * Given a java/lang/VMThread object, return our Thread.
509 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
512 * Given a pthread handle, return the associated Thread*.
513 * Caller must hold the thread list lock.
515 * Returns NULL if the thread was not found.
517 Thread* dvmGetThreadByHandle(pthread_t handle);
520 * Given a thread ID, return the associated Thread*.
521 * Caller must hold the thread list lock.
523 * Returns NULL if the thread was not found.
525 Thread* dvmGetThreadByThreadId(u4 threadId);
528 * Sleep in a thread. Returns when the sleep timer returns or the thread
531 void dvmThreadSleep(u8 msec, u4 nsec);
534 * Get the name of a thread. (For safety, hold the thread list lock.)
536 char* dvmGetThreadName(Thread* thread);
539 * Convert ThreadStatus to a string.
541 const char* dvmGetThreadStatusStr(ThreadStatus status);
544 * Return true if a thread is on the internal list. If it is, the
545 * thread is part of the GC's root set.
547 bool dvmIsOnThreadList(const Thread* thread);
550 * Get/set the JNIEnv field.
552 INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
553 INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
556 * Update the priority value of the underlying pthread.
558 void dvmChangeThreadPriority(Thread* thread, int newPriority);
560 /* "change flags" values for raise/reset thread priority calls */
561 #define kChangedPriority 0x01
562 #define kChangedPolicy 0x02
565 * If necessary, raise the thread's priority to nice=0 cgroup=fg.
567 * Returns bit flags indicating changes made (zero if nothing was done).
569 int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
570 SchedPolicy* pSavedThreadPolicy);
573 * Drop the thread priority to what it was before an earlier call to
574 * dvmRaiseThreadPriorityIfNeeded().
576 void dvmResetThreadPriority(Thread* thread, int changeFlags,
577 int savedThreadPrio, SchedPolicy savedThreadPolicy);
580 * Debug: dump information about a single thread.
582 void dvmDumpThread(Thread* thread, bool isRunning);
583 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
587 * Debug: dump information about all threads.
589 void dvmDumpAllThreads(bool grabLock);
590 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
593 * Debug: kill a thread to get a debuggerd stack trace. Leaves the VM
594 * in an uncertain state.
596 void dvmNukeThread(Thread* thread);
598 #endif /*_DALVIK_THREAD*/