blob: d834f7b0b17105bcb3dc678e6aae924535b901b1 [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)
Ben Chenga8e64a72009-10-20 13:01:36 -0700278 SUSPEND_FOR_TBL_RESIZE,
279 SUSPEND_FOR_IC_PATCH,
Bill Buzbee27176222009-06-09 09:20:16 -0700280#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800281} SuspendCause;
282void dvmSuspendThread(Thread* thread);
283void dvmSuspendSelf(bool jdwpActivity);
284void dvmResumeThread(Thread* thread);
285void dvmSuspendAllThreads(SuspendCause why);
286void dvmResumeAllThreads(SuspendCause why);
287void dvmUndoDebuggerSuspensions(void);
288
289/*
290 * Check suspend state. Grab threadListLock before calling.
291 */
292bool dvmIsSuspended(Thread* thread);
293
294/*
295 * Wait until a thread has suspended. (Used by debugger support.)
296 */
297void dvmWaitForSuspend(Thread* thread);
298
299/*
300 * Check to see if we should be suspended now. If so, suspend ourselves
301 * by sleeping on a condition variable.
302 *
303 * If "self" is NULL, this will use dvmThreadSelf().
304 */
305bool dvmCheckSuspendPending(Thread* self);
306
307/*
The Android Open Source Project99409882009-03-18 22:20:24 -0700308 * Fast test for use in the interpreter. Returns "true" if our suspend
309 * count is nonzero.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800310 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700311INLINE bool dvmCheckSuspendQuick(Thread* self) {
312 return (self->suspendCount != 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800313}
314
315/*
316 * Used when changing thread state. Threads may only change their own.
317 * The "self" argument, which may be NULL, is accepted as an optimization.
318 *
319 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
320 * or THREAD_MONITOR), do so in the same function as the wait -- this records
321 * the current stack depth for the GC.
322 *
323 * If you're changing to THREAD_RUNNING, this will check for suspension.
324 *
325 * Returns the old status.
326 */
327ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
328
329/*
330 * Initialize a mutex.
331 */
332INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
333{
334#ifdef CHECK_MUTEX
335 pthread_mutexattr_t attr;
336 int cc;
337
338 pthread_mutexattr_init(&attr);
339 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
340 assert(cc == 0);
341 pthread_mutex_init(pMutex, &attr);
342 pthread_mutexattr_destroy(&attr);
343#else
344 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
345#endif
346}
347
348/*
349 * Grab a plain mutex.
350 */
351INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
352{
353 int cc = pthread_mutex_lock(pMutex);
354 assert(cc == 0);
355}
356
357/*
358 * Unlock pthread mutex.
359 */
360INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
361{
362 int cc = pthread_mutex_unlock(pMutex);
363 assert(cc == 0);
364}
365
366/*
367 * Destroy a mutex.
368 */
369INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
370{
371 int cc = pthread_mutex_destroy(pMutex);
372 assert(cc == 0);
373}
374
375/*
376 * Create a thread as a result of java.lang.Thread.start().
377 */
378bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
379
380/*
381 * Create a thread internal to the VM. It's visible to interpreted code,
382 * but found in the "system" thread group rather than "main".
383 */
384bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
385 InternalThreadStart func, void* funcArg);
386
387/*
388 * Attach or detach the current thread from the VM.
389 */
390bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
391void dvmDetachCurrentThread(void);
392
393/*
394 * Get the "main" or "system" thread group.
395 */
396Object* dvmGetMainThreadGroup(void);
397Object* dvmGetSystemThreadGroup(void);
398
399/*
400 * Given a java/lang/VMThread object, return our Thread.
401 */
402Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
403
404/*
405 * Sleep in a thread. Returns when the sleep timer returns or the thread
406 * is interrupted.
407 */
408void dvmThreadSleep(u8 msec, u4 nsec);
409
410/*
411 * Get the name of a thread. (For safety, hold the thread list lock.)
412 */
413char* dvmGetThreadName(Thread* thread);
414
415/*
416 * Return true if a thread is on the internal list. If it is, the
417 * thread is part of the GC's root set.
418 */
419bool dvmIsOnThreadList(const Thread* thread);
Jeff Hao97319a82009-08-12 16:57:15 -0700420
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800421/*
422 * Get/set the JNIEnv field.
423 */
424INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
425INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
426
427/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800428 * Update the priority value of the underlying pthread.
429 */
430void dvmChangeThreadPriority(Thread* thread, int newPriority);
431
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800432/*
433 * Debug: dump information about a single thread.
434 */
435void dvmDumpThread(Thread* thread, bool isRunning);
436void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
437 bool isRunning);
438
439/*
440 * Debug: dump information about all threads.
441 */
442void dvmDumpAllThreads(bool grabLock);
443void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
444
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800445#ifdef WITH_MONITOR_TRACKING
446/*
447 * Track locks held by the current thread, along with the stack trace at
448 * the point the lock was acquired.
449 *
450 * At any given time the number of locks held across the VM should be
451 * fairly small, so there's no reason not to generate and store the entire
452 * stack trace.
453 */
454typedef struct LockedObjectData {
455 /* the locked object */
456 struct Object* obj;
457
458 /* number of times it has been locked recursively (zero-based ref count) */
459 int recursionCount;
460
461 /* stack trace at point of initial acquire */
462 u4 stackDepth;
463 int* rawStackTrace;
464
465 struct LockedObjectData* next;
466} LockedObjectData;
467
468/*
469 * Add/remove/find objects from the thread's monitor list.
470 */
471void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
472void dvmRemoveFromMonitorList(Thread* self, Object* obj);
473LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
474#endif
475
476#endif /*_DALVIK_THREAD*/