blob: 194e778866cf322abf957aa70787639d0e9f01a8 [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 */
Bob Lee9dc72a32009-09-04 18:28:16 -070056 THREAD_PAGING = 9, /* paging memory */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080057} 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/*
84 * Our per-thread data.
85 *
86 * These are allocated on the system heap.
87 */
88typedef struct Thread {
89 /* small unique integer; useful for "thin" locks and debug messages */
90 u4 threadId;
91
92 /*
93 * Thread's current status. Can only be changed by the thread itself
94 * (i.e. don't mess with this from other threads).
95 */
Bob Lee9dc72a32009-09-04 18:28:16 -070096 volatile ThreadStatus status;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080097
98 /*
99 * This is the number of times the thread has been suspended. When the
100 * count drops to zero, the thread resumes.
101 *
102 * "dbgSuspendCount" is the portion of the suspend count that the
103 * debugger is responsible for. This has to be tracked separately so
104 * that we can recover correctly if the debugger abruptly disconnects
105 * (suspendCount -= dbgSuspendCount). The debugger should not be able
106 * to resume GC-suspended threads, because we ignore the debugger while
107 * a GC is in progress.
108 *
109 * Both of these are guarded by gDvm.threadSuspendCountLock.
110 *
111 * (We could store both of these in the same 32-bit, using 16-bit
112 * halves, to make atomic ops possible. In practice, you only need
113 * to read suspendCount, and we need to hold a mutex when making
114 * changes, so there's no need to merge them. Note the non-debug
115 * component will rarely be other than 1 or 0 -- not sure it's even
116 * possible with the way mutexes are currently used.)
117 */
118 int suspendCount;
119 int dbgSuspendCount;
120
121 /*
122 * Set to true when the thread suspends itself, false when it wakes up.
123 * This is only expected to be set when status==THREAD_RUNNING.
124 */
125 bool isSuspended;
126
127 /* thread handle, as reported by pthread_self() */
128 pthread_t handle;
129
130 /* thread ID, only useful under Linux */
131 pid_t systemTid;
132
133 /* start (high addr) of interp stack (subtract size to get malloc addr) */
134 u1* interpStackStart;
135
136 /* current limit of stack; flexes for StackOverflowError */
137 const u1* interpStackEnd;
138
139 /* interpreter stack size; our stacks are fixed-length */
140 int interpStackSize;
141 bool stackOverflowed;
142
143 /* FP of bottom-most (currently executing) stack frame on interp stack */
144 void* curFrame;
145
146 /* current exception, or NULL if nothing pending */
147 Object* exception;
148
149 /* the java/lang/Thread that we are associated with */
150 Object* threadObj;
151
152 /* the JNIEnv pointer associated with this thread */
153 JNIEnv* jniEnv;
154
155 /* internal reference tracking */
156 ReferenceTable internalLocalRefTable;
157
158 /* JNI local reference tracking */
Andy McFaddend5ab7262009-08-25 07:19:34 -0700159#ifdef USE_INDIRECT_REF
160 IndirectRefTable jniLocalRefTable;
161#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800162 ReferenceTable jniLocalRefTable;
Andy McFaddend5ab7262009-08-25 07:19:34 -0700163#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800164
165 /* JNI native monitor reference tracking (initialized on first use) */
166 ReferenceTable jniMonitorRefTable;
167
168 /* hack to make JNI_OnLoad work right */
169 Object* classLoaderOverride;
170
171 /* pointer to the monitor lock we're currently waiting on */
172 /* (do not set or clear unless the Monitor itself is held) */
173 /* TODO: consider changing this to Object* for better JDWP interaction */
174 Monitor* waitMonitor;
175 /* set when we confirm that the thread must be interrupted from a wait */
176 bool interruptingWait;
177 /* thread "interrupted" status; stays raised until queried or thrown */
178 bool interrupted;
179
180 /*
181 * Set to true when the thread is in the process of throwing an
182 * OutOfMemoryError.
183 */
184 bool throwingOOME;
185
186 /* links to rest of thread list; grab global lock before traversing */
187 struct Thread* prev;
188 struct Thread* next;
189
190 /* JDWP invoke-during-breakpoint support */
191 DebugInvokeReq invokeReq;
192
193#ifdef WITH_MONITOR_TRACKING
194 /* objects locked by this thread; most recent is at head of list */
195 struct LockedObjectData* pLockedObjects;
196#endif
197
198#ifdef WITH_ALLOC_LIMITS
199 /* allocation limit, for Debug.setAllocationLimit() regression testing */
200 int allocLimit;
201#endif
202
203#ifdef WITH_PROFILER
204 /* base time for per-thread CPU timing */
205 bool cpuClockBaseSet;
206 u8 cpuClockBase;
207
208 /* memory allocation profiling state */
209 AllocProfState allocProf;
210#endif
211
212#ifdef WITH_JNI_STACK_CHECK
213 u4 stackCrc;
214#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700215
216#if WITH_EXTRA_GC_CHECKS > 1
217 /* PC, saved on every instruction; redundant with StackSaveArea */
218 const u2* currentPc2;
219#endif
Bob Lee9dc72a32009-09-04 18:28:16 -0700220
221 /* /proc/PID/task/TID/stat */
222 int statFile;
223 /* offset of state char in stat file, last we checked */
224 int stateOffset;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800225} Thread;
226
227/* start point for an internal thread; mimics pthread args */
228typedef void* (*InternalThreadStart)(void* arg);
229
230/* args for internal thread creation */
231typedef struct InternalStartArgs {
232 /* inputs */
233 InternalThreadStart func;
234 void* funcArg;
235 char* name;
236 Object* group;
237 bool isDaemon;
238 /* result */
239 volatile Thread** pThread;
240 volatile int* pCreateStatus;
241} InternalStartArgs;
242
243/* finish init */
244bool dvmPrepMainForJni(JNIEnv* pEnv);
245bool dvmPrepMainThread(void);
246
247/* utility function to get the tid */
248pid_t dvmGetSysThreadId(void);
249
250/*
251 * Get our Thread* from TLS.
252 *
253 * Returns NULL if this isn't a thread that the VM is aware of.
254 */
255Thread* dvmThreadSelf(void);
256
257/* grab the thread list global lock */
258void dvmLockThreadList(Thread* self);
259/* release the thread list global lock */
260void dvmUnlockThreadList(void);
261
262/*
263 * Thread suspend/resume, used by the GC and debugger.
264 */
265typedef enum SuspendCause {
266 SUSPEND_NOT = 0,
267 SUSPEND_FOR_GC,
268 SUSPEND_FOR_DEBUG,
269 SUSPEND_FOR_DEBUG_EVENT,
270 SUSPEND_FOR_STACK_DUMP,
271 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700272#if defined(WITH_JIT)
273 SUSPEND_FOR_JIT,
274#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800275} SuspendCause;
276void dvmSuspendThread(Thread* thread);
277void dvmSuspendSelf(bool jdwpActivity);
278void dvmResumeThread(Thread* thread);
279void dvmSuspendAllThreads(SuspendCause why);
280void dvmResumeAllThreads(SuspendCause why);
281void dvmUndoDebuggerSuspensions(void);
282
283/*
284 * Check suspend state. Grab threadListLock before calling.
285 */
286bool dvmIsSuspended(Thread* thread);
287
288/*
289 * Wait until a thread has suspended. (Used by debugger support.)
290 */
291void dvmWaitForSuspend(Thread* thread);
292
293/*
294 * Check to see if we should be suspended now. If so, suspend ourselves
295 * by sleeping on a condition variable.
296 *
297 * If "self" is NULL, this will use dvmThreadSelf().
298 */
299bool dvmCheckSuspendPending(Thread* self);
300
301/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700302 * Fast test for use in the interpreter. Returns "true" if our suspend
303 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800304 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700305INLINE bool dvmCheckSuspendQuick(Thread* self) {
306 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800307}
308
309/*
310 * Used when changing thread state. Threads may only change their own.
311 * The "self" argument, which may be NULL, is accepted as an optimization.
312 *
313 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
314 * or THREAD_MONITOR), do so in the same function as the wait -- this records
315 * the current stack depth for the GC.
316 *
317 * If you're changing to THREAD_RUNNING, this will check for suspension.
318 *
319 * Returns the old status.
320 */
321ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
322
323/*
324 * Initialize a mutex.
325 */
326INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
327{
328#ifdef CHECK_MUTEX
329 pthread_mutexattr_t attr;
330 int cc;
331
332 pthread_mutexattr_init(&attr);
333 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
334 assert(cc == 0);
335 pthread_mutex_init(pMutex, &attr);
336 pthread_mutexattr_destroy(&attr);
337#else
338 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
339#endif
340}
341
342/*
343 * Grab a plain mutex.
344 */
345INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
346{
347 int cc = pthread_mutex_lock(pMutex);
348 assert(cc == 0);
349}
350
351/*
352 * Unlock pthread mutex.
353 */
354INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
355{
356 int cc = pthread_mutex_unlock(pMutex);
357 assert(cc == 0);
358}
359
360/*
361 * Destroy a mutex.
362 */
363INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
364{
365 int cc = pthread_mutex_destroy(pMutex);
366 assert(cc == 0);
367}
368
369/*
370 * Create a thread as a result of java.lang.Thread.start().
371 */
372bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
373
374/*
375 * Create a thread internal to the VM. It's visible to interpreted code,
376 * but found in the "system" thread group rather than "main".
377 */
378bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
379 InternalThreadStart func, void* funcArg);
380
381/*
382 * Attach or detach the current thread from the VM.
383 */
384bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
385void dvmDetachCurrentThread(void);
386
387/*
388 * Get the "main" or "system" thread group.
389 */
390Object* dvmGetMainThreadGroup(void);
391Object* dvmGetSystemThreadGroup(void);
392
393/*
394 * Given a java/lang/VMThread object, return our Thread.
395 */
396Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
397
398/*
399 * Sleep in a thread. Returns when the sleep timer returns or the thread
400 * is interrupted.
401 */
402void dvmThreadSleep(u8 msec, u4 nsec);
403
404/*
405 * Get the name of a thread. (For safety, hold the thread list lock.)
406 */
407char* dvmGetThreadName(Thread* thread);
408
409/*
410 * Return true if a thread is on the internal list. If it is, the
411 * thread is part of the GC's root set.
412 */
413bool dvmIsOnThreadList(const Thread* thread);
414
415/*
416 * Get/set the JNIEnv field.
417 */
418INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
419INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
420
421/*
San Mehat894dd462009-09-08 20:29:15 -0700422 * Change the scheduling policy of the current process.
423 * This is mapped onto whatever underlying scheme the kernel
424 * supports (cgroups/scheduler policies/wombats/etc)
San Mehat256fc152009-04-21 14:03:06 -0700425 */
San Mehat894dd462009-09-08 20:29:15 -0700426void dvmChangeThreadSchedulerPolicy(SchedPolicy policy);
San Mehat256fc152009-04-21 14:03:06 -0700427
428/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800429 * Update the priority value of the underlying pthread.
430 */
431void dvmChangeThreadPriority(Thread* thread, int newPriority);
432
433
434/*
435 * Debug: dump information about a single thread.
436 */
437void dvmDumpThread(Thread* thread, bool isRunning);
438void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
439 bool isRunning);
440
441/*
442 * Debug: dump information about all threads.
443 */
444void dvmDumpAllThreads(bool grabLock);
445void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
446
Bob Lee9dc72a32009-09-04 18:28:16 -0700447/*
448 * Reads the native thread status. If the thread is in native code, this
449 * function queries the native thread state and converts it to an equivalent
450 * ThreadStatus. If the native status can't be read, this function returns
451 * THREAD_NATIVE.
452 */
453ThreadStatus dvmGetNativeThreadStatus(Thread* thread);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800454
455#ifdef WITH_MONITOR_TRACKING
456/*
457 * Track locks held by the current thread, along with the stack trace at
458 * the point the lock was acquired.
459 *
460 * At any given time the number of locks held across the VM should be
461 * fairly small, so there's no reason not to generate and store the entire
462 * stack trace.
463 */
464typedef struct LockedObjectData {
465 /* the locked object */
466 struct Object* obj;
467
468 /* number of times it has been locked recursively (zero-based ref count) */
469 int recursionCount;
470
471 /* stack trace at point of initial acquire */
472 u4 stackDepth;
473 int* rawStackTrace;
474
475 struct LockedObjectData* next;
476} LockedObjectData;
477
478/*
479 * Add/remove/find objects from the thread's monitor list.
480 */
481void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
482void dvmRemoveFromMonitorList(Thread* self, Object* obj);
483LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
484#endif
485
486#endif /*_DALVIK_THREAD*/