blob: e2af2531d3bc11c58bdfa132dff488cef972575e [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
Andy McFadden2b94b302010-03-09 16:38:36 -080025#include <cutils/sched_policy.h>
26
27
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080028#if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
Andy McFadden0083d372009-08-21 14:44:04 -070029/* glibc lacks this unless you #define __USE_UNIX98 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080030int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
31enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
32#endif
33
34#ifdef WITH_MONITOR_TRACKING
35struct LockedObjectData;
36#endif
37
38/*
39 * Current status; these map to JDWP constants, so don't rearrange them.
40 * (If you do alter this, update the strings in dvmDumpThread and the
41 * conversion table in VMThread.java.)
42 *
43 * Note that "suspended" is orthogonal to these values (so says JDWP).
44 */
45typedef enum ThreadStatus {
46 /* these match up with JDWP values */
47 THREAD_ZOMBIE = 0, /* TERMINATED */
48 THREAD_RUNNING = 1, /* RUNNABLE or running now */
49 THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */
50 THREAD_MONITOR = 3, /* BLOCKED on a monitor */
51 THREAD_WAIT = 4, /* WAITING in Object.wait() */
52 /* non-JDWP states */
53 THREAD_INITIALIZING = 5, /* allocated, not yet running */
54 THREAD_STARTING = 6, /* started, not yet on thread list */
55 THREAD_NATIVE = 7, /* off in a JNI native method */
56 THREAD_VMWAIT = 8, /* waiting on a VM resource */
57} ThreadStatus;
58
59/* thread priorities, from java.lang.Thread */
60enum {
61 THREAD_MIN_PRIORITY = 1,
62 THREAD_NORM_PRIORITY = 5,
63 THREAD_MAX_PRIORITY = 10,
64};
65
66
67/* initialization */
68bool dvmThreadStartup(void);
69bool dvmThreadObjStartup(void);
70void dvmThreadShutdown(void);
71void dvmSlayDaemons(void);
72
73
Andy McFaddend5ab7262009-08-25 07:19:34 -070074#define kJniLocalRefMin 32
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080075#define kJniLocalRefMax 512 /* arbitrary; should be plenty */
76#define kInternalRefDefault 32 /* equally arbitrary */
77#define kInternalRefMax 4096 /* mainly a sanity check */
78
79#define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
Andy McFadden39b99b02009-05-11 14:39:13 -070080#define kDefaultStackSize (12*1024) /* three 4K pages */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080081#define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
82
83/*
Bob Lee2fe146a2009-09-10 00:36:29 +020084 * System thread state. See native/SystemThread.h.
85 */
86typedef struct SystemThread SystemThread;
87
88/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080089 * Our per-thread data.
90 *
91 * These are allocated on the system heap.
92 */
93typedef struct Thread {
94 /* small unique integer; useful for "thin" locks and debug messages */
95 u4 threadId;
96
97 /*
98 * Thread's current status. Can only be changed by the thread itself
99 * (i.e. don't mess with this from other threads).
100 */
Bob Lee9dc72a32009-09-04 18:28:16 -0700101 volatile ThreadStatus status;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800102
103 /*
104 * This is the number of times the thread has been suspended. When the
105 * count drops to zero, the thread resumes.
106 *
107 * "dbgSuspendCount" is the portion of the suspend count that the
108 * debugger is responsible for. This has to be tracked separately so
109 * that we can recover correctly if the debugger abruptly disconnects
110 * (suspendCount -= dbgSuspendCount). The debugger should not be able
111 * to resume GC-suspended threads, because we ignore the debugger while
112 * a GC is in progress.
113 *
114 * Both of these are guarded by gDvm.threadSuspendCountLock.
115 *
116 * (We could store both of these in the same 32-bit, using 16-bit
117 * halves, to make atomic ops possible. In practice, you only need
118 * to read suspendCount, and we need to hold a mutex when making
119 * changes, so there's no need to merge them. Note the non-debug
120 * component will rarely be other than 1 or 0 -- not sure it's even
121 * possible with the way mutexes are currently used.)
122 */
123 int suspendCount;
124 int dbgSuspendCount;
125
126 /*
127 * Set to true when the thread suspends itself, false when it wakes up.
128 * This is only expected to be set when status==THREAD_RUNNING.
129 */
130 bool isSuspended;
131
132 /* thread handle, as reported by pthread_self() */
133 pthread_t handle;
134
135 /* thread ID, only useful under Linux */
136 pid_t systemTid;
137
138 /* start (high addr) of interp stack (subtract size to get malloc addr) */
139 u1* interpStackStart;
140
141 /* current limit of stack; flexes for StackOverflowError */
142 const u1* interpStackEnd;
143
144 /* interpreter stack size; our stacks are fixed-length */
145 int interpStackSize;
146 bool stackOverflowed;
147
148 /* FP of bottom-most (currently executing) stack frame on interp stack */
149 void* curFrame;
150
151 /* current exception, or NULL if nothing pending */
152 Object* exception;
153
154 /* the java/lang/Thread that we are associated with */
155 Object* threadObj;
156
157 /* the JNIEnv pointer associated with this thread */
158 JNIEnv* jniEnv;
159
160 /* internal reference tracking */
161 ReferenceTable internalLocalRefTable;
162
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800163#if defined(WITH_JIT)
164 /*
165 * Whether the current top VM frame is in the interpreter or JIT cache:
166 * NULL : in the interpreter
167 * non-NULL: entry address of the JIT'ed code (the actual value doesn't
168 * matter)
169 */
170 void* inJitCodeCache;
171#endif
172
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800173 /* JNI local reference tracking */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700174#ifdef USE_INDIRECT_REF
175 IndirectRefTable jniLocalRefTable;
176#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800177 ReferenceTable jniLocalRefTable;
Andy McFaddend5ab7262009-08-25 07:19:34 -0700178#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800179
180 /* JNI native monitor reference tracking (initialized on first use) */
181 ReferenceTable jniMonitorRefTable;
182
183 /* hack to make JNI_OnLoad work right */
184 Object* classLoaderOverride;
185
Carl Shapirob4539192010-01-04 16:50:00 -0800186 /* mutex to guard the interrupted and the waitMonitor members */
187 pthread_mutex_t waitMutex;
188
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800189 /* pointer to the monitor lock we're currently waiting on */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800190 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800191 /* TODO: consider changing this to Object* for better JDWP interaction */
192 Monitor* waitMonitor;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800193
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800194 /* thread "interrupted" status; stays raised until queried or thrown */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800195 /* guarded by waitMutex */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800196 bool interrupted;
197
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800198 /* links to the next thread in the wait set this thread is part of */
199 struct Thread* waitNext;
200
201 /* object to sleep on while we are waiting for a monitor */
202 pthread_cond_t waitCond;
203
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800204 /*
205 * Set to true when the thread is in the process of throwing an
206 * OutOfMemoryError.
207 */
208 bool throwingOOME;
209
210 /* links to rest of thread list; grab global lock before traversing */
211 struct Thread* prev;
212 struct Thread* next;
213
Andy McFadden909ce242009-12-10 16:38:30 -0800214 /* used by threadExitCheck when a thread exits without detaching */
215 int threadExitCheckCount;
216
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800217 /* JDWP invoke-during-breakpoint support */
218 DebugInvokeReq invokeReq;
219
220#ifdef WITH_MONITOR_TRACKING
221 /* objects locked by this thread; most recent is at head of list */
222 struct LockedObjectData* pLockedObjects;
223#endif
224
225#ifdef WITH_ALLOC_LIMITS
226 /* allocation limit, for Debug.setAllocationLimit() regression testing */
227 int allocLimit;
228#endif
229
230#ifdef WITH_PROFILER
231 /* base time for per-thread CPU timing */
232 bool cpuClockBaseSet;
233 u8 cpuClockBase;
234
235 /* memory allocation profiling state */
236 AllocProfState allocProf;
237#endif
238
239#ifdef WITH_JNI_STACK_CHECK
240 u4 stackCrc;
241#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700242
243#if WITH_EXTRA_GC_CHECKS > 1
244 /* PC, saved on every instruction; redundant with StackSaveArea */
245 const u2* currentPc2;
246#endif
Jeff Hao97319a82009-08-12 16:57:15 -0700247
248#if defined(WITH_SELF_VERIFICATION)
249 /* Buffer for register state during self verification */
250 struct ShadowSpace* shadowSpace;
251#endif
Android Git Automerger4d3b5842009-09-09 10:48:47 -0700252
Bob Lee2fe146a2009-09-10 00:36:29 +0200253 /* system thread state */
254 SystemThread* systemThread;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800255} Thread;
256
257/* start point for an internal thread; mimics pthread args */
258typedef void* (*InternalThreadStart)(void* arg);
259
260/* args for internal thread creation */
261typedef struct InternalStartArgs {
262 /* inputs */
263 InternalThreadStart func;
264 void* funcArg;
265 char* name;
266 Object* group;
267 bool isDaemon;
268 /* result */
269 volatile Thread** pThread;
270 volatile int* pCreateStatus;
271} InternalStartArgs;
272
273/* finish init */
274bool dvmPrepMainForJni(JNIEnv* pEnv);
275bool dvmPrepMainThread(void);
276
277/* utility function to get the tid */
278pid_t dvmGetSysThreadId(void);
279
280/*
281 * Get our Thread* from TLS.
282 *
283 * Returns NULL if this isn't a thread that the VM is aware of.
284 */
285Thread* dvmThreadSelf(void);
286
287/* grab the thread list global lock */
288void dvmLockThreadList(Thread* self);
289/* release the thread list global lock */
290void dvmUnlockThreadList(void);
291
292/*
293 * Thread suspend/resume, used by the GC and debugger.
294 */
295typedef enum SuspendCause {
296 SUSPEND_NOT = 0,
297 SUSPEND_FOR_GC,
298 SUSPEND_FOR_DEBUG,
299 SUSPEND_FOR_DEBUG_EVENT,
300 SUSPEND_FOR_STACK_DUMP,
301 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700302#if defined(WITH_JIT)
Ben Cheng60c24f42010-01-04 12:29:56 -0800303 SUSPEND_FOR_TBL_RESIZE, // jit-table resize
304 SUSPEND_FOR_IC_PATCH, // polymorphic callsite inline-cache patch
305 SUSPEND_FOR_CC_RESET, // code-cache reset
Bill Buzbee964a7b02010-01-28 12:54:19 -0800306 SUSPEND_FOR_REFRESH, // Reload data cached in interpState
Bill Buzbee27176222009-06-09 09:20:16 -0700307#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800308} SuspendCause;
309void dvmSuspendThread(Thread* thread);
310void dvmSuspendSelf(bool jdwpActivity);
311void dvmResumeThread(Thread* thread);
312void dvmSuspendAllThreads(SuspendCause why);
313void dvmResumeAllThreads(SuspendCause why);
314void dvmUndoDebuggerSuspensions(void);
315
316/*
317 * Check suspend state. Grab threadListLock before calling.
318 */
319bool dvmIsSuspended(Thread* thread);
320
321/*
322 * Wait until a thread has suspended. (Used by debugger support.)
323 */
324void dvmWaitForSuspend(Thread* thread);
325
326/*
327 * Check to see if we should be suspended now. If so, suspend ourselves
328 * by sleeping on a condition variable.
329 *
330 * If "self" is NULL, this will use dvmThreadSelf().
331 */
332bool dvmCheckSuspendPending(Thread* self);
333
334/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700335 * Fast test for use in the interpreter. Returns "true" if our suspend
336 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800337 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700338INLINE bool dvmCheckSuspendQuick(Thread* self) {
339 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800340}
341
342/*
343 * Used when changing thread state. Threads may only change their own.
344 * The "self" argument, which may be NULL, is accepted as an optimization.
345 *
346 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
347 * or THREAD_MONITOR), do so in the same function as the wait -- this records
348 * the current stack depth for the GC.
349 *
350 * If you're changing to THREAD_RUNNING, this will check for suspension.
351 *
352 * Returns the old status.
353 */
354ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
355
356/*
357 * Initialize a mutex.
358 */
359INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
360{
361#ifdef CHECK_MUTEX
362 pthread_mutexattr_t attr;
363 int cc;
364
365 pthread_mutexattr_init(&attr);
366 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
367 assert(cc == 0);
368 pthread_mutex_init(pMutex, &attr);
369 pthread_mutexattr_destroy(&attr);
370#else
371 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
372#endif
373}
374
375/*
376 * Grab a plain mutex.
377 */
378INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
379{
Carl Shapiro98389d02010-02-14 23:11:47 -0800380 int cc __attribute__ ((__unused__));
381 cc = pthread_mutex_lock(pMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800382 assert(cc == 0);
383}
384
385/*
Bill Buzbee964a7b02010-01-28 12:54:19 -0800386 * Try grabbing a plain mutex. Returns 0 if successful.
387 */
388INLINE int dvmTryLockMutex(pthread_mutex_t* pMutex)
389{
390 return pthread_mutex_trylock(pMutex);
391}
392
393/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800394 * Unlock pthread mutex.
395 */
396INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
397{
Carl Shapiro98389d02010-02-14 23:11:47 -0800398 int cc __attribute__ ((__unused__));
399 cc = pthread_mutex_unlock(pMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800400 assert(cc == 0);
401}
402
403/*
404 * Destroy a mutex.
405 */
406INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
407{
Carl Shapiro98389d02010-02-14 23:11:47 -0800408 int cc __attribute__ ((__unused__));
409 cc = pthread_mutex_destroy(pMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800410 assert(cc == 0);
411}
412
413/*
414 * Create a thread as a result of java.lang.Thread.start().
415 */
416bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
417
418/*
419 * Create a thread internal to the VM. It's visible to interpreted code,
420 * but found in the "system" thread group rather than "main".
421 */
422bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
423 InternalThreadStart func, void* funcArg);
424
425/*
426 * Attach or detach the current thread from the VM.
427 */
428bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
429void dvmDetachCurrentThread(void);
430
431/*
432 * Get the "main" or "system" thread group.
433 */
434Object* dvmGetMainThreadGroup(void);
435Object* dvmGetSystemThreadGroup(void);
436
437/*
438 * Given a java/lang/VMThread object, return our Thread.
439 */
440Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
441
442/*
Andy McFadden2b94b302010-03-09 16:38:36 -0800443 * Given a pthread handle, return the associated Thread*.
Andy McFaddenfd542662010-03-12 13:39:59 -0800444 * Caller must hold the thread list lock.
Andy McFadden2b94b302010-03-09 16:38:36 -0800445 *
446 * Returns NULL if the thread was not found.
447 */
448Thread* dvmGetThreadByHandle(pthread_t handle);
449
450/*
Andy McFaddenfd542662010-03-12 13:39:59 -0800451 * Given a thread ID, return the associated Thread*.
452 * Caller must hold the thread list lock.
453 *
454 * Returns NULL if the thread was not found.
455 */
456Thread* dvmGetThreadByThreadId(u4 threadId);
457
458/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800459 * Sleep in a thread. Returns when the sleep timer returns or the thread
460 * is interrupted.
461 */
462void dvmThreadSleep(u8 msec, u4 nsec);
463
464/*
465 * Get the name of a thread. (For safety, hold the thread list lock.)
466 */
467char* dvmGetThreadName(Thread* thread);
468
469/*
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800470 * Convert ThreadStatus to a string.
471 */
472const char* dvmGetThreadStatusStr(ThreadStatus status);
473
474/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800475 * Return true if a thread is on the internal list. If it is, the
476 * thread is part of the GC's root set.
477 */
478bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700479
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800480/*
481 * Get/set the JNIEnv field.
482 */
483INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
484INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
485
486/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800487 * Update the priority value of the underlying pthread.
488 */
489void dvmChangeThreadPriority(Thread* thread, int newPriority);
490
Andy McFadden2b94b302010-03-09 16:38:36 -0800491/* "change flags" values for raise/reset thread priority calls */
492#define kChangedPriority 0x01
493#define kChangedPolicy 0x02
494
495/*
496 * If necessary, raise the thread's priority to nice=0 cgroup=fg.
497 *
498 * Returns bit flags indicating changes made (zero if nothing was done).
499 */
500int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
501 SchedPolicy* pSavedThreadPolicy);
502
503/*
504 * Drop the thread priority to what it was before an earlier call to
505 * dvmRaiseThreadPriorityIfNeeded().
506 */
507void dvmResetThreadPriority(Thread* thread, int changeFlags,
508 int savedThreadPrio, SchedPolicy savedThreadPolicy);
509
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800510/*
511 * Debug: dump information about a single thread.
512 */
513void dvmDumpThread(Thread* thread, bool isRunning);
514void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
515 bool isRunning);
516
517/*
518 * Debug: dump information about all threads.
519 */
520void dvmDumpAllThreads(bool grabLock);
521void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
522
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800523#ifdef WITH_MONITOR_TRACKING
524/*
525 * Track locks held by the current thread, along with the stack trace at
526 * the point the lock was acquired.
527 *
528 * At any given time the number of locks held across the VM should be
529 * fairly small, so there's no reason not to generate and store the entire
530 * stack trace.
531 */
532typedef struct LockedObjectData {
533 /* the locked object */
534 struct Object* obj;
535
536 /* number of times it has been locked recursively (zero-based ref count) */
537 int recursionCount;
538
539 /* stack trace at point of initial acquire */
540 u4 stackDepth;
541 int* rawStackTrace;
542
543 struct LockedObjectData* next;
544} LockedObjectData;
545
546/*
547 * Add/remove/find objects from the thread's monitor list.
548 */
549void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
550void dvmRemoveFromMonitorList(Thread* self, Object* obj);
551LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
552#endif
553
554#endif /*_DALVIK_THREAD*/