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.
19 #ifndef _DALVIK_THREAD
20 #define _DALVIK_THREAD
24 #if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
25 /* Linux lacks this unless you #define __USE_UNIX98 */
26 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
27 enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
30 #ifdef WITH_MONITOR_TRACKING
31 struct LockedObjectData;
35 * Current status; these map to JDWP constants, so don't rearrange them.
36 * (If you do alter this, update the strings in dvmDumpThread and the
37 * conversion table in VMThread.java.)
39 * Note that "suspended" is orthogonal to these values (so says JDWP).
41 typedef enum ThreadStatus {
42 /* these match up with JDWP values */
43 THREAD_ZOMBIE = 0, /* TERMINATED */
44 THREAD_RUNNING = 1, /* RUNNABLE or running now */
45 THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */
46 THREAD_MONITOR = 3, /* BLOCKED on a monitor */
47 THREAD_WAIT = 4, /* WAITING in Object.wait() */
49 THREAD_INITIALIZING = 5, /* allocated, not yet running */
50 THREAD_STARTING = 6, /* started, not yet on thread list */
51 THREAD_NATIVE = 7, /* off in a JNI native method */
52 THREAD_VMWAIT = 8, /* waiting on a VM resource */
55 /* thread priorities, from java.lang.Thread */
57 THREAD_MIN_PRIORITY = 1,
58 THREAD_NORM_PRIORITY = 5,
59 THREAD_MAX_PRIORITY = 10,
64 bool dvmThreadStartup(void);
65 bool dvmThreadObjStartup(void);
66 void dvmThreadShutdown(void);
67 void dvmSlayDaemons(void);
70 #define kJniLocalRefMax 512 /* arbitrary; should be plenty */
71 #define kInternalRefDefault 32 /* equally arbitrary */
72 #define kInternalRefMax 4096 /* mainly a sanity check */
74 #define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
75 #define kDefaultStackSize (12*1024) /* three 4K pages */
76 #define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
79 * Our per-thread data.
81 * These are allocated on the system heap.
83 typedef struct Thread {
84 /* small unique integer; useful for "thin" locks and debug messages */
88 * Thread's current status. Can only be changed by the thread itself
89 * (i.e. don't mess with this from other threads).
94 * This is the number of times the thread has been suspended. When the
95 * count drops to zero, the thread resumes.
97 * "dbgSuspendCount" is the portion of the suspend count that the
98 * debugger is responsible for. This has to be tracked separately so
99 * that we can recover correctly if the debugger abruptly disconnects
100 * (suspendCount -= dbgSuspendCount). The debugger should not be able
101 * to resume GC-suspended threads, because we ignore the debugger while
102 * a GC is in progress.
104 * Both of these are guarded by gDvm.threadSuspendCountLock.
106 * (We could store both of these in the same 32-bit, using 16-bit
107 * halves, to make atomic ops possible. In practice, you only need
108 * to read suspendCount, and we need to hold a mutex when making
109 * changes, so there's no need to merge them. Note the non-debug
110 * component will rarely be other than 1 or 0 -- not sure it's even
111 * possible with the way mutexes are currently used.)
117 * Set to true when the thread suspends itself, false when it wakes up.
118 * This is only expected to be set when status==THREAD_RUNNING.
122 /* thread handle, as reported by pthread_self() */
125 /* thread ID, only useful under Linux */
128 /* start (high addr) of interp stack (subtract size to get malloc addr) */
129 u1* interpStackStart;
131 /* current limit of stack; flexes for StackOverflowError */
132 const u1* interpStackEnd;
134 /* interpreter stack size; our stacks are fixed-length */
136 bool stackOverflowed;
138 /* FP of bottom-most (currently executing) stack frame on interp stack */
141 /* current exception, or NULL if nothing pending */
144 /* the java/lang/Thread that we are associated with */
147 /* the JNIEnv pointer associated with this thread */
150 /* internal reference tracking */
151 ReferenceTable internalLocalRefTable;
153 /* JNI local reference tracking */
154 // TODO: move this to JNIEnvExt to avoid an indirection?
155 ReferenceTable jniLocalRefTable;
157 /* JNI native monitor reference tracking (initialized on first use) */
158 ReferenceTable jniMonitorRefTable;
160 /* hack to make JNI_OnLoad work right */
161 Object* classLoaderOverride;
163 /* pointer to the monitor lock we're currently waiting on */
164 /* (do not set or clear unless the Monitor itself is held) */
165 /* TODO: consider changing this to Object* for better JDWP interaction */
166 Monitor* waitMonitor;
167 /* set when we confirm that the thread must be interrupted from a wait */
168 bool interruptingWait;
169 /* thread "interrupted" status; stays raised until queried or thrown */
173 * Set to true when the thread is in the process of throwing an
178 /* links to rest of thread list; grab global lock before traversing */
182 /* JDWP invoke-during-breakpoint support */
183 DebugInvokeReq invokeReq;
185 #ifdef WITH_MONITOR_TRACKING
186 /* objects locked by this thread; most recent is at head of list */
187 struct LockedObjectData* pLockedObjects;
190 #ifdef WITH_ALLOC_LIMITS
191 /* allocation limit, for Debug.setAllocationLimit() regression testing */
196 /* base time for per-thread CPU timing */
197 bool cpuClockBaseSet;
200 /* memory allocation profiling state */
201 AllocProfState allocProf;
204 #ifdef WITH_JNI_STACK_CHECK
208 #if WITH_EXTRA_GC_CHECKS > 1
209 /* PC, saved on every instruction; redundant with StackSaveArea */
210 const u2* currentPc2;
214 /* start point for an internal thread; mimics pthread args */
215 typedef void* (*InternalThreadStart)(void* arg);
217 /* args for internal thread creation */
218 typedef struct InternalStartArgs {
220 InternalThreadStart func;
226 volatile Thread** pThread;
227 volatile int* pCreateStatus;
231 bool dvmPrepMainForJni(JNIEnv* pEnv);
232 bool dvmPrepMainThread(void);
234 /* utility function to get the tid */
235 pid_t dvmGetSysThreadId(void);
238 * Get our Thread* from TLS.
240 * Returns NULL if this isn't a thread that the VM is aware of.
242 Thread* dvmThreadSelf(void);
244 /* grab the thread list global lock */
245 void dvmLockThreadList(Thread* self);
246 /* release the thread list global lock */
247 void dvmUnlockThreadList(void);
250 * Thread suspend/resume, used by the GC and debugger.
252 typedef enum SuspendCause {
256 SUSPEND_FOR_DEBUG_EVENT,
257 SUSPEND_FOR_STACK_DUMP,
259 #if defined(WITH_JIT)
263 void dvmSuspendThread(Thread* thread);
264 void dvmSuspendSelf(bool jdwpActivity);
265 void dvmResumeThread(Thread* thread);
266 void dvmSuspendAllThreads(SuspendCause why);
267 void dvmResumeAllThreads(SuspendCause why);
268 void dvmUndoDebuggerSuspensions(void);
271 * Check suspend state. Grab threadListLock before calling.
273 bool dvmIsSuspended(Thread* thread);
276 * Wait until a thread has suspended. (Used by debugger support.)
278 void dvmWaitForSuspend(Thread* thread);
281 * Check to see if we should be suspended now. If so, suspend ourselves
282 * by sleeping on a condition variable.
284 * If "self" is NULL, this will use dvmThreadSelf().
286 bool dvmCheckSuspendPending(Thread* self);
289 * Fast test for use in the interpreter. Returns "true" if our suspend
292 INLINE bool dvmCheckSuspendQuick(Thread* self) {
293 return (self->suspendCount != 0);
297 * Used when changing thread state. Threads may only change their own.
298 * The "self" argument, which may be NULL, is accepted as an optimization.
300 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
301 * or THREAD_MONITOR), do so in the same function as the wait -- this records
302 * the current stack depth for the GC.
304 * If you're changing to THREAD_RUNNING, this will check for suspension.
306 * Returns the old status.
308 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
311 * Initialize a mutex.
313 INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
316 pthread_mutexattr_t attr;
319 pthread_mutexattr_init(&attr);
320 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
322 pthread_mutex_init(pMutex, &attr);
323 pthread_mutexattr_destroy(&attr);
325 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
330 * Grab a plain mutex.
332 INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
334 int cc = pthread_mutex_lock(pMutex);
339 * Unlock pthread mutex.
341 INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
343 int cc = pthread_mutex_unlock(pMutex);
350 INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
352 int cc = pthread_mutex_destroy(pMutex);
357 * Create a thread as a result of java.lang.Thread.start().
359 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
362 * Create a thread internal to the VM. It's visible to interpreted code,
363 * but found in the "system" thread group rather than "main".
365 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
366 InternalThreadStart func, void* funcArg);
369 * Attach or detach the current thread from the VM.
371 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
372 void dvmDetachCurrentThread(void);
375 * Get the "main" or "system" thread group.
377 Object* dvmGetMainThreadGroup(void);
378 Object* dvmGetSystemThreadGroup(void);
381 * Given a java/lang/VMThread object, return our Thread.
383 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
386 * Sleep in a thread. Returns when the sleep timer returns or the thread
389 void dvmThreadSleep(u8 msec, u4 nsec);
392 * Get the name of a thread. (For safety, hold the thread list lock.)
394 char* dvmGetThreadName(Thread* thread);
397 * Return true if a thread is on the internal list. If it is, the
398 * thread is part of the GC's root set.
400 bool dvmIsOnThreadList(const Thread* thread);
403 * Get/set the JNIEnv field.
405 INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
406 INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
409 * Change the scheduler group of the current process
411 int dvmChangeThreadSchedulerGroup(const char *group);
414 * Update the priority value of the underlying pthread.
416 void dvmChangeThreadPriority(Thread* thread, int newPriority);
420 * Debug: dump information about a single thread.
422 void dvmDumpThread(Thread* thread, bool isRunning);
423 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
427 * Debug: dump information about all threads.
429 void dvmDumpAllThreads(bool grabLock);
430 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
433 #ifdef WITH_MONITOR_TRACKING
435 * Track locks held by the current thread, along with the stack trace at
436 * the point the lock was acquired.
438 * At any given time the number of locks held across the VM should be
439 * fairly small, so there's no reason not to generate and store the entire
442 typedef struct LockedObjectData {
443 /* the locked object */
446 /* number of times it has been locked recursively (zero-based ref count) */
449 /* stack trace at point of initial acquire */
453 struct LockedObjectData* next;
457 * Add/remove/find objects from the thread's monitor list.
459 void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
460 void dvmRemoveFromMonitorList(Thread* self, Object* obj);
461 LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
464 #endif /*_DALVIK_THREAD*/