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