blob: 1725b1edb55637677a7a352a86054cbf91822594 [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
25#if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
Andy McFadden0083d372009-08-21 14:44:04 -070026/* glibc lacks this unless you #define __USE_UNIX98 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080027int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
28enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
29#endif
30
31#ifdef WITH_MONITOR_TRACKING
32struct LockedObjectData;
33#endif
34
35/*
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 {
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() */
49 /* non-JDWP states */
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 */
54} ThreadStatus;
55
56/* thread priorities, from java.lang.Thread */
57enum {
58 THREAD_MIN_PRIORITY = 1,
59 THREAD_NORM_PRIORITY = 5,
60 THREAD_MAX_PRIORITY = 10,
61};
62
63
64/* initialization */
65bool dvmThreadStartup(void);
66bool dvmThreadObjStartup(void);
67void dvmThreadShutdown(void);
68void dvmSlayDaemons(void);
69
70
71#define kJniLocalRefMax 512 /* arbitrary; should be plenty */
72#define kInternalRefDefault 32 /* equally arbitrary */
73#define kInternalRefMax 4096 /* mainly a sanity check */
74
75#define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
Andy McFadden39b99b02009-05-11 14:39:13 -070076#define kDefaultStackSize (12*1024) /* three 4K pages */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080077#define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
78
79/*
80 * Our per-thread data.
81 *
82 * These are allocated on the system heap.
83 */
84typedef struct Thread {
85 /* small unique integer; useful for "thin" locks and debug messages */
86 u4 threadId;
87
88 /*
89 * Thread's current status. Can only be changed by the thread itself
90 * (i.e. don't mess with this from other threads).
91 */
92 ThreadStatus status;
93
94 /*
95 * This is the number of times the thread has been suspended. When the
96 * count drops to zero, the thread resumes.
97 *
98 * "dbgSuspendCount" is the portion of the suspend count that the
99 * debugger is responsible for. This has to be tracked separately so
100 * that we can recover correctly if the debugger abruptly disconnects
101 * (suspendCount -= dbgSuspendCount). The debugger should not be able
102 * to resume GC-suspended threads, because we ignore the debugger while
103 * a GC is in progress.
104 *
105 * Both of these are guarded by gDvm.threadSuspendCountLock.
106 *
107 * (We could store both of these in the same 32-bit, using 16-bit
108 * halves, to make atomic ops possible. In practice, you only need
109 * to read suspendCount, and we need to hold a mutex when making
110 * changes, so there's no need to merge them. Note the non-debug
111 * component will rarely be other than 1 or 0 -- not sure it's even
112 * possible with the way mutexes are currently used.)
113 */
114 int suspendCount;
115 int dbgSuspendCount;
116
117 /*
118 * Set to true when the thread suspends itself, false when it wakes up.
119 * This is only expected to be set when status==THREAD_RUNNING.
120 */
121 bool isSuspended;
122
123 /* thread handle, as reported by pthread_self() */
124 pthread_t handle;
125
126 /* thread ID, only useful under Linux */
127 pid_t systemTid;
128
129 /* start (high addr) of interp stack (subtract size to get malloc addr) */
130 u1* interpStackStart;
131
132 /* current limit of stack; flexes for StackOverflowError */
133 const u1* interpStackEnd;
134
135 /* interpreter stack size; our stacks are fixed-length */
136 int interpStackSize;
137 bool stackOverflowed;
138
139 /* FP of bottom-most (currently executing) stack frame on interp stack */
140 void* curFrame;
141
142 /* current exception, or NULL if nothing pending */
143 Object* exception;
144
145 /* the java/lang/Thread that we are associated with */
146 Object* threadObj;
147
148 /* the JNIEnv pointer associated with this thread */
149 JNIEnv* jniEnv;
150
151 /* internal reference tracking */
152 ReferenceTable internalLocalRefTable;
153
154 /* JNI local reference tracking */
155 ReferenceTable jniLocalRefTable;
156
157 /* JNI native monitor reference tracking (initialized on first use) */
158 ReferenceTable jniMonitorRefTable;
159
160 /* hack to make JNI_OnLoad work right */
161 Object* classLoaderOverride;
162
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 */
170 bool interrupted;
171
172 /*
173 * Set to true when the thread is in the process of throwing an
174 * OutOfMemoryError.
175 */
176 bool throwingOOME;
177
178 /* links to rest of thread list; grab global lock before traversing */
179 struct Thread* prev;
180 struct Thread* next;
181
182 /* JDWP invoke-during-breakpoint support */
183 DebugInvokeReq invokeReq;
184
185#ifdef WITH_MONITOR_TRACKING
186 /* objects locked by this thread; most recent is at head of list */
187 struct LockedObjectData* pLockedObjects;
188#endif
189
190#ifdef WITH_ALLOC_LIMITS
191 /* allocation limit, for Debug.setAllocationLimit() regression testing */
192 int allocLimit;
193#endif
194
195#ifdef WITH_PROFILER
196 /* base time for per-thread CPU timing */
197 bool cpuClockBaseSet;
198 u8 cpuClockBase;
199
200 /* memory allocation profiling state */
201 AllocProfState allocProf;
202#endif
203
204#ifdef WITH_JNI_STACK_CHECK
205 u4 stackCrc;
206#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700207
208#if WITH_EXTRA_GC_CHECKS > 1
209 /* PC, saved on every instruction; redundant with StackSaveArea */
210 const u2* currentPc2;
211#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800212} Thread;
213
214/* start point for an internal thread; mimics pthread args */
215typedef void* (*InternalThreadStart)(void* arg);
216
217/* args for internal thread creation */
218typedef struct InternalStartArgs {
219 /* inputs */
220 InternalThreadStart func;
221 void* funcArg;
222 char* name;
223 Object* group;
224 bool isDaemon;
225 /* result */
226 volatile Thread** pThread;
227 volatile int* pCreateStatus;
228} InternalStartArgs;
229
230/* finish init */
231bool dvmPrepMainForJni(JNIEnv* pEnv);
232bool dvmPrepMainThread(void);
233
234/* utility function to get the tid */
235pid_t dvmGetSysThreadId(void);
236
237/*
238 * Get our Thread* from TLS.
239 *
240 * Returns NULL if this isn't a thread that the VM is aware of.
241 */
242Thread* dvmThreadSelf(void);
243
244/* grab the thread list global lock */
245void dvmLockThreadList(Thread* self);
246/* release the thread list global lock */
247void dvmUnlockThreadList(void);
248
249/*
250 * Thread suspend/resume, used by the GC and debugger.
251 */
252typedef enum SuspendCause {
253 SUSPEND_NOT = 0,
254 SUSPEND_FOR_GC,
255 SUSPEND_FOR_DEBUG,
256 SUSPEND_FOR_DEBUG_EVENT,
257 SUSPEND_FOR_STACK_DUMP,
258 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700259#if defined(WITH_JIT)
260 SUSPEND_FOR_JIT,
261#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800262} SuspendCause;
263void dvmSuspendThread(Thread* thread);
264void dvmSuspendSelf(bool jdwpActivity);
265void dvmResumeThread(Thread* thread);
266void dvmSuspendAllThreads(SuspendCause why);
267void dvmResumeAllThreads(SuspendCause why);
268void dvmUndoDebuggerSuspensions(void);
269
270/*
271 * Check suspend state. Grab threadListLock before calling.
272 */
273bool dvmIsSuspended(Thread* thread);
274
275/*
276 * Wait until a thread has suspended. (Used by debugger support.)
277 */
278void dvmWaitForSuspend(Thread* thread);
279
280/*
281 * Check to see if we should be suspended now. If so, suspend ourselves
282 * by sleeping on a condition variable.
283 *
284 * If "self" is NULL, this will use dvmThreadSelf().
285 */
286bool dvmCheckSuspendPending(Thread* self);
287
288/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700289 * Fast test for use in the interpreter. Returns "true" if our suspend
290 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800291 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700292INLINE bool dvmCheckSuspendQuick(Thread* self) {
293 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800294}
295
296/*
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.
299 *
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.
303 *
304 * If you're changing to THREAD_RUNNING, this will check for suspension.
305 *
306 * Returns the old status.
307 */
308ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
309
310/*
311 * Initialize a mutex.
312 */
313INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
314{
315#ifdef CHECK_MUTEX
316 pthread_mutexattr_t attr;
317 int cc;
318
319 pthread_mutexattr_init(&attr);
320 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
321 assert(cc == 0);
322 pthread_mutex_init(pMutex, &attr);
323 pthread_mutexattr_destroy(&attr);
324#else
325 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
326#endif
327}
328
329/*
330 * Grab a plain mutex.
331 */
332INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
333{
334 int cc = pthread_mutex_lock(pMutex);
335 assert(cc == 0);
336}
337
338/*
339 * Unlock pthread mutex.
340 */
341INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
342{
343 int cc = pthread_mutex_unlock(pMutex);
344 assert(cc == 0);
345}
346
347/*
348 * Destroy a mutex.
349 */
350INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
351{
352 int cc = pthread_mutex_destroy(pMutex);
353 assert(cc == 0);
354}
355
356/*
357 * Create a thread as a result of java.lang.Thread.start().
358 */
359bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
360
361/*
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".
364 */
365bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
366 InternalThreadStart func, void* funcArg);
367
368/*
369 * Attach or detach the current thread from the VM.
370 */
371bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
372void dvmDetachCurrentThread(void);
373
374/*
375 * Get the "main" or "system" thread group.
376 */
377Object* dvmGetMainThreadGroup(void);
378Object* dvmGetSystemThreadGroup(void);
379
380/*
381 * Given a java/lang/VMThread object, return our Thread.
382 */
383Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
384
385/*
386 * Sleep in a thread. Returns when the sleep timer returns or the thread
387 * is interrupted.
388 */
389void dvmThreadSleep(u8 msec, u4 nsec);
390
391/*
392 * Get the name of a thread. (For safety, hold the thread list lock.)
393 */
394char* dvmGetThreadName(Thread* thread);
395
396/*
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.
399 */
400bool dvmIsOnThreadList(const Thread* thread);
401
402/*
403 * Get/set the JNIEnv field.
404 */
405INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
406INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
407
408/*
San Mehat256fc152009-04-21 14:03:06 -0700409 * Change the scheduler group of the current process
410 */
411int dvmChangeThreadSchedulerGroup(const char *group);
412
413/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800414 * Update the priority value of the underlying pthread.
415 */
416void dvmChangeThreadPriority(Thread* thread, int newPriority);
417
418
419/*
420 * Debug: dump information about a single thread.
421 */
422void dvmDumpThread(Thread* thread, bool isRunning);
423void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
424 bool isRunning);
425
426/*
427 * Debug: dump information about all threads.
428 */
429void dvmDumpAllThreads(bool grabLock);
430void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
431
432
433#ifdef WITH_MONITOR_TRACKING
434/*
435 * Track locks held by the current thread, along with the stack trace at
436 * the point the lock was acquired.
437 *
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
440 * stack trace.
441 */
442typedef struct LockedObjectData {
443 /* the locked object */
444 struct Object* obj;
445
446 /* number of times it has been locked recursively (zero-based ref count) */
447 int recursionCount;
448
449 /* stack trace at point of initial acquire */
450 u4 stackDepth;
451 int* rawStackTrace;
452
453 struct LockedObjectData* next;
454} LockedObjectData;
455
456/*
457 * Add/remove/find objects from the thread's monitor list.
458 */
459void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
460void dvmRemoveFromMonitorList(Thread* self, Object* obj);
461LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
462#endif
463
464#endif /*_DALVIK_THREAD*/