blob: 402d4c836734bf6991237def79a92d521b262b71 [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 */
Bob Lee9dc72a32009-09-04 18:28:16 -070054 THREAD_PAGING = 9, /* paging memory */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080055} ThreadStatus;
56
57/* thread priorities, from java.lang.Thread */
58enum {
59 THREAD_MIN_PRIORITY = 1,
60 THREAD_NORM_PRIORITY = 5,
61 THREAD_MAX_PRIORITY = 10,
62};
63
64
65/* initialization */
66bool dvmThreadStartup(void);
67bool dvmThreadObjStartup(void);
68void dvmThreadShutdown(void);
69void dvmSlayDaemons(void);
70
71
Andy McFaddend5ab7262009-08-25 07:19:34 -070072#define kJniLocalRefMin 32
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080073#define kJniLocalRefMax 512 /* arbitrary; should be plenty */
74#define kInternalRefDefault 32 /* equally arbitrary */
75#define kInternalRefMax 4096 /* mainly a sanity check */
76
77#define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
Andy McFadden39b99b02009-05-11 14:39:13 -070078#define kDefaultStackSize (12*1024) /* three 4K pages */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080079#define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
80
81/*
82 * Our per-thread data.
83 *
84 * These are allocated on the system heap.
85 */
86typedef struct Thread {
87 /* small unique integer; useful for "thin" locks and debug messages */
88 u4 threadId;
89
90 /*
91 * Thread's current status. Can only be changed by the thread itself
92 * (i.e. don't mess with this from other threads).
93 */
Bob Lee9dc72a32009-09-04 18:28:16 -070094 volatile ThreadStatus status;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080095
96 /*
97 * This is the number of times the thread has been suspended. When the
98 * count drops to zero, the thread resumes.
99 *
100 * "dbgSuspendCount" is the portion of the suspend count that the
101 * debugger is responsible for. This has to be tracked separately so
102 * that we can recover correctly if the debugger abruptly disconnects
103 * (suspendCount -= dbgSuspendCount). The debugger should not be able
104 * to resume GC-suspended threads, because we ignore the debugger while
105 * a GC is in progress.
106 *
107 * Both of these are guarded by gDvm.threadSuspendCountLock.
108 *
109 * (We could store both of these in the same 32-bit, using 16-bit
110 * halves, to make atomic ops possible. In practice, you only need
111 * to read suspendCount, and we need to hold a mutex when making
112 * changes, so there's no need to merge them. Note the non-debug
113 * component will rarely be other than 1 or 0 -- not sure it's even
114 * possible with the way mutexes are currently used.)
115 */
116 int suspendCount;
117 int dbgSuspendCount;
118
119 /*
120 * Set to true when the thread suspends itself, false when it wakes up.
121 * This is only expected to be set when status==THREAD_RUNNING.
122 */
123 bool isSuspended;
124
125 /* thread handle, as reported by pthread_self() */
126 pthread_t handle;
127
128 /* thread ID, only useful under Linux */
129 pid_t systemTid;
130
131 /* start (high addr) of interp stack (subtract size to get malloc addr) */
132 u1* interpStackStart;
133
134 /* current limit of stack; flexes for StackOverflowError */
135 const u1* interpStackEnd;
136
137 /* interpreter stack size; our stacks are fixed-length */
138 int interpStackSize;
139 bool stackOverflowed;
140
141 /* FP of bottom-most (currently executing) stack frame on interp stack */
142 void* curFrame;
143
144 /* current exception, or NULL if nothing pending */
145 Object* exception;
146
147 /* the java/lang/Thread that we are associated with */
148 Object* threadObj;
149
150 /* the JNIEnv pointer associated with this thread */
151 JNIEnv* jniEnv;
152
153 /* internal reference tracking */
154 ReferenceTable internalLocalRefTable;
155
156 /* JNI local reference tracking */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700157#ifdef USE_INDIRECT_REF
158 IndirectRefTable jniLocalRefTable;
159#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800160 ReferenceTable jniLocalRefTable;
Andy McFaddend5ab7262009-08-25 07:19:34 -0700161#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800162
163 /* JNI native monitor reference tracking (initialized on first use) */
164 ReferenceTable jniMonitorRefTable;
165
166 /* hack to make JNI_OnLoad work right */
167 Object* classLoaderOverride;
168
169 /* pointer to the monitor lock we're currently waiting on */
170 /* (do not set or clear unless the Monitor itself is held) */
171 /* TODO: consider changing this to Object* for better JDWP interaction */
172 Monitor* waitMonitor;
173 /* set when we confirm that the thread must be interrupted from a wait */
174 bool interruptingWait;
175 /* thread "interrupted" status; stays raised until queried or thrown */
176 bool interrupted;
177
178 /*
179 * Set to true when the thread is in the process of throwing an
180 * OutOfMemoryError.
181 */
182 bool throwingOOME;
183
184 /* links to rest of thread list; grab global lock before traversing */
185 struct Thread* prev;
186 struct Thread* next;
187
188 /* JDWP invoke-during-breakpoint support */
189 DebugInvokeReq invokeReq;
190
191#ifdef WITH_MONITOR_TRACKING
192 /* objects locked by this thread; most recent is at head of list */
193 struct LockedObjectData* pLockedObjects;
194#endif
195
196#ifdef WITH_ALLOC_LIMITS
197 /* allocation limit, for Debug.setAllocationLimit() regression testing */
198 int allocLimit;
199#endif
200
201#ifdef WITH_PROFILER
202 /* base time for per-thread CPU timing */
203 bool cpuClockBaseSet;
204 u8 cpuClockBase;
205
206 /* memory allocation profiling state */
207 AllocProfState allocProf;
208#endif
209
210#ifdef WITH_JNI_STACK_CHECK
211 u4 stackCrc;
212#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700213
214#if WITH_EXTRA_GC_CHECKS > 1
215 /* PC, saved on every instruction; redundant with StackSaveArea */
216 const u2* currentPc2;
217#endif
Jeff Hao97319a82009-08-12 16:57:15 -0700218
219#if defined(WITH_SELF_VERIFICATION)
220 /* Buffer for register state during self verification */
221 struct ShadowSpace* shadowSpace;
222#endif
Android Git Automerger4d3b5842009-09-09 10:48:47 -0700223
Bob Lee9dc72a32009-09-04 18:28:16 -0700224 /* /proc/PID/task/TID/stat */
225 int statFile;
226 /* offset of state char in stat file, last we checked */
227 int stateOffset;
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);
262/* release the thread list global lock */
263void dvmUnlockThreadList(void);
264
265/*
266 * Thread suspend/resume, used by the GC and debugger.
267 */
268typedef enum SuspendCause {
269 SUSPEND_NOT = 0,
270 SUSPEND_FOR_GC,
271 SUSPEND_FOR_DEBUG,
272 SUSPEND_FOR_DEBUG_EVENT,
273 SUSPEND_FOR_STACK_DUMP,
274 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700275#if defined(WITH_JIT)
276 SUSPEND_FOR_JIT,
277#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800278} SuspendCause;
279void dvmSuspendThread(Thread* thread);
280void dvmSuspendSelf(bool jdwpActivity);
281void dvmResumeThread(Thread* thread);
282void dvmSuspendAllThreads(SuspendCause why);
283void dvmResumeAllThreads(SuspendCause why);
284void dvmUndoDebuggerSuspensions(void);
285
286/*
287 * Check suspend state. Grab threadListLock before calling.
288 */
289bool dvmIsSuspended(Thread* thread);
290
291/*
292 * Wait until a thread has suspended. (Used by debugger support.)
293 */
294void dvmWaitForSuspend(Thread* thread);
295
296/*
297 * Check to see if we should be suspended now. If so, suspend ourselves
298 * by sleeping on a condition variable.
299 *
300 * If "self" is NULL, this will use dvmThreadSelf().
301 */
302bool dvmCheckSuspendPending(Thread* self);
303
304/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700305 * Fast test for use in the interpreter. Returns "true" if our suspend
306 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800307 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700308INLINE bool dvmCheckSuspendQuick(Thread* self) {
309 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800310}
311
312/*
313 * Used when changing thread state. Threads may only change their own.
314 * The "self" argument, which may be NULL, is accepted as an optimization.
315 *
316 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
317 * or THREAD_MONITOR), do so in the same function as the wait -- this records
318 * the current stack depth for the GC.
319 *
320 * If you're changing to THREAD_RUNNING, this will check for suspension.
321 *
322 * Returns the old status.
323 */
324ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
325
326/*
327 * Initialize a mutex.
328 */
329INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
330{
331#ifdef CHECK_MUTEX
332 pthread_mutexattr_t attr;
333 int cc;
334
335 pthread_mutexattr_init(&attr);
336 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
337 assert(cc == 0);
338 pthread_mutex_init(pMutex, &attr);
339 pthread_mutexattr_destroy(&attr);
340#else
341 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
342#endif
343}
344
345/*
346 * Grab a plain mutex.
347 */
348INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
349{
350 int cc = pthread_mutex_lock(pMutex);
351 assert(cc == 0);
352}
353
354/*
355 * Unlock pthread mutex.
356 */
357INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
358{
359 int cc = pthread_mutex_unlock(pMutex);
360 assert(cc == 0);
361}
362
363/*
364 * Destroy a mutex.
365 */
366INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
367{
368 int cc = pthread_mutex_destroy(pMutex);
369 assert(cc == 0);
370}
371
372/*
373 * Create a thread as a result of java.lang.Thread.start().
374 */
375bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
376
377/*
378 * Create a thread internal to the VM. It's visible to interpreted code,
379 * but found in the "system" thread group rather than "main".
380 */
381bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
382 InternalThreadStart func, void* funcArg);
383
384/*
385 * Attach or detach the current thread from the VM.
386 */
387bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
388void dvmDetachCurrentThread(void);
389
390/*
391 * Get the "main" or "system" thread group.
392 */
393Object* dvmGetMainThreadGroup(void);
394Object* dvmGetSystemThreadGroup(void);
395
396/*
397 * Given a java/lang/VMThread object, return our Thread.
398 */
399Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
400
401/*
402 * Sleep in a thread. Returns when the sleep timer returns or the thread
403 * is interrupted.
404 */
405void dvmThreadSleep(u8 msec, u4 nsec);
406
407/*
408 * Get the name of a thread. (For safety, hold the thread list lock.)
409 */
410char* dvmGetThreadName(Thread* thread);
411
412/*
413 * Return true if a thread is on the internal list. If it is, the
414 * thread is part of the GC's root set.
415 */
416bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700417
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800418/*
419 * Get/set the JNIEnv field.
420 */
421INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
422INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
423
424/*
San Mehat256fc152009-04-21 14:03:06 -0700425 * Change the scheduler group of the current process
426 */
427int dvmChangeThreadSchedulerGroup(const char *group);
428
429/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800430 * Update the priority value of the underlying pthread.
431 */
432void dvmChangeThreadPriority(Thread* thread, int newPriority);
433
434
435/*
436 * Debug: dump information about a single thread.
437 */
438void dvmDumpThread(Thread* thread, bool isRunning);
439void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
440 bool isRunning);
441
442/*
443 * Debug: dump information about all threads.
444 */
445void dvmDumpAllThreads(bool grabLock);
446void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
447
Bob Lee9dc72a32009-09-04 18:28:16 -0700448/*
449 * Reads the native thread status. If the thread is in native code, this
450 * function queries the native thread state and converts it to an equivalent
451 * ThreadStatus. If the native status can't be read, this function returns
452 * THREAD_NATIVE.
453 */
454ThreadStatus dvmGetNativeThreadStatus(Thread* thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800455
456#ifdef WITH_MONITOR_TRACKING
457/*
458 * Track locks held by the current thread, along with the stack trace at
459 * the point the lock was acquired.
460 *
461 * At any given time the number of locks held across the VM should be
462 * fairly small, so there's no reason not to generate and store the entire
463 * stack trace.
464 */
465typedef struct LockedObjectData {
466 /* the locked object */
467 struct Object* obj;
468
469 /* number of times it has been locked recursively (zero-based ref count) */
470 int recursionCount;
471
472 /* stack trace at point of initial acquire */
473 u4 stackDepth;
474 int* rawStackTrace;
475
476 struct LockedObjectData* next;
477} LockedObjectData;
478
479/*
480 * Add/remove/find objects from the thread's monitor list.
481 */
482void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
483void dvmRemoveFromMonitorList(Thread* self, Object* obj);
484LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
485#endif
486
487#endif /*_DALVIK_THREAD*/