blob: 964c968741223a0bf6d217c4d90e19a4acd3ea4d [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
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800160#if defined(WITH_JIT)
161 /*
162 * Whether the current top VM frame is in the interpreter or JIT cache:
163 * NULL : in the interpreter
164 * non-NULL: entry address of the JIT'ed code (the actual value doesn't
165 * matter)
166 */
167 void* inJitCodeCache;
168#endif
169
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800170 /* JNI local reference tracking */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700171#ifdef USE_INDIRECT_REF
172 IndirectRefTable jniLocalRefTable;
173#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800174 ReferenceTable jniLocalRefTable;
Andy McFaddend5ab7262009-08-25 07:19:34 -0700175#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800176
177 /* JNI native monitor reference tracking (initialized on first use) */
178 ReferenceTable jniMonitorRefTable;
179
180 /* hack to make JNI_OnLoad work right */
181 Object* classLoaderOverride;
182
Carl Shapirob4539192010-01-04 16:50:00 -0800183 /* mutex to guard the interrupted and the waitMonitor members */
184 pthread_mutex_t waitMutex;
185
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800186 /* pointer to the monitor lock we're currently waiting on */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800187 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800188 /* TODO: consider changing this to Object* for better JDWP interaction */
189 Monitor* waitMonitor;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800190
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800191 /* thread "interrupted" status; stays raised until queried or thrown */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800192 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800193 bool interrupted;
194
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800195 /* links to the next thread in the wait set this thread is part of */
196 struct Thread* waitNext;
197
198 /* object to sleep on while we are waiting for a monitor */
199 pthread_cond_t waitCond;
200
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800201 /*
202 * Set to true when the thread is in the process of throwing an
203 * OutOfMemoryError.
204 */
205 bool throwingOOME;
206
207 /* links to rest of thread list; grab global lock before traversing */
208 struct Thread* prev;
209 struct Thread* next;
210
Andy McFadden909ce242009-12-10 16:38:30 -0800211 /* used by threadExitCheck when a thread exits without detaching */
212 int threadExitCheckCount;
213
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800214 /* JDWP invoke-during-breakpoint support */
215 DebugInvokeReq invokeReq;
216
217#ifdef WITH_MONITOR_TRACKING
218 /* objects locked by this thread; most recent is at head of list */
219 struct LockedObjectData* pLockedObjects;
220#endif
221
222#ifdef WITH_ALLOC_LIMITS
223 /* allocation limit, for Debug.setAllocationLimit() regression testing */
224 int allocLimit;
225#endif
226
227#ifdef WITH_PROFILER
228 /* base time for per-thread CPU timing */
229 bool cpuClockBaseSet;
230 u8 cpuClockBase;
231
232 /* memory allocation profiling state */
233 AllocProfState allocProf;
234#endif
235
236#ifdef WITH_JNI_STACK_CHECK
237 u4 stackCrc;
238#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700239
240#if WITH_EXTRA_GC_CHECKS > 1
241 /* PC, saved on every instruction; redundant with StackSaveArea */
242 const u2* currentPc2;
243#endif
Jeff Hao97319a82009-08-12 16:57:15 -0700244
245#if defined(WITH_SELF_VERIFICATION)
246 /* Buffer for register state during self verification */
247 struct ShadowSpace* shadowSpace;
248#endif
Android Git Automerger4d3b5842009-09-09 10:48:47 -0700249
Bob Lee2fe146a2009-09-10 00:36:29 +0200250 /* system thread state */
251 SystemThread* systemThread;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800252} Thread;
253
254/* start point for an internal thread; mimics pthread args */
255typedef void* (*InternalThreadStart)(void* arg);
256
257/* args for internal thread creation */
258typedef struct InternalStartArgs {
259 /* inputs */
260 InternalThreadStart func;
261 void* funcArg;
262 char* name;
263 Object* group;
264 bool isDaemon;
265 /* result */
266 volatile Thread** pThread;
267 volatile int* pCreateStatus;
268} InternalStartArgs;
269
270/* finish init */
271bool dvmPrepMainForJni(JNIEnv* pEnv);
272bool dvmPrepMainThread(void);
273
274/* utility function to get the tid */
275pid_t dvmGetSysThreadId(void);
276
277/*
278 * Get our Thread* from TLS.
279 *
280 * Returns NULL if this isn't a thread that the VM is aware of.
281 */
282Thread* dvmThreadSelf(void);
283
284/* grab the thread list global lock */
285void dvmLockThreadList(Thread* self);
286/* release the thread list global lock */
287void dvmUnlockThreadList(void);
288
289/*
290 * Thread suspend/resume, used by the GC and debugger.
291 */
292typedef enum SuspendCause {
293 SUSPEND_NOT = 0,
294 SUSPEND_FOR_GC,
295 SUSPEND_FOR_DEBUG,
296 SUSPEND_FOR_DEBUG_EVENT,
297 SUSPEND_FOR_STACK_DUMP,
298 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700299#if defined(WITH_JIT)
Ben Cheng60c24f42010-01-04 12:29:56 -0800300 SUSPEND_FOR_TBL_RESIZE, // jit-table resize
301 SUSPEND_FOR_IC_PATCH, // polymorphic callsite inline-cache patch
302 SUSPEND_FOR_CC_RESET, // code-cache reset
Bill Buzbee964a7b02010-01-28 12:54:19 -0800303 SUSPEND_FOR_REFRESH, // Reload data cached in interpState
Bill Buzbee27176222009-06-09 09:20:16 -0700304#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800305} SuspendCause;
306void dvmSuspendThread(Thread* thread);
307void dvmSuspendSelf(bool jdwpActivity);
308void dvmResumeThread(Thread* thread);
309void dvmSuspendAllThreads(SuspendCause why);
310void dvmResumeAllThreads(SuspendCause why);
311void dvmUndoDebuggerSuspensions(void);
312
313/*
314 * Check suspend state. Grab threadListLock before calling.
315 */
316bool dvmIsSuspended(Thread* thread);
317
318/*
319 * Wait until a thread has suspended. (Used by debugger support.)
320 */
321void dvmWaitForSuspend(Thread* thread);
322
323/*
324 * Check to see if we should be suspended now. If so, suspend ourselves
325 * by sleeping on a condition variable.
326 *
327 * If "self" is NULL, this will use dvmThreadSelf().
328 */
329bool dvmCheckSuspendPending(Thread* self);
330
331/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700332 * Fast test for use in the interpreter. Returns "true" if our suspend
333 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800334 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700335INLINE bool dvmCheckSuspendQuick(Thread* self) {
336 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800337}
338
339/*
340 * Used when changing thread state. Threads may only change their own.
341 * The "self" argument, which may be NULL, is accepted as an optimization.
342 *
343 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
344 * or THREAD_MONITOR), do so in the same function as the wait -- this records
345 * the current stack depth for the GC.
346 *
347 * If you're changing to THREAD_RUNNING, this will check for suspension.
348 *
349 * Returns the old status.
350 */
351ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
352
353/*
354 * Initialize a mutex.
355 */
356INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
357{
358#ifdef CHECK_MUTEX
359 pthread_mutexattr_t attr;
360 int cc;
361
362 pthread_mutexattr_init(&attr);
363 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
364 assert(cc == 0);
365 pthread_mutex_init(pMutex, &attr);
366 pthread_mutexattr_destroy(&attr);
367#else
368 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
369#endif
370}
371
372/*
373 * Grab a plain mutex.
374 */
375INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
376{
377 int cc = pthread_mutex_lock(pMutex);
378 assert(cc == 0);
379}
380
381/*
Bill Buzbee964a7b02010-01-28 12:54:19 -0800382 * Try grabbing a plain mutex. Returns 0 if successful.
383 */
384INLINE int dvmTryLockMutex(pthread_mutex_t* pMutex)
385{
386 return pthread_mutex_trylock(pMutex);
387}
388
389/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800390 * Unlock pthread mutex.
391 */
392INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
393{
394 int cc = pthread_mutex_unlock(pMutex);
395 assert(cc == 0);
396}
397
398/*
399 * Destroy a mutex.
400 */
401INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
402{
403 int cc = pthread_mutex_destroy(pMutex);
404 assert(cc == 0);
405}
406
407/*
408 * Create a thread as a result of java.lang.Thread.start().
409 */
410bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
411
412/*
413 * Create a thread internal to the VM. It's visible to interpreted code,
414 * but found in the "system" thread group rather than "main".
415 */
416bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
417 InternalThreadStart func, void* funcArg);
418
419/*
420 * Attach or detach the current thread from the VM.
421 */
422bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
423void dvmDetachCurrentThread(void);
424
425/*
426 * Get the "main" or "system" thread group.
427 */
428Object* dvmGetMainThreadGroup(void);
429Object* dvmGetSystemThreadGroup(void);
430
431/*
432 * Given a java/lang/VMThread object, return our Thread.
433 */
434Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
435
436/*
437 * Sleep in a thread. Returns when the sleep timer returns or the thread
438 * is interrupted.
439 */
440void dvmThreadSleep(u8 msec, u4 nsec);
441
442/*
443 * Get the name of a thread. (For safety, hold the thread list lock.)
444 */
445char* dvmGetThreadName(Thread* thread);
446
447/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800448 * Convert ThreadStatus to a string.
449 */
450const char* dvmGetThreadStatusStr(ThreadStatus status);
451
452/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800453 * Return true if a thread is on the internal list. If it is, the
454 * thread is part of the GC's root set.
455 */
456bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700457
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800458/*
459 * Get/set the JNIEnv field.
460 */
461INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
462INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
463
464/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800465 * Update the priority value of the underlying pthread.
466 */
467void dvmChangeThreadPriority(Thread* thread, int newPriority);
468
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800469/*
470 * Debug: dump information about a single thread.
471 */
472void dvmDumpThread(Thread* thread, bool isRunning);
473void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
474 bool isRunning);
475
476/*
477 * Debug: dump information about all threads.
478 */
479void dvmDumpAllThreads(bool grabLock);
480void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
481
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800482#ifdef WITH_MONITOR_TRACKING
483/*
484 * Track locks held by the current thread, along with the stack trace at
485 * the point the lock was acquired.
486 *
487 * At any given time the number of locks held across the VM should be
488 * fairly small, so there's no reason not to generate and store the entire
489 * stack trace.
490 */
491typedef struct LockedObjectData {
492 /* the locked object */
493 struct Object* obj;
494
495 /* number of times it has been locked recursively (zero-based ref count) */
496 int recursionCount;
497
498 /* stack trace at point of initial acquire */
499 u4 stackDepth;
500 int* rawStackTrace;
501
502 struct LockedObjectData* next;
503} LockedObjectData;
504
505/*
506 * Add/remove/find objects from the thread's monitor list.
507 */
508void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
509void dvmRemoveFromMonitorList(Thread* self, Object* obj);
510LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
511#endif
512
513#endif /*_DALVIK_THREAD*/