blob: 179a920c256cb6b13099b6d8b241fed1f9094936 [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 */
174 /* (do not set or clear unless the Monitor itself is held) */
175 /* TODO: consider changing this to Object* for better JDWP interaction */
176 Monitor* waitMonitor;
177 /* set when we confirm that the thread must be interrupted from a wait */
178 bool interruptingWait;
179 /* thread "interrupted" status; stays raised until queried or thrown */
180 bool interrupted;
181
182 /*
183 * Set to true when the thread is in the process of throwing an
184 * OutOfMemoryError.
185 */
186 bool throwingOOME;
187
188 /* links to rest of thread list; grab global lock before traversing */
189 struct Thread* prev;
190 struct Thread* next;
191
192 /* JDWP invoke-during-breakpoint support */
193 DebugInvokeReq invokeReq;
194
195#ifdef WITH_MONITOR_TRACKING
196 /* objects locked by this thread; most recent is at head of list */
197 struct LockedObjectData* pLockedObjects;
198#endif
199
200#ifdef WITH_ALLOC_LIMITS
201 /* allocation limit, for Debug.setAllocationLimit() regression testing */
202 int allocLimit;
203#endif
204
205#ifdef WITH_PROFILER
206 /* base time for per-thread CPU timing */
207 bool cpuClockBaseSet;
208 u8 cpuClockBase;
209
210 /* memory allocation profiling state */
211 AllocProfState allocProf;
212#endif
213
214#ifdef WITH_JNI_STACK_CHECK
215 u4 stackCrc;
216#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700217
218#if WITH_EXTRA_GC_CHECKS > 1
219 /* PC, saved on every instruction; redundant with StackSaveArea */
220 const u2* currentPc2;
221#endif
Jeff Hao97319a82009-08-12 16:57:15 -0700222
223#if defined(WITH_SELF_VERIFICATION)
224 /* Buffer for register state during self verification */
225 struct ShadowSpace* shadowSpace;
226#endif
Android Git Automerger4d3b5842009-09-09 10:48:47 -0700227
Bob Lee2fe146a2009-09-10 00:36:29 +0200228 /* system thread state */
229 SystemThread* systemThread;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800230} Thread;
231
232/* start point for an internal thread; mimics pthread args */
233typedef void* (*InternalThreadStart)(void* arg);
234
235/* args for internal thread creation */
236typedef struct InternalStartArgs {
237 /* inputs */
238 InternalThreadStart func;
239 void* funcArg;
240 char* name;
241 Object* group;
242 bool isDaemon;
243 /* result */
244 volatile Thread** pThread;
245 volatile int* pCreateStatus;
246} InternalStartArgs;
247
248/* finish init */
249bool dvmPrepMainForJni(JNIEnv* pEnv);
250bool dvmPrepMainThread(void);
251
252/* utility function to get the tid */
253pid_t dvmGetSysThreadId(void);
254
255/*
256 * Get our Thread* from TLS.
257 *
258 * Returns NULL if this isn't a thread that the VM is aware of.
259 */
260Thread* dvmThreadSelf(void);
261
262/* grab the thread list global lock */
263void dvmLockThreadList(Thread* self);
264/* release the thread list global lock */
265void dvmUnlockThreadList(void);
266
267/*
268 * Thread suspend/resume, used by the GC and debugger.
269 */
270typedef enum SuspendCause {
271 SUSPEND_NOT = 0,
272 SUSPEND_FOR_GC,
273 SUSPEND_FOR_DEBUG,
274 SUSPEND_FOR_DEBUG_EVENT,
275 SUSPEND_FOR_STACK_DUMP,
276 SUSPEND_FOR_DEX_OPT,
Bill Buzbee27176222009-06-09 09:20:16 -0700277#if defined(WITH_JIT)
278 SUSPEND_FOR_JIT,
279#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800280} SuspendCause;
281void dvmSuspendThread(Thread* thread);
282void dvmSuspendSelf(bool jdwpActivity);
283void dvmResumeThread(Thread* thread);
284void dvmSuspendAllThreads(SuspendCause why);
285void dvmResumeAllThreads(SuspendCause why);
286void dvmUndoDebuggerSuspensions(void);
287
288/*
289 * Check suspend state. Grab threadListLock before calling.
290 */
291bool dvmIsSuspended(Thread* thread);
292
293/*
294 * Wait until a thread has suspended. (Used by debugger support.)
295 */
296void dvmWaitForSuspend(Thread* thread);
297
298/*
299 * Check to see if we should be suspended now. If so, suspend ourselves
300 * by sleeping on a condition variable.
301 *
302 * If "self" is NULL, this will use dvmThreadSelf().
303 */
304bool dvmCheckSuspendPending(Thread* self);
305
306/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700307 * Fast test for use in the interpreter. Returns "true" if our suspend
308 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800309 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700310INLINE bool dvmCheckSuspendQuick(Thread* self) {
311 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800312}
313
314/*
315 * Used when changing thread state. Threads may only change their own.
316 * The "self" argument, which may be NULL, is accepted as an optimization.
317 *
318 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
319 * or THREAD_MONITOR), do so in the same function as the wait -- this records
320 * the current stack depth for the GC.
321 *
322 * If you're changing to THREAD_RUNNING, this will check for suspension.
323 *
324 * Returns the old status.
325 */
326ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
327
328/*
329 * Initialize a mutex.
330 */
331INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
332{
333#ifdef CHECK_MUTEX
334 pthread_mutexattr_t attr;
335 int cc;
336
337 pthread_mutexattr_init(&attr);
338 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
339 assert(cc == 0);
340 pthread_mutex_init(pMutex, &attr);
341 pthread_mutexattr_destroy(&attr);
342#else
343 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
344#endif
345}
346
347/*
348 * Grab a plain mutex.
349 */
350INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
351{
352 int cc = pthread_mutex_lock(pMutex);
353 assert(cc == 0);
354}
355
356/*
357 * Unlock pthread mutex.
358 */
359INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
360{
361 int cc = pthread_mutex_unlock(pMutex);
362 assert(cc == 0);
363}
364
365/*
366 * Destroy a mutex.
367 */
368INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
369{
370 int cc = pthread_mutex_destroy(pMutex);
371 assert(cc == 0);
372}
373
374/*
375 * Create a thread as a result of java.lang.Thread.start().
376 */
377bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
378
379/*
380 * Create a thread internal to the VM. It's visible to interpreted code,
381 * but found in the "system" thread group rather than "main".
382 */
383bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
384 InternalThreadStart func, void* funcArg);
385
386/*
387 * Attach or detach the current thread from the VM.
388 */
389bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
390void dvmDetachCurrentThread(void);
391
392/*
393 * Get the "main" or "system" thread group.
394 */
395Object* dvmGetMainThreadGroup(void);
396Object* dvmGetSystemThreadGroup(void);
397
398/*
399 * Given a java/lang/VMThread object, return our Thread.
400 */
401Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
402
403/*
404 * Sleep in a thread. Returns when the sleep timer returns or the thread
405 * is interrupted.
406 */
407void dvmThreadSleep(u8 msec, u4 nsec);
408
409/*
410 * Get the name of a thread. (For safety, hold the thread list lock.)
411 */
412char* dvmGetThreadName(Thread* thread);
413
414/*
415 * Return true if a thread is on the internal list. If it is, the
416 * thread is part of the GC's root set.
417 */
418bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700419
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800420/*
421 * Get/set the JNIEnv field.
422 */
423INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
424INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
425
426/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800427 * Update the priority value of the underlying pthread.
428 */
429void dvmChangeThreadPriority(Thread* thread, int newPriority);
430
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800431/*
432 * Debug: dump information about a single thread.
433 */
434void dvmDumpThread(Thread* thread, bool isRunning);
435void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
436 bool isRunning);
437
438/*
439 * Debug: dump information about all threads.
440 */
441void dvmDumpAllThreads(bool grabLock);
442void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
443
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800444#ifdef WITH_MONITOR_TRACKING
445/*
446 * Track locks held by the current thread, along with the stack trace at
447 * the point the lock was acquired.
448 *
449 * At any given time the number of locks held across the VM should be
450 * fairly small, so there's no reason not to generate and store the entire
451 * stack trace.
452 */
453typedef struct LockedObjectData {
454 /* the locked object */
455 struct Object* obj;
456
457 /* number of times it has been locked recursively (zero-based ref count) */
458 int recursionCount;
459
460 /* stack trace at point of initial acquire */
461 u4 stackDepth;
462 int* rawStackTrace;
463
464 struct LockedObjectData* next;
465} LockedObjectData;
466
467/*
468 * Add/remove/find objects from the thread's monitor list.
469 */
470void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
471void dvmRemoveFromMonitorList(Thread* self, Object* obj);
472LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
473#endif
474
475#endif /*_DALVIK_THREAD*/