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