blob: 3baf9aad1d9d622972096e1dcc99fe46d5297722 [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
Bob Lee9dc72a32009-09-04 18:28:16 -0700218
219 /* /proc/PID/task/TID/stat */
220 int statFile;
221 /* offset of state char in stat file, last we checked */
222 int stateOffset;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800223} Thread;
224
225/* start point for an internal thread; mimics pthread args */
226typedef void* (*InternalThreadStart)(void* arg);
227
228/* args for internal thread creation */
229typedef struct InternalStartArgs {
230 /* inputs */
231 InternalThreadStart func;
232 void* funcArg;
233 char* name;
234 Object* group;
235 bool isDaemon;
236 /* result */
237 volatile Thread** pThread;
238 volatile int* pCreateStatus;
239} InternalStartArgs;
240
241/* finish init */
242bool dvmPrepMainForJni(JNIEnv* pEnv);
243bool dvmPrepMainThread(void);
244
245/* utility function to get the tid */
246pid_t dvmGetSysThreadId(void);
247
248/*
249 * Get our Thread* from TLS.
250 *
251 * Returns NULL if this isn't a thread that the VM is aware of.
252 */
253Thread* dvmThreadSelf(void);
254
255/* grab the thread list global lock */
256void dvmLockThreadList(Thread* self);
257/* release the thread list global lock */
258void dvmUnlockThreadList(void);
259
260/*
261 * Thread suspend/resume, used by the GC and debugger.
262 */
263typedef enum SuspendCause {
264 SUSPEND_NOT = 0,
265 SUSPEND_FOR_GC,
266 SUSPEND_FOR_DEBUG,
267 SUSPEND_FOR_DEBUG_EVENT,
268 SUSPEND_FOR_STACK_DUMP,
269 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700270#if defined(WITH_JIT)
271 SUSPEND_FOR_JIT,
272#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800273} SuspendCause;
274void dvmSuspendThread(Thread* thread);
275void dvmSuspendSelf(bool jdwpActivity);
276void dvmResumeThread(Thread* thread);
277void dvmSuspendAllThreads(SuspendCause why);
278void dvmResumeAllThreads(SuspendCause why);
279void dvmUndoDebuggerSuspensions(void);
280
281/*
282 * Check suspend state. Grab threadListLock before calling.
283 */
284bool dvmIsSuspended(Thread* thread);
285
286/*
287 * Wait until a thread has suspended. (Used by debugger support.)
288 */
289void dvmWaitForSuspend(Thread* thread);
290
291/*
292 * Check to see if we should be suspended now. If so, suspend ourselves
293 * by sleeping on a condition variable.
294 *
295 * If "self" is NULL, this will use dvmThreadSelf().
296 */
297bool dvmCheckSuspendPending(Thread* self);
298
299/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700300 * Fast test for use in the interpreter. Returns "true" if our suspend
301 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800302 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700303INLINE bool dvmCheckSuspendQuick(Thread* self) {
304 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800305}
306
307/*
308 * Used when changing thread state. Threads may only change their own.
309 * The "self" argument, which may be NULL, is accepted as an optimization.
310 *
311 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
312 * or THREAD_MONITOR), do so in the same function as the wait -- this records
313 * the current stack depth for the GC.
314 *
315 * If you're changing to THREAD_RUNNING, this will check for suspension.
316 *
317 * Returns the old status.
318 */
319ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
320
321/*
322 * Initialize a mutex.
323 */
324INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
325{
326#ifdef CHECK_MUTEX
327 pthread_mutexattr_t attr;
328 int cc;
329
330 pthread_mutexattr_init(&attr);
331 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
332 assert(cc == 0);
333 pthread_mutex_init(pMutex, &attr);
334 pthread_mutexattr_destroy(&attr);
335#else
336 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
337#endif
338}
339
340/*
341 * Grab a plain mutex.
342 */
343INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
344{
345 int cc = pthread_mutex_lock(pMutex);
346 assert(cc == 0);
347}
348
349/*
350 * Unlock pthread mutex.
351 */
352INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
353{
354 int cc = pthread_mutex_unlock(pMutex);
355 assert(cc == 0);
356}
357
358/*
359 * Destroy a mutex.
360 */
361INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
362{
363 int cc = pthread_mutex_destroy(pMutex);
364 assert(cc == 0);
365}
366
367/*
368 * Create a thread as a result of java.lang.Thread.start().
369 */
370bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
371
372/*
373 * Create a thread internal to the VM. It's visible to interpreted code,
374 * but found in the "system" thread group rather than "main".
375 */
376bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
377 InternalThreadStart func, void* funcArg);
378
379/*
380 * Attach or detach the current thread from the VM.
381 */
382bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
383void dvmDetachCurrentThread(void);
384
385/*
386 * Get the "main" or "system" thread group.
387 */
388Object* dvmGetMainThreadGroup(void);
389Object* dvmGetSystemThreadGroup(void);
390
391/*
392 * Given a java/lang/VMThread object, return our Thread.
393 */
394Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
395
396/*
397 * Sleep in a thread. Returns when the sleep timer returns or the thread
398 * is interrupted.
399 */
400void dvmThreadSleep(u8 msec, u4 nsec);
401
402/*
403 * Get the name of a thread. (For safety, hold the thread list lock.)
404 */
405char* dvmGetThreadName(Thread* thread);
406
407/*
408 * Return true if a thread is on the internal list. If it is, the
409 * thread is part of the GC's root set.
410 */
411bool dvmIsOnThreadList(const Thread* thread);
412
413/*
414 * Get/set the JNIEnv field.
415 */
416INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
417INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
418
419/*
San Mehat256fc152009-04-21 14:03:06 -0700420 * Change the scheduler group of the current process
421 */
422int dvmChangeThreadSchedulerGroup(const char *group);
423
424/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800425 * Update the priority value of the underlying pthread.
426 */
427void dvmChangeThreadPriority(Thread* thread, int newPriority);
428
429
430/*
431 * Debug: dump information about a single thread.
432 */
433void dvmDumpThread(Thread* thread, bool isRunning);
434void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
435 bool isRunning);
436
437/*
438 * Debug: dump information about all threads.
439 */
440void dvmDumpAllThreads(bool grabLock);
441void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
442
Bob Lee9dc72a32009-09-04 18:28:16 -0700443/*
444 * Reads the native thread status. If the thread is in native code, this
445 * function queries the native thread state and converts it to an equivalent
446 * ThreadStatus. If the native status can't be read, this function returns
447 * THREAD_NATIVE.
448 */
449ThreadStatus dvmGetNativeThreadStatus(Thread* thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800450
451#ifdef WITH_MONITOR_TRACKING
452/*
453 * Track locks held by the current thread, along with the stack trace at
454 * the point the lock was acquired.
455 *
456 * At any given time the number of locks held across the VM should be
457 * fairly small, so there's no reason not to generate and store the entire
458 * stack trace.
459 */
460typedef struct LockedObjectData {
461 /* the locked object */
462 struct Object* obj;
463
464 /* number of times it has been locked recursively (zero-based ref count) */
465 int recursionCount;
466
467 /* stack trace at point of initial acquire */
468 u4 stackDepth;
469 int* rawStackTrace;
470
471 struct LockedObjectData* next;
472} LockedObjectData;
473
474/*
475 * Add/remove/find objects from the thread's monitor list.
476 */
477void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
478void dvmRemoveFromMonitorList(Thread* self, Object* obj);
479LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
480#endif
481
482#endif /*_DALVIK_THREAD*/