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