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_H_
21 #define DALVIK_THREAD_H_
22
23 #include "jni.h"
24 #include "interp/InterpState.h"
25
26 #include <errno.h>
27 #include <cutils/sched_policy.h>
28
29 #if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
30 /* glibc lacks this unless you #define __USE_UNIX98 */
31 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
32 enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
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 */
42 enum ThreadStatus {
43 THREAD_UNDEFINED = -1, /* makes enum compatible with int32_t */
44
45 /* these match up with JDWP values */
46 THREAD_ZOMBIE = 0, /* TERMINATED */
47 THREAD_RUNNING = 1, /* RUNNABLE or running now */
48 THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */
49 THREAD_MONITOR = 3, /* BLOCKED on a monitor */
50 THREAD_WAIT = 4, /* WAITING in Object.wait() */
51 /* non-JDWP states */
52 THREAD_INITIALIZING = 5, /* allocated, not yet running */
53 THREAD_STARTING = 6, /* started, not yet on thread list */
54 THREAD_NATIVE = 7, /* off in a JNI native method */
55 THREAD_VMWAIT = 8, /* waiting on a VM resource */
56 THREAD_SUSPENDED = 9, /* suspended, usually by GC or debugger */
57 };
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 void dvmThreadShutdown(void);
70 void dvmSlayDaemons(void);
71
72
73 #define kJniLocalRefMin 64
74 #define kJniLocalRefMax 512 /* arbitrary; should be plenty */
75 #define kInternalRefDefault 32 /* equally arbitrary */
76 #define kInternalRefMax 4096 /* mainly a sanity check */
77
78 #define kMinStackSize (512 + STACK_OVERFLOW_RESERVE)
79 #define kDefaultStackSize (16*1024) /* four 4K pages */
80 #define kMaxStackSize (256*1024 + STACK_OVERFLOW_RESERVE)
81
82 /*
83 * Interpreter control struction. Packed into a long long to enable
84 * atomic updates.
85 */
86 union InterpBreak {
87 volatile int64_t all;
88 struct {
89 uint16_t subMode;
90 uint8_t breakFlags;
91 int8_t unused; /* for future expansion */
92 #ifndef DVM_NO_ASM_INTERP
93 void* curHandlerTable;
94 #else
95 int32_t unused1;
96 #endif
97 } ctl;
98 };
99
100 /*
101 * Our per-thread data.
102 *
103 * These are allocated on the system heap.
104 */
105 struct Thread {
106 /*
107 * Interpreter state which must be preserved across nested
108 * interpreter invocations (via JNI callbacks). Must be the first
109 * element in Thread.
110 */
111 InterpSaveState interpSave;
112
113 /* small unique integer; useful for "thin" locks and debug messages */
114 u4 threadId;
115
116 /*
117 * Begin interpreter state which does not need to be preserved, but should
118 * be located towards the beginning of the Thread structure for
119 * efficiency.
120 */
121
122 /*
123 * interpBreak contains info about the interpreter mode, as well as
124 * a count of the number of times the thread has been suspended. When
125 * the count drops to zero, the thread resumes.
126 */
127 InterpBreak interpBreak;
128
129 /*
130 * "dbgSuspendCount" is the portion of the suspend count that the
131 * debugger is responsible for. This has to be tracked separately so
132 * that we can recover correctly if the debugger abruptly disconnects
133 * (suspendCount -= dbgSuspendCount). The debugger should not be able
134 * to resume GC-suspended threads, because we ignore the debugger while
135 * a GC is in progress.
136 *
137 * Both of these are guarded by gDvm.threadSuspendCountLock.
138 *
139 * Note the non-debug component will rarely be other than 1 or 0 -- (not
140 * sure it's even possible with the way mutexes are currently used.)
141 */
142
143 int suspendCount;
144 int dbgSuspendCount;
145
146 u1* cardTable;
147
148 /* current limit of stack; flexes for StackOverflowError */
149 const u1* interpStackEnd;
150
151 /* FP of bottom-most (currently executing) stack frame on interp stack */
152 void* XcurFrame;
153 /* current exception, or NULL if nothing pending */
154 Object* exception;
155
156 bool debugIsMethodEntry;
157 /* interpreter stack size; our stacks are fixed-length */
158 int interpStackSize;
159 bool stackOverflowed;
160
161 /* thread handle, as reported by pthread_self() */
162 pthread_t handle;
163
164 /* Assembly interpreter handler tables */
165 #ifndef DVM_NO_ASM_INTERP
166 void* mainHandlerTable; // Table of actual instruction handler
167 void* altHandlerTable; // Table of breakout handlers
168 #else
169 void* unused0; // Consume space to keep offsets
170 void* unused1; // the same between builds with
171 #endif
172
173 /*
174 * singleStepCount is a countdown timer used with the breakFlag
175 * kInterpSingleStep. If kInterpSingleStep is set in breakFlags,
176 * singleStepCount will decremented each instruction execution.
177 * Once it reaches zero, the kInterpSingleStep flag in breakFlags
178 * will be cleared. This can be used to temporarily prevent
179 * execution from re-entering JIT'd code or force inter-instruction
180 * checks by delaying the reset of curHandlerTable to mainHandlerTable.
181 */
182 int singleStepCount;
183
184 #ifdef WITH_JIT
185 struct JitToInterpEntries jitToInterpEntries;
186 /*
187 * Whether the current top VM frame is in the interpreter or JIT cache:
188 * NULL : in the interpreter
189 * non-NULL: entry address of the JIT'ed code (the actual value doesn't
190 * matter)
191 */
192 void* inJitCodeCache;
193 unsigned char* pJitProfTable;
194 int jitThreshold;
195 const void* jitResumeNPC; // Translation return point
196 const u4* jitResumeNSP; // Native SP at return point
197 const u2* jitResumeDPC; // Dalvik inst following single-step
198 JitState jitState;
199 int icRechainCount;
200 const void* pProfileCountdown;
201 const ClassObject* callsiteClass;
202 const Method* methodToCall;
203 #endif
204
205 /* JNI local reference tracking */
206 IndirectRefTable jniLocalRefTable;
207
208 #if defined(WITH_JIT)
209 #if defined(WITH_SELF_VERIFICATION)
210 /* Buffer for register state during self verification */
211 struct ShadowSpace* shadowSpace;
212 #endif
213 int currTraceRun;
214 int totalTraceLen; // Number of Dalvik insts in trace
215 const u2* currTraceHead; // Start of the trace we're building
216 const u2* currRunHead; // Start of run we're building
217 int currRunLen; // Length of run in 16-bit words
218 const u2* lastPC; // Stage the PC for the threaded interpreter
219 const Method* traceMethod; // Starting method of current trace
220 intptr_t threshFilter[JIT_TRACE_THRESH_FILTER_SIZE];
221 JitTraceRun trace[MAX_JIT_RUN_LEN];
222 #endif
223
224 /*
225 * Thread's current status. Can only be changed by the thread itself
226 * (i.e. don't mess with this from other threads).
227 */
228 volatile ThreadStatus status;
229
230 /* thread ID, only useful under Linux */
231 pid_t systemTid;
232
233 /* start (high addr) of interp stack (subtract size to get malloc addr) */
234 u1* interpStackStart;
235
236 /* the java/lang/Thread that we are associated with */
237 Object* threadObj;
238
239 /* the JNIEnv pointer associated with this thread */
240 JNIEnv* jniEnv;
241
242 /* internal reference tracking */
243 ReferenceTable internalLocalRefTable;
244
245
246 /* JNI native monitor reference tracking (initialized on first use) */
247 ReferenceTable jniMonitorRefTable;
248
249 /* hack to make JNI_OnLoad work right */
250 Object* classLoaderOverride;
251
252 /* mutex to guard the interrupted and the waitMonitor members */
253 pthread_mutex_t waitMutex;
254
255 /* pointer to the monitor lock we're currently waiting on */
256 /* guarded by waitMutex */
257 /* TODO: consider changing this to Object* for better JDWP interaction */
258 Monitor* waitMonitor;
259
260 /* thread "interrupted" status; stays raised until queried or thrown */
261 /* guarded by waitMutex */
262 bool interrupted;
263
264 /* links to the next thread in the wait set this thread is part of */
265 struct Thread* waitNext;
266
267 /* object to sleep on while we are waiting for a monitor */
268 pthread_cond_t waitCond;
269
270 /*
271 * Set to true when the thread is in the process of throwing an
272 * OutOfMemoryError.
273 */
274 bool throwingOOME;
275
276 /* links to rest of thread list; grab global lock before traversing */
277 struct Thread* prev;
278 struct Thread* next;
279
280 /* used by threadExitCheck when a thread exits without detaching */
281 int threadExitCheckCount;
282
283 /* JDWP invoke-during-breakpoint support */
284 DebugInvokeReq invokeReq;
285
286 /* base time for per-thread CPU timing (used by method profiling) */
287 bool cpuClockBaseSet;
288 u8 cpuClockBase;
289
290 /* previous stack trace sample and length (used by sampling profiler) */
291 const Method** stackTraceSample;
292 size_t stackTraceSampleLength;
293
294 /* memory allocation profiling state */
295 AllocProfState allocProf;
296
297 #ifdef WITH_JNI_STACK_CHECK
298 u4 stackCrc;
299 #endif
300
301 #if WITH_EXTRA_GC_CHECKS > 1
302 /* PC, saved on every instruction; redundant with StackSaveArea */
303 const u2* currentPc2;
304 #endif
305
306 /* Safepoint callback state */
307 pthread_mutex_t callbackMutex;
308 SafePointCallback callback;
309 void* callbackArg;
310
311 #if defined(ARCH_IA32) && defined(WITH_JIT)
312 u4 spillRegion[MAX_SPILL_JIT_IA];
313 #endif
314 };
315
316 /* start point for an internal thread; mimics pthread args */
317 typedef void* (*InternalThreadStart)(void* arg);
318
319 /* args for internal thread creation */
320 struct InternalStartArgs {
321 /* inputs */
322 InternalThreadStart func;
323 void* funcArg;
324 char* name;
325 Object* group;
326 bool isDaemon;
327 /* result */
328 volatile Thread** pThread;
329 volatile int* pCreateStatus;
330 };
331
332 /* finish init */
333 bool dvmPrepMainForJni(JNIEnv* pEnv);
334 bool dvmPrepMainThread(void);
335
336 /* utility function to get the tid */
337 pid_t dvmGetSysThreadId(void);
338
339 /*
340 * Get our Thread* from TLS.
341 *
342 * Returns NULL if this isn't a thread that the VM is aware of.
343 */
344 Thread* dvmThreadSelf(void);
345
346 /* grab the thread list global lock */
347 void dvmLockThreadList(Thread* self);
348 /* try to grab the thread list global lock */
349 bool dvmTryLockThreadList(void);
350 /* release the thread list global lock */
351 void dvmUnlockThreadList(void);
352
353 /*
354 * Thread suspend/resume, used by the GC and debugger.
355 */
356 enum SuspendCause {
357 SUSPEND_NOT = 0,
358 SUSPEND_FOR_GC,
359 SUSPEND_FOR_DEBUG,
360 SUSPEND_FOR_DEBUG_EVENT,
361 SUSPEND_FOR_STACK_DUMP,
362 SUSPEND_FOR_DEX_OPT,
363 SUSPEND_FOR_VERIFY,
364 SUSPEND_FOR_HPROF,
365 SUSPEND_FOR_SAMPLING,
366 #if defined(WITH_JIT)
367 SUSPEND_FOR_TBL_RESIZE, // jit-table resize
368 SUSPEND_FOR_IC_PATCH, // polymorphic callsite inline-cache patch
369 SUSPEND_FOR_CC_RESET, // code-cache reset
370 SUSPEND_FOR_REFRESH, // Reload data cached in interpState
371 #endif
372 };
373 void dvmSuspendThread(Thread* thread);
374 void dvmSuspendSelf(bool jdwpActivity);
375 void dvmResumeThread(Thread* thread);
376 void dvmSuspendAllThreads(SuspendCause why);
377 void dvmResumeAllThreads(SuspendCause why);
378 void dvmUndoDebuggerSuspensions(void);
379
380 /*
381 * Check suspend state. Grab threadListLock before calling.
382 */
383 bool dvmIsSuspended(const Thread* thread);
384
385 /*
386 * Wait until a thread has suspended. (Used by debugger support.)
387 */
388 void dvmWaitForSuspend(Thread* thread);
389
390 /*
391 * Check to see if we should be suspended now. If so, suspend ourselves
392 * by sleeping on a condition variable.
393 */
394 extern "C" bool dvmCheckSuspendPending(Thread* self);
395
396 /*
397 * Fast test for use in the interpreter. Returns "true" if our suspend
398 * count is nonzero.
399 */
dvmCheckSuspendQuick(Thread * self)400 INLINE bool dvmCheckSuspendQuick(Thread* self) {
401 return (self->interpBreak.ctl.subMode & kSubModeSuspendPending);
402 }
403
404 /*
405 * Used when changing thread state. Threads may only change their own.
406 * The "self" argument, which may be NULL, is accepted as an optimization.
407 *
408 * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
409 * or THREAD_MONITOR), do so in the same function as the wait -- this records
410 * the current stack depth for the GC.
411 *
412 * If you're changing to THREAD_RUNNING, this will check for suspension.
413 *
414 * Returns the old status.
415 */
416 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
417
418 /*
419 * Initialize a mutex.
420 */
dvmInitMutex(pthread_mutex_t * pMutex)421 INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
422 {
423 #ifdef CHECK_MUTEX
424 pthread_mutexattr_t attr;
425 int cc;
426
427 pthread_mutexattr_init(&attr);
428 cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
429 assert(cc == 0);
430 pthread_mutex_init(pMutex, &attr);
431 pthread_mutexattr_destroy(&attr);
432 #else
433 pthread_mutex_init(pMutex, NULL); // default=PTHREAD_MUTEX_FAST_NP
434 #endif
435 }
436
437 /*
438 * Grab a plain mutex.
439 */
dvmLockMutex(pthread_mutex_t * pMutex)440 INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
441 {
442 int cc __attribute__ ((__unused__)) = pthread_mutex_lock(pMutex);
443 assert(cc == 0);
444 }
445
446 /*
447 * Try grabbing a plain mutex. Returns 0 if successful.
448 */
dvmTryLockMutex(pthread_mutex_t * pMutex)449 INLINE int dvmTryLockMutex(pthread_mutex_t* pMutex)
450 {
451 int cc = pthread_mutex_trylock(pMutex);
452 assert(cc == 0 || cc == EBUSY);
453 return cc;
454 }
455
456 /*
457 * Unlock pthread mutex.
458 */
dvmUnlockMutex(pthread_mutex_t * pMutex)459 INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
460 {
461 int cc __attribute__ ((__unused__)) = pthread_mutex_unlock(pMutex);
462 assert(cc == 0);
463 }
464
465 /*
466 * Destroy a mutex.
467 */
dvmDestroyMutex(pthread_mutex_t * pMutex)468 INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
469 {
470 int cc __attribute__ ((__unused__)) = pthread_mutex_destroy(pMutex);
471 assert(cc == 0);
472 }
473
dvmBroadcastCond(pthread_cond_t * pCond)474 INLINE void dvmBroadcastCond(pthread_cond_t* pCond)
475 {
476 int cc __attribute__ ((__unused__)) = pthread_cond_broadcast(pCond);
477 assert(cc == 0);
478 }
479
dvmSignalCond(pthread_cond_t * pCond)480 INLINE void dvmSignalCond(pthread_cond_t* pCond)
481 {
482 int cc __attribute__ ((__unused__)) = pthread_cond_signal(pCond);
483 assert(cc == 0);
484 }
485
dvmWaitCond(pthread_cond_t * pCond,pthread_mutex_t * pMutex)486 INLINE void dvmWaitCond(pthread_cond_t* pCond, pthread_mutex_t* pMutex)
487 {
488 int cc __attribute__ ((__unused__)) = pthread_cond_wait(pCond, pMutex);
489 assert(cc == 0);
490 }
491
492 /*
493 * Create a thread as a result of java.lang.Thread.start().
494 */
495 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
496
497 /*
498 * Create a thread internal to the VM. It's visible to interpreted code,
499 * but found in the "system" thread group rather than "main".
500 */
501 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
502 InternalThreadStart func, void* funcArg);
503
504 /*
505 * Attach or detach the current thread from the VM.
506 */
507 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
508 void dvmDetachCurrentThread(void);
509
510 /*
511 * Get the "main" or "system" thread group.
512 */
513 Object* dvmGetMainThreadGroup(void);
514 Object* dvmGetSystemThreadGroup(void);
515
516 /*
517 * Given a java/lang/VMThread object, return our Thread.
518 */
519 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
520
521 /*
522 * Given a pthread handle, return the associated Thread*.
523 * Caller must hold the thread list lock.
524 *
525 * Returns NULL if the thread was not found.
526 */
527 Thread* dvmGetThreadByHandle(pthread_t handle);
528
529 /*
530 * Given a thread ID, return the associated Thread*.
531 * Caller must hold the thread list lock.
532 *
533 * Returns NULL if the thread was not found.
534 */
535 Thread* dvmGetThreadByThreadId(u4 threadId);
536
537 /*
538 * Sleep in a thread. Returns when the sleep timer returns or the thread
539 * is interrupted.
540 */
541 void dvmThreadSleep(u8 msec, u4 nsec);
542
543 /*
544 * Get the name of a thread.
545 *
546 * For correctness, the caller should hold the thread list lock to ensure
547 * that the thread doesn't go away mid-call.
548 */
549 std::string dvmGetThreadName(Thread* thread);
550
551 /*
552 * Convert ThreadStatus to a string.
553 */
554 const char* dvmGetThreadStatusStr(ThreadStatus status);
555
556 /*
557 * Return true if a thread is on the internal list. If it is, the
558 * thread is part of the GC's root set.
559 */
560 bool dvmIsOnThreadList(const Thread* thread);
561
562 /*
563 * Get/set the JNIEnv field.
564 */
dvmGetThreadJNIEnv(Thread * self)565 INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
dvmSetThreadJNIEnv(Thread * self,JNIEnv * env)566 INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
567
568 /*
569 * Update the priority value of the underlying pthread.
570 */
571 void dvmChangeThreadPriority(Thread* thread, int newPriority);
572
573 /* "change flags" values for raise/reset thread priority calls */
574 #define kChangedPriority 0x01
575 #define kChangedPolicy 0x02
576
577 /*
578 * If necessary, raise the thread's priority to nice=0 cgroup=fg.
579 *
580 * Returns bit flags indicating changes made (zero if nothing was done).
581 */
582 int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
583 SchedPolicy* pSavedThreadPolicy);
584
585 /*
586 * Drop the thread priority to what it was before an earlier call to
587 * dvmRaiseThreadPriorityIfNeeded().
588 */
589 void dvmResetThreadPriority(Thread* thread, int changeFlags,
590 int savedThreadPrio, SchedPolicy savedThreadPolicy);
591
592 /*
593 * Debug: dump information about a single thread.
594 */
595 void dvmDumpThread(Thread* thread, bool isRunning);
596 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
597 bool isRunning);
598
599 /*
600 * Debug: dump information about all threads.
601 */
602 void dvmDumpAllThreads(bool grabLock);
603 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
604
605 /*
606 * Debug: kill a thread to get a debuggerd stack trace. Leaves the VM
607 * in an uncertain state.
608 */
609 void dvmNukeThread(Thread* thread);
610
611 #endif // DALVIK_THREAD_H_
612