2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Variables with library scope.
20 * Prefer this over scattered static and global variables -- it's easier to
21 * view the state in a debugger, it makes clean shutdown simpler, we can
22 * trivially dump the state into a crash log, and it dodges most naming
23 * collisions that will arise when we are embedded in a larger program.
25 * If we want multiple VMs per process, this can get stuffed into TLS (or
26 * accessed through a Thread field). May need to pass it around for some
27 * of the early initialization functions.
29 #ifndef _DALVIK_GLOBALS
30 #define _DALVIK_GLOBALS
35 #define MAX_BREAKPOINTS 20 /* used for a debugger optimization */
37 /* private structures */
38 typedef struct GcHeap GcHeap;
39 typedef struct BreakpointSet BreakpointSet;
40 typedef struct InlineSub InlineSub;
43 * One of these for each -ea/-da/-esa/-dsa on the command line.
45 typedef struct AssertionControl {
46 char* pkgOrClass; /* package/class string, or NULL for esa/dsa */
47 int pkgOrClassLen; /* string length, for quick compare */
48 bool enable; /* enable or disable */
49 bool isPackage; /* string ended with "..."? */
53 * Execution mode, e.g. interpreter vs. JIT.
55 typedef enum ExecutionMode {
56 kExecutionModeUnknown = 0,
57 kExecutionModeInterpPortable,
58 kExecutionModeInterpFast,
65 * All fields are initialized to zero.
67 * Storage allocated here must be freed by a subsystem shutdown function or
68 * from within freeGlobals().
72 * Some options from the command line or environment.
74 char* bootClassPathStr;
77 unsigned int heapSizeStart;
78 unsigned int heapSizeMax;
79 unsigned int stackSize;
86 bool jdwpAllowed; // debugging allowed for this process?
87 bool jdwpConfigured; // has debugging info been provided?
95 * Lock profiling threshold value in milliseconds. Acquires that
96 * exceed threshold are logged. Acquires within the threshold are
97 * logged with a probability of $\frac{time}{threshold}$ . If the
98 * threshold is unset no additional logging occurs.
100 u4 lockProfThreshold;
102 int (*vfprintfHook)(FILE*, const char*, va_list);
103 void (*exitHook)(int);
104 void (*abortHook)(void);
106 int jniGrefLimit; // 0 means no limit
109 bool verifyDexChecksum;
110 char* stackTraceFile; // for SIGQUIT-inspired output
114 DexOptimizerMode dexOptMode;
115 DexClassVerifyMode classVerifyMode;
124 bool generateRegisterMaps;
125 bool concurrentMarkSweep;
127 int assertionCtrlCount;
128 AssertionControl* assertionCtrl;
130 ExecutionMode executionMode;
133 * VM init management.
136 int initExceptionCount;
140 * java.lang.System properties set from the command line.
147 * Where the VM goes to find system classes.
149 ClassPathEntry* bootClassPath;
150 /* used by the DEX optimizer to load classes from an unfinished DEX */
151 DvmDex* bootClassPathOptExtra;
152 bool optimizingBootstrapClass;
155 * Loaded classes, hashed by class name. Each entry is a ClassObject*,
156 * allocated in GC space.
158 HashTable* loadedClasses;
161 * Value for the next class serial number to be assigned. This is
162 * incremented as we load classes. Failed loads and races may result
163 * in some numbers being skipped, and the serial number is not
164 * guaranteed to start at 1, so the current value should not be used
165 * as a count of loaded classes.
167 volatile int classSerialNumber;
170 * Classes with a low classSerialNumber are probably in the zygote, and
171 * their InitiatingLoaderList is not used, to promote sharing. The list is
174 InitiatingLoaderList* initiatingLoaderList;
179 HashTable* internedStrings;
182 * Quick lookups for popular classes used internally.
184 ClassObject* classJavaLangClass;
185 ClassObject* classJavaLangClassArray;
186 ClassObject* classJavaLangError;
187 ClassObject* classJavaLangObject;
188 ClassObject* classJavaLangObjectArray;
189 ClassObject* classJavaLangRuntimeException;
190 ClassObject* classJavaLangString;
191 ClassObject* classJavaLangThread;
192 ClassObject* classJavaLangVMThread;
193 ClassObject* classJavaLangThreadGroup;
194 ClassObject* classJavaLangThrowable;
195 ClassObject* classJavaLangStackOverflowError;
196 ClassObject* classJavaLangStackTraceElement;
197 ClassObject* classJavaLangStackTraceElementArray;
198 ClassObject* classJavaLangAnnotationAnnotationArray;
199 ClassObject* classJavaLangAnnotationAnnotationArrayArray;
200 ClassObject* classJavaLangReflectAccessibleObject;
201 ClassObject* classJavaLangReflectConstructor;
202 ClassObject* classJavaLangReflectConstructorArray;
203 ClassObject* classJavaLangReflectField;
204 ClassObject* classJavaLangReflectFieldArray;
205 ClassObject* classJavaLangReflectMethod;
206 ClassObject* classJavaLangReflectMethodArray;
207 ClassObject* classJavaLangReflectProxy;
208 ClassObject* classJavaLangExceptionInInitializerError;
209 ClassObject* classJavaLangRefPhantomReference;
210 ClassObject* classJavaLangRefReference;
211 ClassObject* classJavaNioReadWriteDirectByteBuffer;
212 ClassObject* classJavaSecurityAccessController;
213 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
214 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
215 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
216 ClassObject* classOrgApacheHarmonyNioInternalDirectBuffer;
217 jclass jclassOrgApacheHarmonyNioInternalDirectBuffer;
219 /* synthetic classes for arrays of primitives */
220 ClassObject* classArrayBoolean;
221 ClassObject* classArrayChar;
222 ClassObject* classArrayFloat;
223 ClassObject* classArrayDouble;
224 ClassObject* classArrayByte;
225 ClassObject* classArrayShort;
226 ClassObject* classArrayInt;
227 ClassObject* classArrayLong;
229 /* method offsets - Object */
230 int voffJavaLangObject_equals;
231 int voffJavaLangObject_hashCode;
232 int voffJavaLangObject_toString;
233 int voffJavaLangObject_finalize;
235 /* field offsets - Class */
236 int offJavaLangClass_pd;
238 /* field offsets - String */
239 int javaLangStringReady; /* 0=not init, 1=ready, -1=initing */
240 int offJavaLangString_value;
241 int offJavaLangString_count;
242 int offJavaLangString_offset;
243 int offJavaLangString_hashCode;
245 /* field offsets - Thread */
246 int offJavaLangThread_vmThread;
247 int offJavaLangThread_group;
248 int offJavaLangThread_daemon;
249 int offJavaLangThread_name;
250 int offJavaLangThread_priority;
252 /* method offsets - Thread */
253 int voffJavaLangThread_run;
255 /* field offsets - VMThread */
256 int offJavaLangVMThread_thread;
257 int offJavaLangVMThread_vmData;
259 /* method offsets - ThreadGroup */
260 int voffJavaLangThreadGroup_removeThread;
262 /* field offsets - Throwable */
263 int offJavaLangThrowable_stackState;
264 int offJavaLangThrowable_message;
265 int offJavaLangThrowable_cause;
267 /* field offsets - java.lang.reflect.* */
268 int offJavaLangReflectAccessibleObject_flag;
269 int offJavaLangReflectConstructor_slot;
270 int offJavaLangReflectConstructor_declClass;
271 int offJavaLangReflectField_slot;
272 int offJavaLangReflectField_declClass;
273 int offJavaLangReflectMethod_slot;
274 int offJavaLangReflectMethod_declClass;
276 /* field offsets - java.lang.ref.Reference */
277 int offJavaLangRefReference_referent;
278 int offJavaLangRefReference_queue;
279 int offJavaLangRefReference_queueNext;
281 /* method pointers - java.lang.ref.Reference */
282 Method* methJavaLangRefReference_enqueueInternal;
284 /* field offsets - java.nio.Buffer and java.nio.DirectByteBufferImpl */
285 //int offJavaNioBuffer_capacity;
286 //int offJavaNioDirectByteBufferImpl_pointer;
288 /* method pointers - java.security.AccessController */
289 volatile bool javaSecurityAccessControllerReady;
290 Method* methJavaSecurityAccessController_doPrivileged[4];
292 /* constructor method pointers; no vtable involved, so use Method* */
293 Method* methJavaLangStackTraceElement_init;
294 Method* methJavaLangExceptionInInitializerError_init;
295 Method* methJavaLangRefPhantomReference_init;
296 Method* methJavaLangReflectConstructor_init;
297 Method* methJavaLangReflectField_init;
298 Method* methJavaLangReflectMethod_init;
299 Method* methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
301 /* static method pointers - android.lang.annotation.* */
303 methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
305 /* direct method pointers - java.lang.reflect.Proxy */
306 Method* methJavaLangReflectProxy_constructorPrototype;
308 /* field offsets - java.lang.reflect.Proxy */
309 int offJavaLangReflectProxy_h;
311 /* fake native entry point method */
312 Method* methFakeNativeEntry;
314 /* assorted direct buffer helpers */
315 Method* methJavaNioReadWriteDirectByteBuffer_init;
316 Method* methOrgApacheHarmonyLuniPlatformPlatformAddress_on;
317 Method* methOrgApacheHarmonyNioInternalDirectBuffer_getEffectiveAddress;
318 int offJavaNioBuffer_capacity;
319 int offJavaNioBuffer_effectiveDirectAddress;
320 int offOrgApacheHarmonyLuniPlatformPlatformAddress_osaddr;
321 int voffOrgApacheHarmonyLuniPlatformPlatformAddress_toLong;
324 * VM-synthesized primitive classes, for arrays.
326 ClassObject* volatile primitiveClass[PRIM_MAX];
329 * Thread list. This always has at least one element in it (main),
330 * and main is always the first entry.
332 * The threadListLock is used for several things, including the thread
333 * start condition variable. Generally speaking, you must hold the
334 * threadListLock when:
335 * - adding/removing items from the list
336 * - waiting on or signaling threadStartCond
337 * - examining the Thread struct for another thread (this is to avoid
338 * one thread freeing the Thread struct while another thread is
342 pthread_mutex_t threadListLock;
344 pthread_cond_t threadStartCond;
347 * The thread code grabs this before suspending all threads. There
348 * are a few things that can cause a "suspend all":
349 * (1) the GC is starting;
350 * (2) the debugger has sent a "suspend all" request;
351 * (3) a thread has hit a breakpoint or exception that the debugger
352 * has marked as a "suspend all" event;
353 * (4) the SignalCatcher caught a signal that requires suspension.
354 * (5) (if implemented) the JIT needs to perform a heavyweight
355 * rearrangement of the translation cache or JitTable.
357 * Because we use "safe point" self-suspension, it is never safe to
358 * do a blocking "lock" call on this mutex -- if it has been acquired,
359 * somebody is probably trying to put you to sleep. The leading '_' is
360 * intended as a reminder that this lock is special.
362 pthread_mutex_t _threadSuspendLock;
365 * Guards Thread->suspendCount for all threads, and provides the lock
366 * for the condition variable that all suspended threads sleep on
367 * (threadSuspendCountCond).
369 * This has to be separate from threadListLock because of the way
370 * threads put themselves to sleep.
372 pthread_mutex_t threadSuspendCountLock;
375 * Suspended threads sleep on this. They should sleep on the condition
376 * variable until their "suspend count" is zero.
378 * Paired with "threadSuspendCountLock".
380 pthread_cond_t threadSuspendCountCond;
383 * Sum of all threads' suspendCount fields. The JIT needs to know if any
384 * thread is suspended. Guarded by threadSuspendCountLock.
386 int sumThreadSuspendCount;
389 * MUTEX ORDERING: when locking multiple mutexes, always grab them in
390 * this order to avoid deadlock:
392 * (1) _threadSuspendLock (use lockThreadSuspend())
393 * (2) threadListLock (use dvmLockThreadList())
394 * (3) threadSuspendCountLock (use lockThreadSuspendCount())
399 * Thread ID bitmap. We want threads to have small integer IDs so
400 * we can use them in "thin locks".
402 BitVector* threadIdMap;
405 * Manage exit conditions. The VM exits when all non-daemon threads
406 * have exited. If the main thread returns early, we need to sleep
407 * on a condition variable.
409 int nonDaemonThreadCount; /* must hold threadListLock to access */
410 //pthread_mutex_t vmExitLock;
411 pthread_cond_t vmExitCond;
414 * The set of DEX files loaded by custom class loaders.
416 HashTable* userDexFiles;
419 * JNI global reference table.
421 #ifdef USE_INDIRECT_REF
422 IndirectRefTable jniGlobalRefTable;
424 ReferenceTable jniGlobalRefTable;
426 pthread_mutex_t jniGlobalRefLock;
427 int jniGlobalRefHiMark;
428 int jniGlobalRefLoMark;
431 * JNI pinned object table (used for primitive arrays).
433 ReferenceTable jniPinRefTable;
434 pthread_mutex_t jniPinRefLock;
437 * Native shared library table.
439 HashTable* nativeLibs;
442 * GC heap lock. Functions like gcMalloc() acquire this before making
443 * any changes to the heap. It is held throughout garbage collection.
445 pthread_mutex_t gcHeapLock;
448 * Condition variable to queue threads waiting to retry an
449 * allocation. Signaled after a concurrent GC is completed.
451 pthread_cond_t gcHeapCond;
453 /* Opaque pointer representing the heap. */
457 * Pre-allocated throwables.
459 Object* outOfMemoryObj;
460 Object* internalErrorObj;
461 Object* noClassDefFoundErrorObj;
463 /* Monitor list, so we can free them */
464 /*volatile*/ Monitor* monitorList;
466 /* Monitor for Thread.sleep() implementation */
467 Monitor* threadSleepMon;
469 /* set when we create a second heap inside the zygote */
470 bool newZygoteHeapAllocated;
475 pthread_key_t pthreadKeySelf; /* Thread*, for dvmThreadSelf */
478 * JNI allows you to have multiple VMs, but we limit ourselves to 1,
479 * so "vmList" is really just a pointer to the one and only VM.
484 * Cache results of "A instanceof B".
486 AtomicCache* instanceofCache;
488 /* instruction width table, used for optimization and verification */
489 InstructionWidth* instrWidth;
490 /* instruction flags table, used for verification */
491 InstructionFlags* instrFlags;
492 /* instruction format table, used for verification */
493 InstructionFormat* instrFormat;
495 /* inline substitution table, used during optimization */
496 InlineSub* inlineSubs;
499 * Bootstrap class loader linear allocator.
501 LinearAllocHdr* pBootLoaderAlloc;
505 * Heap worker thread.
507 bool heapWorkerInitialized;
508 bool heapWorkerReady;
510 pthread_t heapWorkerHandle;
511 pthread_mutex_t heapWorkerLock;
512 pthread_cond_t heapWorkerCond;
513 pthread_cond_t heapWorkerIdleCond;
514 pthread_mutex_t heapWorkerListLock;
517 * Compute some stats on loaded classes.
519 int numLoadedClasses;
520 int numDeclaredMethods;
521 int numDeclaredInstFields;
522 int numDeclaredStaticFields;
524 /* when using a native debugger, set this to suppress watchdog timers */
525 bool nativeDebuggerActive;
528 * JDWP debugger support.
530 * Note "debuggerActive" is accessed from mterp, so its storage size and
531 * meaning must not be changed without updating the assembly sources.
533 bool debuggerConnected; /* debugger or DDMS is connected */
534 u1 debuggerActive; /* debugger is making requests */
535 JdwpState* jdwpState;
538 * Registry of objects known to the debugger.
540 HashTable* dbgRegistry;
543 * Debugger breakpoint table.
545 BreakpointSet* breakpointSet;
548 * Single-step control struct. We currently only allow one thread to
549 * be single-stepping at a time, which is all that really makes sense,
550 * but it's possible we may need to expand this to be per-thread.
552 StepControl stepControl;
555 * DDM features embedded in the VM.
557 bool ddmThreadNotification;
560 * Zygote (partially-started process) support
565 * Used for tracking allocations that we report to DDMS. When the feature
566 * is enabled (through a DDMS request) the "allocRecords" pointer becomes
569 pthread_mutex_t allocTrackerLock;
570 AllocRecord* allocRecords;
571 int allocRecordHead; /* most-recently-added entry */
572 int allocRecordCount; /* #of valid entries */
574 #ifdef WITH_ALLOC_LIMITS
575 /* set on first use of an alloc limit, never cleared */
576 bool checkAllocLimits;
577 /* allocation limit, for setGlobalAllocationLimit() regression testing */
581 #ifdef WITH_DEADLOCK_PREDICTION
582 /* global lock on history tree accesses */
583 pthread_mutex_t deadlockHistoryLock;
585 enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
590 * When a profiler is enabled, this is incremented. Distinct profilers
591 * include "dmtrace" method tracing, emulator method tracing, and
592 * possibly instruction counting.
594 * The purpose of this is to have a single value that the interpreter
595 * can check to see if any profiling activity is enabled.
597 volatile int activeProfilers;
600 * State for method-trace profiling.
602 MethodTraceState methodTrace;
605 * State for emulator tracing.
607 void* emulatorTracePage;
608 int emulatorTraceEnableCount;
611 * Global state for memory allocation profiling.
613 AllocProfState allocProf;
616 * Pointers to the original methods for things that have been inlined.
617 * This makes it easy for us to output method entry/exit records for
618 * the method calls we're not actually making.
620 Method** inlinedMethods;
623 * Dalvik instruction counts (256 entries).
625 int* executedInstrCounts;
626 bool instructionCountEnableCount;
630 * Signal catcher thread (for SIGQUIT).
632 pthread_t signalCatcherHandle;
633 bool haltSignalCatcher;
636 * Stdout/stderr conversion thread.
638 bool haltStdioConverter;
639 bool stdioConverterReady;
640 pthread_t stdioConverterHandle;
641 pthread_mutex_t stdioConverterLock;
642 pthread_cond_t stdioConverterCond;
645 * pid of the system_server process. We track it so that when system server
646 * crashes the Zygote process will be killed and restarted.
648 pid_t systemServerPid;
650 int kernelGroupScheduling;
652 //#define COUNT_PRECISE_METHODS
653 #ifdef COUNT_PRECISE_METHODS
654 PointerSet* preciseMethods;
657 /* some RegisterMap statistics, useful during development */
658 void* registerMapStats;
661 extern struct DvmGlobals gDvm;
663 #if defined(WITH_JIT)
666 * Exiting the compiled code w/o chaining will incur overhead to look up the
667 * target in the code cache which is extra work only when JIT is enabled. So
668 * we want to monitor it closely to make sure we don't have performance bugs.
670 typedef enum NoChainExits {
671 kInlineCacheMiss = 0,
672 kCallsiteInterpreted,
679 * JIT-specific global state
681 struct DvmJitGlobals {
683 * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
684 * chain fields within the JIT hash table. Note carefully the access
686 * Only writes are guarded, and the guarded fields must be updated in a
687 * specific order using atomic operations. Further, once a field is
688 * written it cannot be changed without halting all threads.
690 * The write order is:
693 * 3) chain [if necessary]
695 * This mutex also guards both read and write of curJitTableEntries.
697 pthread_mutex_t tableLock;
699 /* The JIT hash table. Note that for access speed, copies of this pointer
700 * are stored in each thread. */
701 struct JitEntry *pJitEntryTable;
703 /* Array of profile threshold counters */
704 unsigned char *pProfTable;
706 /* Copy of pProfTable used for temporarily disabling the Jit */
707 unsigned char *pProfTableCopy;
709 /* Size of JIT hash table in entries. Must be a power of 2 */
710 unsigned int jitTableSize;
712 /* Mask used in hash function for JitTable. Should be jitTableSize-1 */
713 unsigned int jitTableMask;
715 /* How many entries in the JitEntryTable are in use */
716 unsigned int jitTableEntriesUsed;
718 /* Bytes allocated for the code cache */
719 unsigned int codeCacheSize;
721 /* Trigger for trace selection */
722 unsigned short threshold;
724 /* JIT Compiler Control */
725 bool haltCompilerThread;
727 pthread_t compilerHandle;
728 pthread_mutex_t compilerLock;
729 pthread_mutex_t compilerICPatchLock;
730 pthread_cond_t compilerQueueActivity;
731 pthread_cond_t compilerQueueEmpty;
732 volatile int compilerQueueLength;
733 int compilerHighWater;
734 int compilerWorkEnqueueIndex;
735 int compilerWorkDequeueIndex;
736 int compilerICPatchIndex;
738 /* JIT internal stats */
739 int compilerMaxQueued;
740 int translationChains;
742 /* Compiled code cache */
745 /* Bytes used by the code templates */
746 unsigned int templateSize;
748 /* Bytes already used in the code cache */
749 unsigned int codeCacheByteUsed;
751 /* Number of installed compilations in the cache */
752 unsigned int numCompilations;
754 /* Flag to indicate that the code cache is full */
758 unsigned int pageSizeMask;
760 /* Lock to change the protection type of the code cache */
761 pthread_mutex_t codeCacheProtectionLock;
763 /* Number of times that the code cache has been reset */
764 int numCodeCacheReset;
766 /* Number of times that the code cache reset request has been delayed */
767 int numCodeCacheResetDelayed;
769 /* true/false: compile/reject opcodes specified in the -Xjitop list */
770 bool includeSelectedOp;
772 /* true/false: compile/reject methods specified in the -Xjitmethod list */
773 bool includeSelectedMethod;
775 /* Disable JIT for selected opcodes - one bit for each opcode */
778 /* Disable JIT for selected methods */
779 HashTable *methodTable;
781 /* Flag to dump all compiled code */
784 /* Flag to count trace execution */
787 /* Vector to disable selected optimizations */
790 /* Table to track the overall and trace statistics of hot methods */
791 HashTable* methodStatsTable;
793 /* Filter method compilation blacklist with call-graph information */
796 /* New translation chain has been set up */
797 volatile bool hasNewChain;
799 #if defined(WITH_SELF_VERIFICATION)
800 /* Spin when error is detected, volatile so GDB can reset it */
801 volatile bool selfVerificationSpin;
804 /* Framework or stand-alone? */
805 bool runningInAndroidFramework;
807 /* Framework callback happened? */
808 bool alreadyEnabledViaFramework;
810 /* Framework requests to disable the JIT for good */
813 #if defined(SIGNATURE_BREAKPOINT)
814 /* Signature breakpoint */
815 u4 signatureBreakpointSize; // # of words
816 u4 *signatureBreakpoint; // Signature content
819 #if defined(WITH_JIT_TUNING)
820 /* Performance tuning counters */
821 int addrLookupsFound;
822 int addrLookupsNotFound;
823 int noChainExit[kNoChainExitLast];
826 int invokeMonomorphic;
827 int invokePolymorphic;
836 int codeCachePatches;
839 /* Place arrays at the end to ease the display in gdb sessions */
841 /* Work order queue for compilations */
842 CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
844 /* Work order queue for predicted chain patching */
845 ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
848 extern struct DvmJitGlobals gDvmJit;
850 #if defined(WITH_JIT_TUNING)
851 extern int gDvmICHitCount;
856 #endif /*_DALVIK_GLOBALS*/