blob: 60b24968fa1e14092385480d188a6852c8392d4d [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/*
Bob Lee2fe146a2009-09-10 00:36:29 +020081 * System thread state. See native/SystemThread.h.
82 */
83typedef struct SystemThread SystemThread;
84
85/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080086 * Our per-thread data.
87 *
88 * These are allocated on the system heap.
89 */
90typedef struct Thread {
91 /* small unique integer; useful for "thin" locks and debug messages */
92 u4 threadId;
93
94 /*
95 * Thread's current status. Can only be changed by the thread itself
96 * (i.e. don't mess with this from other threads).
97 */
Bob Lee9dc72a32009-09-04 18:28:16 -070098 volatile ThreadStatus status;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080099
100 /*
101 * This is the number of times the thread has been suspended. When the
102 * count drops to zero, the thread resumes.
103 *
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.
110 *
111 * Both of these are guarded by gDvm.threadSuspendCountLock.
112 *
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.)
119 */
120 int suspendCount;
121 int dbgSuspendCount;
122
123 /*
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.
126 */
127 bool isSuspended;
128
129 /* thread handle, as reported by pthread_self() */
130 pthread_t handle;
131
132 /* thread ID, only useful under Linux */
133 pid_t systemTid;
134
135 /* start (high addr) of interp stack (subtract size to get malloc addr) */
136 u1* interpStackStart;
137
138 /* current limit of stack; flexes for StackOverflowError */
139 const u1* interpStackEnd;
140
141 /* interpreter stack size; our stacks are fixed-length */
142 int interpStackSize;
143 bool stackOverflowed;
144
145 /* FP of bottom-most (currently executing) stack frame on interp stack */
146 void* curFrame;
147
148 /* current exception, or NULL if nothing pending */
149 Object* exception;
150
151 /* the java/lang/Thread that we are associated with */
152 Object* threadObj;
153
154 /* the JNIEnv pointer associated with this thread */
155 JNIEnv* jniEnv;
156
157 /* internal reference tracking */
158 ReferenceTable internalLocalRefTable;
159
160 /* JNI local reference tracking */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700161#ifdef USE_INDIRECT_REF
162 IndirectRefTable jniLocalRefTable;
163#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800164 ReferenceTable jniLocalRefTable;
Andy McFaddend5ab7262009-08-25 07:19:34 -0700165#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800166
167 /* JNI native monitor reference tracking (initialized on first use) */
168 ReferenceTable jniMonitorRefTable;
169
170 /* hack to make JNI_OnLoad work right */
171 Object* classLoaderOverride;
172
173 /* pointer to the monitor lock we're currently waiting on */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800174 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800175 /* TODO: consider changing this to Object* for better JDWP interaction */
176 Monitor* waitMonitor;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800177
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800178 /* thread "interrupted" status; stays raised until queried or thrown */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800179 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800180 bool interrupted;
181
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800182 /* links to the next thread in the wait set this thread is part of */
183 struct Thread* waitNext;
184
185 /* object to sleep on while we are waiting for a monitor */
186 pthread_cond_t waitCond;
187
188 /* mutex to guard the interrupted and the waitMonitor members */
189 pthread_mutex_t waitMutex;
190
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800191 /*
192 * Set to true when the thread is in the process of throwing an
193 * OutOfMemoryError.
194 */
195 bool throwingOOME;
196
197 /* links to rest of thread list; grab global lock before traversing */
198 struct Thread* prev;
199 struct Thread* next;
200
Andy McFadden909ce242009-12-10 16:38:30 -0800201 /* used by threadExitCheck when a thread exits without detaching */
202 int threadExitCheckCount;
203
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800204 /* JDWP invoke-during-breakpoint support */
205 DebugInvokeReq invokeReq;
206
207#ifdef WITH_MONITOR_TRACKING
208 /* objects locked by this thread; most recent is at head of list */
209 struct LockedObjectData* pLockedObjects;
210#endif
211
212#ifdef WITH_ALLOC_LIMITS
213 /* allocation limit, for Debug.setAllocationLimit() regression testing */
214 int allocLimit;
215#endif
216
217#ifdef WITH_PROFILER
218 /* base time for per-thread CPU timing */
219 bool cpuClockBaseSet;
220 u8 cpuClockBase;
221
222 /* memory allocation profiling state */
223 AllocProfState allocProf;
224#endif
225
226#ifdef WITH_JNI_STACK_CHECK
227 u4 stackCrc;
228#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700229
230#if WITH_EXTRA_GC_CHECKS > 1
231 /* PC, saved on every instruction; redundant with StackSaveArea */
232 const u2* currentPc2;
233#endif
Jeff Hao97319a82009-08-12 16:57:15 -0700234
235#if defined(WITH_SELF_VERIFICATION)
236 /* Buffer for register state during self verification */
237 struct ShadowSpace* shadowSpace;
238#endif
Android Git Automerger4d3b5842009-09-09 10:48:47 -0700239
Bob Lee2fe146a2009-09-10 00:36:29 +0200240 /* system thread state */
241 SystemThread* systemThread;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800242} Thread;
243
244/* start point for an internal thread; mimics pthread args */
245typedef void* (*InternalThreadStart)(void* arg);
246
247/* args for internal thread creation */
248typedef struct InternalStartArgs {
249 /* inputs */
250 InternalThreadStart func;
251 void* funcArg;
252 char* name;
253 Object* group;
254 bool isDaemon;
255 /* result */
256 volatile Thread** pThread;
257 volatile int* pCreateStatus;
258} InternalStartArgs;
259
260/* finish init */
261bool dvmPrepMainForJni(JNIEnv* pEnv);
262bool dvmPrepMainThread(void);
263
264/* utility function to get the tid */
265pid_t dvmGetSysThreadId(void);
266
267/*
268 * Get our Thread* from TLS.
269 *
270 * Returns NULL if this isn't a thread that the VM is aware of.
271 */
272Thread* dvmThreadSelf(void);
273
274/* grab the thread list global lock */
275void dvmLockThreadList(Thread* self);
276/* release the thread list global lock */
277void dvmUnlockThreadList(void);
278
279/*
280 * Thread suspend/resume, used by the GC and debugger.
281 */
282typedef enum SuspendCause {
283 SUSPEND_NOT = 0,
284 SUSPEND_FOR_GC,
285 SUSPEND_FOR_DEBUG,
286 SUSPEND_FOR_DEBUG_EVENT,
287 SUSPEND_FOR_STACK_DUMP,
288 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700289#if defined(WITH_JIT)
Ben Chenga8e64a72009-10-20 13:01:36 -0700290 SUSPEND_FOR_TBL_RESIZE,
291 SUSPEND_FOR_IC_PATCH,
Bill Buzbee27176222009-06-09 09:20:16 -0700292#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800293} SuspendCause;
294void dvmSuspendThread(Thread* thread);
295void dvmSuspendSelf(bool jdwpActivity);
296void dvmResumeThread(Thread* thread);
297void dvmSuspendAllThreads(SuspendCause why);
298void dvmResumeAllThreads(SuspendCause why);
299void dvmUndoDebuggerSuspensions(void);
300
301/*
302 * Check suspend state. Grab threadListLock before calling.
303 */
304bool dvmIsSuspended(Thread* thread);
305
306/*
307 * Wait until a thread has suspended. (Used by debugger support.)
308 */
309void dvmWaitForSuspend(Thread* thread);
310
311/*
312 * Check to see if we should be suspended now. If so, suspend ourselves
313 * by sleeping on a condition variable.
314 *
315 * If "self" is NULL, this will use dvmThreadSelf().
316 */
317bool dvmCheckSuspendPending(Thread* self);
318
319/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700320 * Fast test for use in the interpreter. Returns "true" if our suspend
321 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800322 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700323INLINE bool dvmCheckSuspendQuick(Thread* self) {
324 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800325}
326
327/*
328 * Used when changing thread state. Threads may only change their own.
329 * The "self" argument, which may be NULL, is accepted as an optimization.
330 *
331 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
332 * or THREAD_MONITOR), do so in the same function as the wait -- this records
333 * the current stack depth for the GC.
334 *
335 * If you're changing to THREAD_RUNNING, this will check for suspension.
336 *
337 * Returns the old status.
338 */
339ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
340
341/*
342 * Initialize a mutex.
343 */
344INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
345{
346#ifdef CHECK_MUTEX
347 pthread_mutexattr_t attr;
348 int cc;
349
350 pthread_mutexattr_init(&attr);
351 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
352 assert(cc == 0);
353 pthread_mutex_init(pMutex, &attr);
354 pthread_mutexattr_destroy(&attr);
355#else
356 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
357#endif
358}
359
360/*
361 * Grab a plain mutex.
362 */
363INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
364{
365 int cc = pthread_mutex_lock(pMutex);
366 assert(cc == 0);
367}
368
369/*
370 * Unlock pthread mutex.
371 */
372INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
373{
374 int cc = pthread_mutex_unlock(pMutex);
375 assert(cc == 0);
376}
377
378/*
379 * Destroy a mutex.
380 */
381INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
382{
383 int cc = pthread_mutex_destroy(pMutex);
384 assert(cc == 0);
385}
386
387/*
388 * Create a thread as a result of java.lang.Thread.start().
389 */
390bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
391
392/*
393 * Create a thread internal to the VM. It's visible to interpreted code,
394 * but found in the "system" thread group rather than "main".
395 */
396bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
397 InternalThreadStart func, void* funcArg);
398
399/*
400 * Attach or detach the current thread from the VM.
401 */
402bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
403void dvmDetachCurrentThread(void);
404
405/*
406 * Get the "main" or "system" thread group.
407 */
408Object* dvmGetMainThreadGroup(void);
409Object* dvmGetSystemThreadGroup(void);
410
411/*
412 * Given a java/lang/VMThread object, return our Thread.
413 */
414Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
415
416/*
417 * Sleep in a thread. Returns when the sleep timer returns or the thread
418 * is interrupted.
419 */
420void dvmThreadSleep(u8 msec, u4 nsec);
421
422/*
423 * Get the name of a thread. (For safety, hold the thread list lock.)
424 */
425char* dvmGetThreadName(Thread* thread);
426
427/*
428 * Return true if a thread is on the internal list. If it is, the
429 * thread is part of the GC's root set.
430 */
431bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700432
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800433/*
434 * Get/set the JNIEnv field.
435 */
436INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
437INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
438
439/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800440 * Update the priority value of the underlying pthread.
441 */
442void dvmChangeThreadPriority(Thread* thread, int newPriority);
443
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800444/*
445 * Debug: dump information about a single thread.
446 */
447void dvmDumpThread(Thread* thread, bool isRunning);
448void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
449 bool isRunning);
450
451/*
452 * Debug: dump information about all threads.
453 */
454void dvmDumpAllThreads(bool grabLock);
455void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
456
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800457#ifdef WITH_MONITOR_TRACKING
458/*
459 * Track locks held by the current thread, along with the stack trace at
460 * the point the lock was acquired.
461 *
462 * At any given time the number of locks held across the VM should be
463 * fairly small, so there's no reason not to generate and store the entire
464 * stack trace.
465 */
466typedef struct LockedObjectData {
467 /* the locked object */
468 struct Object* obj;
469
470 /* number of times it has been locked recursively (zero-based ref count) */
471 int recursionCount;
472
473 /* stack trace at point of initial acquire */
474 u4 stackDepth;
475 int* rawStackTrace;
476
477 struct LockedObjectData* next;
478} LockedObjectData;
479
480/*
481 * Add/remove/find objects from the thread's monitor list.
482 */
483void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
484void dvmRemoveFromMonitorList(Thread* self, Object* obj);
485LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
486#endif
487
488#endif /*_DALVIK_THREAD*/