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