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