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
25 #if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
26 /* glibc lacks this unless you #define __USE_UNIX98 */
27 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
28 enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
31 #ifdef WITH_MONITOR_TRACKING
32 struct LockedObjectData;
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.)
40 * Note that "suspended" is orthogonal to these values (so says JDWP).
42 typedef enum ThreadStatus {
43 /* these match up with JDWP values */
44 THREAD_ZOMBIE = 0, /* TERMINATED */
45 THREAD_RUNNING = 1, /* RUNNABLE or running now */
46 THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */
47 THREAD_MONITOR = 3, /* BLOCKED on a monitor */
48 THREAD_WAIT = 4, /* WAITING in Object.wait() */
50 THREAD_INITIALIZING = 5, /* allocated, not yet running */
51 THREAD_STARTING = 6, /* started, not yet on thread list */
52 THREAD_NATIVE = 7, /* off in a JNI native method */
53 THREAD_VMWAIT = 8, /* waiting on a VM resource */
56 /* thread priorities, from java.lang.Thread */
58 THREAD_MIN_PRIORITY = 1,
59 THREAD_NORM_PRIORITY = 5,
60 THREAD_MAX_PRIORITY = 10,
65 bool dvmThreadStartup(void);
66 bool dvmThreadObjStartup(void);
67 void dvmThreadShutdown(void);
68 void dvmSlayDaemons(void);
71 #define kJniLocalRefMin 32
72 #define kJniLocalRefMax 512 /* arbitrary; should be plenty */
73 #define kInternalRefDefault 32 /* equally arbitrary */
74 #define kInternalRefMax 4096 /* mainly a sanity check */
76 #define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
77 #define kDefaultStackSize (12*1024) /* three 4K pages */
78 #define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
81 * System thread state. See native/SystemThread.h.
83 typedef struct SystemThread SystemThread;
86 * Our per-thread data.
88 * These are allocated on the system heap.
90 typedef struct Thread {
91 /* small unique integer; useful for "thin" locks and debug messages */
95 * Thread's current status. Can only be changed by the thread itself
96 * (i.e. don't mess with this from other threads).
98 volatile ThreadStatus status;
101 * This is the number of times the thread has been suspended. When the
102 * count drops to zero, the thread resumes.
104 * "dbgSuspendCount" is the portion of the suspend count that the
105 * debugger is responsible for. This has to be tracked separately so
106 * that we can recover correctly if the debugger abruptly disconnects
107 * (suspendCount -= dbgSuspendCount). The debugger should not be able
108 * to resume GC-suspended threads, because we ignore the debugger while
109 * a GC is in progress.
111 * Both of these are guarded by gDvm.threadSuspendCountLock.
113 * (We could store both of these in the same 32-bit, using 16-bit
114 * halves, to make atomic ops possible. In practice, you only need
115 * to read suspendCount, and we need to hold a mutex when making
116 * changes, so there's no need to merge them. Note the non-debug
117 * component will rarely be other than 1 or 0 -- not sure it's even
118 * possible with the way mutexes are currently used.)
124 * Set to true when the thread suspends itself, false when it wakes up.
125 * This is only expected to be set when status==THREAD_RUNNING.
129 /* thread handle, as reported by pthread_self() */
132 /* thread ID, only useful under Linux */
135 /* start (high addr) of interp stack (subtract size to get malloc addr) */
136 u1* interpStackStart;
138 /* current limit of stack; flexes for StackOverflowError */
139 const u1* interpStackEnd;
141 /* interpreter stack size; our stacks are fixed-length */
143 bool stackOverflowed;
145 /* FP of bottom-most (currently executing) stack frame on interp stack */
148 /* current exception, or NULL if nothing pending */
151 /* the java/lang/Thread that we are associated with */
154 /* the JNIEnv pointer associated with this thread */
157 /* internal reference tracking */
158 ReferenceTable internalLocalRefTable;
160 /* JNI local reference tracking */
161 #ifdef USE_INDIRECT_REF
162 IndirectRefTable jniLocalRefTable;
164 ReferenceTable jniLocalRefTable;
167 /* JNI native monitor reference tracking (initialized on first use) */
168 ReferenceTable jniMonitorRefTable;
170 /* hack to make JNI_OnLoad work right */
171 Object* classLoaderOverride;
173 /* pointer to the monitor lock we're currently waiting on */
174 /* (do not set or clear unless the Monitor itself is held) */
175 /* TODO: consider changing this to Object* for better JDWP interaction */
176 Monitor* waitMonitor;
177 /* set when we confirm that the thread must be interrupted from a wait */
178 bool interruptingWait;
179 /* thread "interrupted" status; stays raised until queried or thrown */
183 * Set to true when the thread is in the process of throwing an
188 /* links to rest of thread list; grab global lock before traversing */
192 /* JDWP invoke-during-breakpoint support */
193 DebugInvokeReq invokeReq;
195 #ifdef WITH_MONITOR_TRACKING
196 /* objects locked by this thread; most recent is at head of list */
197 struct LockedObjectData* pLockedObjects;
200 #ifdef WITH_ALLOC_LIMITS
201 /* allocation limit, for Debug.setAllocationLimit() regression testing */
206 /* base time for per-thread CPU timing */
207 bool cpuClockBaseSet;
210 /* memory allocation profiling state */
211 AllocProfState allocProf;
214 #ifdef WITH_JNI_STACK_CHECK
218 #if WITH_EXTRA_GC_CHECKS > 1
219 /* PC, saved on every instruction; redundant with StackSaveArea */
220 const u2* currentPc2;
223 /* system thread state */
224 SystemThread* systemThread;
227 /* start point for an internal thread; mimics pthread args */
228 typedef void* (*InternalThreadStart)(void* arg);
230 /* args for internal thread creation */
231 typedef struct InternalStartArgs {
233 InternalThreadStart func;
239 volatile Thread** pThread;
240 volatile int* pCreateStatus;
244 bool dvmPrepMainForJni(JNIEnv* pEnv);
245 bool dvmPrepMainThread(void);
247 /* utility function to get the tid */
248 pid_t dvmGetSysThreadId(void);
251 * Get our Thread* from TLS.
253 * Returns NULL if this isn't a thread that the VM is aware of.
255 Thread* dvmThreadSelf(void);
257 /* grab the thread list global lock */
258 void dvmLockThreadList(Thread* self);
259 /* release the thread list global lock */
260 void dvmUnlockThreadList(void);
263 * Thread suspend/resume, used by the GC and debugger.
265 typedef enum SuspendCause {
269 SUSPEND_FOR_DEBUG_EVENT,
270 SUSPEND_FOR_STACK_DUMP,
272 #if defined(WITH_JIT)
276 void dvmSuspendThread(Thread* thread);
277 void dvmSuspendSelf(bool jdwpActivity);
278 void dvmResumeThread(Thread* thread);
279 void dvmSuspendAllThreads(SuspendCause why);
280 void dvmResumeAllThreads(SuspendCause why);
281 void dvmUndoDebuggerSuspensions(void);
284 * Check suspend state. Grab threadListLock before calling.
286 bool dvmIsSuspended(Thread* thread);
289 * Wait until a thread has suspended. (Used by debugger support.)
291 void dvmWaitForSuspend(Thread* thread);
294 * Check to see if we should be suspended now. If so, suspend ourselves
295 * by sleeping on a condition variable.
297 * If "self" is NULL, this will use dvmThreadSelf().
299 bool dvmCheckSuspendPending(Thread* self);
302 * Fast test for use in the interpreter. Returns "true" if our suspend
305 INLINE bool dvmCheckSuspendQuick(Thread* self) {
306 return (self->suspendCount != 0);
310 * Used when changing thread state. Threads may only change their own.
311 * The "self" argument, which may be NULL, is accepted as an optimization.
313 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
314 * or THREAD_MONITOR), do so in the same function as the wait -- this records
315 * the current stack depth for the GC.
317 * If you're changing to THREAD_RUNNING, this will check for suspension.
319 * Returns the old status.
321 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
324 * Initialize a mutex.
326 INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
329 pthread_mutexattr_t attr;
332 pthread_mutexattr_init(&attr);
333 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
335 pthread_mutex_init(pMutex, &attr);
336 pthread_mutexattr_destroy(&attr);
338 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
343 * Grab a plain mutex.
345 INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
347 int cc = pthread_mutex_lock(pMutex);
352 * Unlock pthread mutex.
354 INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
356 int cc = pthread_mutex_unlock(pMutex);
363 INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
365 int cc = pthread_mutex_destroy(pMutex);
370 * Create a thread as a result of java.lang.Thread.start().
372 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
375 * Create a thread internal to the VM. It's visible to interpreted code,
376 * but found in the "system" thread group rather than "main".
378 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
379 InternalThreadStart func, void* funcArg);
382 * Attach or detach the current thread from the VM.
384 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
385 void dvmDetachCurrentThread(void);
388 * Get the "main" or "system" thread group.
390 Object* dvmGetMainThreadGroup(void);
391 Object* dvmGetSystemThreadGroup(void);
394 * Given a java/lang/VMThread object, return our Thread.
396 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
399 * Sleep in a thread. Returns when the sleep timer returns or the thread
402 void dvmThreadSleep(u8 msec, u4 nsec);
405 * Get the name of a thread. (For safety, hold the thread list lock.)
407 char* dvmGetThreadName(Thread* thread);
410 * Return true if a thread is on the internal list. If it is, the
411 * thread is part of the GC's root set.
413 bool dvmIsOnThreadList(const Thread* thread);
416 * Get/set the JNIEnv field.
418 INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
419 INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
422 * Update the priority value of the underlying pthread.
424 void dvmChangeThreadPriority(Thread* thread, int newPriority);
427 * Debug: dump information about a single thread.
429 void dvmDumpThread(Thread* thread, bool isRunning);
430 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
434 * Debug: dump information about all threads.
436 void dvmDumpAllThreads(bool grabLock);
437 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
439 #ifdef WITH_MONITOR_TRACKING
441 * Track locks held by the current thread, along with the stack trace at
442 * the point the lock was acquired.
444 * At any given time the number of locks held across the VM should be
445 * fairly small, so there's no reason not to generate and store the entire
448 typedef struct LockedObjectData {
449 /* the locked object */
452 /* number of times it has been locked recursively (zero-based ref count) */
455 /* stack trace at point of initial acquire */
459 struct LockedObjectData* next;
463 * Add/remove/find objects from the thread's monitor list.
465 void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
466 void dvmRemoveFromMonitorList(Thread* self, Object* obj);
467 LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
470 #endif /*_DALVIK_THREAD*/