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
110 bool verifyDexChecksum;
111 char* stackTraceFile; // for SIGQUIT-inspired output
115 DexOptimizerMode dexOptMode;
116 DexClassVerifyMode classVerifyMode;
125 bool generateRegisterMaps;
126 bool concurrentMarkSweep;
127 bool verifyCardTable;
129 int assertionCtrlCount;
130 AssertionControl* assertionCtrl;
132 ExecutionMode executionMode;
135 * VM init management.
138 int initExceptionCount;
142 * java.lang.System properties set from the command line.
149 * Where the VM goes to find system classes.
151 ClassPathEntry* bootClassPath;
152 /* used by the DEX optimizer to load classes from an unfinished DEX */
153 DvmDex* bootClassPathOptExtra;
154 bool optimizingBootstrapClass;
157 * Loaded classes, hashed by class name. Each entry is a ClassObject*,
158 * allocated in GC space.
160 HashTable* loadedClasses;
163 * Value for the next class serial number to be assigned. This is
164 * incremented as we load classes. Failed loads and races may result
165 * in some numbers being skipped, and the serial number is not
166 * guaranteed to start at 1, so the current value should not be used
167 * as a count of loaded classes.
169 volatile int classSerialNumber;
172 * Classes with a low classSerialNumber are probably in the zygote, and
173 * their InitiatingLoaderList is not used, to promote sharing. The list is
176 InitiatingLoaderList* initiatingLoaderList;
181 HashTable* internedStrings;
184 * Quick lookups for popular classes used internally.
186 ClassObject* classJavaLangClass;
187 ClassObject* classJavaLangClassArray;
188 ClassObject* classJavaLangError;
189 ClassObject* classJavaLangObject;
190 ClassObject* classJavaLangObjectArray;
191 ClassObject* classJavaLangRuntimeException;
192 ClassObject* classJavaLangString;
193 ClassObject* classJavaLangThread;
194 ClassObject* classJavaLangVMThread;
195 ClassObject* classJavaLangThreadGroup;
196 ClassObject* classJavaLangThrowable;
197 ClassObject* classJavaLangStackOverflowError;
198 ClassObject* classJavaLangStackTraceElement;
199 ClassObject* classJavaLangStackTraceElementArray;
200 ClassObject* classJavaLangAnnotationAnnotationArray;
201 ClassObject* classJavaLangAnnotationAnnotationArrayArray;
202 ClassObject* classJavaLangReflectAccessibleObject;
203 ClassObject* classJavaLangReflectConstructor;
204 ClassObject* classJavaLangReflectConstructorArray;
205 ClassObject* classJavaLangReflectField;
206 ClassObject* classJavaLangReflectFieldArray;
207 ClassObject* classJavaLangReflectMethod;
208 ClassObject* classJavaLangReflectMethodArray;
209 ClassObject* classJavaLangReflectProxy;
210 ClassObject* classJavaLangExceptionInInitializerError;
211 ClassObject* classJavaLangRefPhantomReference;
212 ClassObject* classJavaLangRefReference;
213 ClassObject* classJavaNioReadWriteDirectByteBuffer;
214 ClassObject* classJavaSecurityAccessController;
215 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
216 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
217 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
218 ClassObject* classOrgApacheHarmonyNioInternalDirectBuffer;
219 jclass jclassOrgApacheHarmonyNioInternalDirectBuffer;
221 /* synthetic classes for arrays of primitives */
222 ClassObject* classArrayBoolean;
223 ClassObject* classArrayChar;
224 ClassObject* classArrayFloat;
225 ClassObject* classArrayDouble;
226 ClassObject* classArrayByte;
227 ClassObject* classArrayShort;
228 ClassObject* classArrayInt;
229 ClassObject* classArrayLong;
231 /* method offsets - Object */
232 int voffJavaLangObject_equals;
233 int voffJavaLangObject_hashCode;
234 int voffJavaLangObject_toString;
235 int voffJavaLangObject_finalize;
237 /* field offsets - Class */
238 int offJavaLangClass_pd;
240 /* field offsets - String */
241 int javaLangStringReady; /* 0=not init, 1=ready, -1=initing */
242 int offJavaLangString_value;
243 int offJavaLangString_count;
244 int offJavaLangString_offset;
245 int offJavaLangString_hashCode;
247 /* field offsets - Thread */
248 int offJavaLangThread_vmThread;
249 int offJavaLangThread_group;
250 int offJavaLangThread_daemon;
251 int offJavaLangThread_name;
252 int offJavaLangThread_priority;
254 /* method offsets - Thread */
255 int voffJavaLangThread_run;
257 /* field offsets - VMThread */
258 int offJavaLangVMThread_thread;
259 int offJavaLangVMThread_vmData;
261 /* method offsets - ThreadGroup */
262 int voffJavaLangThreadGroup_removeThread;
264 /* field offsets - Throwable */
265 int offJavaLangThrowable_stackState;
266 int offJavaLangThrowable_message;
267 int offJavaLangThrowable_cause;
269 /* field offsets - java.lang.reflect.* */
270 int offJavaLangReflectAccessibleObject_flag;
271 int offJavaLangReflectConstructor_slot;
272 int offJavaLangReflectConstructor_declClass;
273 int offJavaLangReflectField_slot;
274 int offJavaLangReflectField_declClass;
275 int offJavaLangReflectMethod_slot;
276 int offJavaLangReflectMethod_declClass;
278 /* field offsets - java.lang.ref.Reference */
279 int offJavaLangRefReference_referent;
280 int offJavaLangRefReference_queue;
281 int offJavaLangRefReference_queueNext;
282 int offJavaLangRefReference_pendingNext;
284 /* method pointers - java.lang.ref.Reference */
285 Method* methJavaLangRefReference_enqueueInternal;
287 /* field offsets - java.nio.Buffer and java.nio.DirectByteBufferImpl */
288 //int offJavaNioBuffer_capacity;
289 //int offJavaNioDirectByteBufferImpl_pointer;
291 /* method pointers - java.security.AccessController */
292 volatile bool javaSecurityAccessControllerReady;
293 Method* methJavaSecurityAccessController_doPrivileged[4];
295 /* constructor method pointers; no vtable involved, so use Method* */
296 Method* methJavaLangStackTraceElement_init;
297 Method* methJavaLangExceptionInInitializerError_init;
298 Method* methJavaLangRefPhantomReference_init;
299 Method* methJavaLangReflectConstructor_init;
300 Method* methJavaLangReflectField_init;
301 Method* methJavaLangReflectMethod_init;
302 Method* methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
304 /* static method pointers - android.lang.annotation.* */
306 methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
308 /* direct method pointers - java.lang.reflect.Proxy */
309 Method* methJavaLangReflectProxy_constructorPrototype;
311 /* field offsets - java.lang.reflect.Proxy */
312 int offJavaLangReflectProxy_h;
314 /* fake native entry point method */
315 Method* methFakeNativeEntry;
317 /* assorted direct buffer helpers */
318 Method* methJavaNioReadWriteDirectByteBuffer_init;
319 Method* methOrgApacheHarmonyLuniPlatformPlatformAddress_on;
320 Method* methOrgApacheHarmonyNioInternalDirectBuffer_getEffectiveAddress;
321 int offJavaNioBuffer_capacity;
322 int offJavaNioBuffer_effectiveDirectAddress;
323 int offOrgApacheHarmonyLuniPlatformPlatformAddress_osaddr;
324 int voffOrgApacheHarmonyLuniPlatformPlatformAddress_toLong;
327 * VM-synthesized primitive classes, for arrays.
329 ClassObject* volatile primitiveClass[PRIM_MAX];
332 * Thread list. This always has at least one element in it (main),
333 * and main is always the first entry.
335 * The threadListLock is used for several things, including the thread
336 * start condition variable. Generally speaking, you must hold the
337 * threadListLock when:
338 * - adding/removing items from the list
339 * - waiting on or signaling threadStartCond
340 * - examining the Thread struct for another thread (this is to avoid
341 * one thread freeing the Thread struct while another thread is
345 pthread_mutex_t threadListLock;
347 pthread_cond_t threadStartCond;
350 * The thread code grabs this before suspending all threads. There
351 * are a few things that can cause a "suspend all":
352 * (1) the GC is starting;
353 * (2) the debugger has sent a "suspend all" request;
354 * (3) a thread has hit a breakpoint or exception that the debugger
355 * has marked as a "suspend all" event;
356 * (4) the SignalCatcher caught a signal that requires suspension.
357 * (5) (if implemented) the JIT needs to perform a heavyweight
358 * rearrangement of the translation cache or JitTable.
360 * Because we use "safe point" self-suspension, it is never safe to
361 * do a blocking "lock" call on this mutex -- if it has been acquired,
362 * somebody is probably trying to put you to sleep. The leading '_' is
363 * intended as a reminder that this lock is special.
365 pthread_mutex_t _threadSuspendLock;
368 * Guards Thread->suspendCount for all threads, and provides the lock
369 * for the condition variable that all suspended threads sleep on
370 * (threadSuspendCountCond).
372 * This has to be separate from threadListLock because of the way
373 * threads put themselves to sleep.
375 pthread_mutex_t threadSuspendCountLock;
378 * Suspended threads sleep on this. They should sleep on the condition
379 * variable until their "suspend count" is zero.
381 * Paired with "threadSuspendCountLock".
383 pthread_cond_t threadSuspendCountCond;
386 * Sum of all threads' suspendCount fields. The JIT needs to know if any
387 * thread is suspended. Guarded by threadSuspendCountLock.
389 int sumThreadSuspendCount;
392 * MUTEX ORDERING: when locking multiple mutexes, always grab them in
393 * this order to avoid deadlock:
395 * (1) _threadSuspendLock (use lockThreadSuspend())
396 * (2) threadListLock (use dvmLockThreadList())
397 * (3) threadSuspendCountLock (use lockThreadSuspendCount())
402 * Thread ID bitmap. We want threads to have small integer IDs so
403 * we can use them in "thin locks".
405 BitVector* threadIdMap;
408 * Manage exit conditions. The VM exits when all non-daemon threads
409 * have exited. If the main thread returns early, we need to sleep
410 * on a condition variable.
412 int nonDaemonThreadCount; /* must hold threadListLock to access */
413 //pthread_mutex_t vmExitLock;
414 pthread_cond_t vmExitCond;
417 * The set of DEX files loaded by custom class loaders.
419 HashTable* userDexFiles;
422 * JNI global reference table.
424 #ifdef USE_INDIRECT_REF
425 IndirectRefTable jniGlobalRefTable;
427 ReferenceTable jniGlobalRefTable;
429 pthread_mutex_t jniGlobalRefLock;
430 int jniGlobalRefHiMark;
431 int jniGlobalRefLoMark;
434 * JNI pinned object table (used for primitive arrays).
436 ReferenceTable jniPinRefTable;
437 pthread_mutex_t jniPinRefLock;
440 * Native shared library table.
442 HashTable* nativeLibs;
445 * GC heap lock. Functions like gcMalloc() acquire this before making
446 * any changes to the heap. It is held throughout garbage collection.
448 pthread_mutex_t gcHeapLock;
451 * Condition variable to queue threads waiting to retry an
452 * allocation. Signaled after a concurrent GC is completed.
454 pthread_cond_t gcHeapCond;
456 /* Opaque pointer representing the heap. */
459 /* The card table base, modified as needed for marking cards. */
460 u1* biasedCardTableBase;
463 * Pre-allocated throwables.
465 Object* outOfMemoryObj;
466 Object* internalErrorObj;
467 Object* noClassDefFoundErrorObj;
469 /* Monitor list, so we can free them */
470 /*volatile*/ Monitor* monitorList;
472 /* Monitor for Thread.sleep() implementation */
473 Monitor* threadSleepMon;
475 /* set when we create a second heap inside the zygote */
476 bool newZygoteHeapAllocated;
481 pthread_key_t pthreadKeySelf; /* Thread*, for dvmThreadSelf */
484 * JNI allows you to have multiple VMs, but we limit ourselves to 1,
485 * so "vmList" is really just a pointer to the one and only VM.
490 * Cache results of "A instanceof B".
492 AtomicCache* instanceofCache;
494 /* instruction width table, used for optimization and verification */
495 InstructionWidth* instrWidth;
496 /* instruction flags table, used for verification */
497 InstructionFlags* instrFlags;
498 /* instruction format table, used for verification */
499 InstructionFormat* instrFormat;
501 /* inline substitution table, used during optimization */
502 InlineSub* inlineSubs;
505 * Bootstrap class loader linear allocator.
507 LinearAllocHdr* pBootLoaderAlloc;
511 * Heap worker thread.
513 bool heapWorkerInitialized;
514 bool heapWorkerReady;
516 pthread_t heapWorkerHandle;
517 pthread_mutex_t heapWorkerLock;
518 pthread_cond_t heapWorkerCond;
519 pthread_cond_t heapWorkerIdleCond;
520 pthread_mutex_t heapWorkerListLock;
523 * Compute some stats on loaded classes.
525 int numLoadedClasses;
526 int numDeclaredMethods;
527 int numDeclaredInstFields;
528 int numDeclaredStaticFields;
530 /* when using a native debugger, set this to suppress watchdog timers */
531 bool nativeDebuggerActive;
534 * JDWP debugger support.
536 * Note "debuggerActive" is accessed from mterp, so its storage size and
537 * meaning must not be changed without updating the assembly sources.
539 bool debuggerConnected; /* debugger or DDMS is connected */
540 u1 debuggerActive; /* debugger is making requests */
541 JdwpState* jdwpState;
544 * Registry of objects known to the debugger.
546 HashTable* dbgRegistry;
549 * Debugger breakpoint table.
551 BreakpointSet* breakpointSet;
554 * Single-step control struct. We currently only allow one thread to
555 * be single-stepping at a time, which is all that really makes sense,
556 * but it's possible we may need to expand this to be per-thread.
558 StepControl stepControl;
561 * DDM features embedded in the VM.
563 bool ddmThreadNotification;
566 * Zygote (partially-started process) support
571 * Used for tracking allocations that we report to DDMS. When the feature
572 * is enabled (through a DDMS request) the "allocRecords" pointer becomes
575 pthread_mutex_t allocTrackerLock;
576 AllocRecord* allocRecords;
577 int allocRecordHead; /* most-recently-added entry */
578 int allocRecordCount; /* #of valid entries */
580 #ifdef WITH_ALLOC_LIMITS
581 /* set on first use of an alloc limit, never cleared */
582 bool checkAllocLimits;
583 /* allocation limit, for setGlobalAllocationLimit() regression testing */
587 #ifdef WITH_DEADLOCK_PREDICTION
588 /* global lock on history tree accesses */
589 pthread_mutex_t deadlockHistoryLock;
591 enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
596 * When a profiler is enabled, this is incremented. Distinct profilers
597 * include "dmtrace" method tracing, emulator method tracing, and
598 * possibly instruction counting.
600 * The purpose of this is to have a single value that the interpreter
601 * can check to see if any profiling activity is enabled.
603 volatile int activeProfilers;
606 * State for method-trace profiling.
608 MethodTraceState methodTrace;
611 * State for emulator tracing.
613 void* emulatorTracePage;
614 int emulatorTraceEnableCount;
617 * Global state for memory allocation profiling.
619 AllocProfState allocProf;
622 * Pointers to the original methods for things that have been inlined.
623 * This makes it easy for us to output method entry/exit records for
624 * the method calls we're not actually making.
626 Method** inlinedMethods;
629 * Dalvik instruction counts (256 entries).
631 int* executedInstrCounts;
632 bool instructionCountEnableCount;
636 * Signal catcher thread (for SIGQUIT).
638 pthread_t signalCatcherHandle;
639 bool haltSignalCatcher;
642 * Stdout/stderr conversion thread.
644 bool haltStdioConverter;
645 bool stdioConverterReady;
646 pthread_t stdioConverterHandle;
647 pthread_mutex_t stdioConverterLock;
648 pthread_cond_t stdioConverterCond;
651 * pid of the system_server process. We track it so that when system server
652 * crashes the Zygote process will be killed and restarted.
654 pid_t systemServerPid;
656 int kernelGroupScheduling;
658 //#define COUNT_PRECISE_METHODS
659 #ifdef COUNT_PRECISE_METHODS
660 PointerSet* preciseMethods;
663 /* some RegisterMap statistics, useful during development */
664 void* registerMapStats;
667 extern struct DvmGlobals gDvm;
669 #if defined(WITH_JIT)
672 * Exiting the compiled code w/o chaining will incur overhead to look up the
673 * target in the code cache which is extra work only when JIT is enabled. So
674 * we want to monitor it closely to make sure we don't have performance bugs.
676 typedef enum NoChainExits {
677 kInlineCacheMiss = 0,
678 kCallsiteInterpreted,
685 * JIT-specific global state
687 struct DvmJitGlobals {
689 * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
690 * chain fields within the JIT hash table. Note carefully the access
692 * Only writes are guarded, and the guarded fields must be updated in a
693 * specific order using atomic operations. Further, once a field is
694 * written it cannot be changed without halting all threads.
696 * The write order is:
699 * 3) chain [if necessary]
701 * This mutex also guards both read and write of curJitTableEntries.
703 pthread_mutex_t tableLock;
705 /* The JIT hash table. Note that for access speed, copies of this pointer
706 * are stored in each thread. */
707 struct JitEntry *pJitEntryTable;
709 /* Array of profile threshold counters */
710 unsigned char *pProfTable;
712 /* Copy of pProfTable used for temporarily disabling the Jit */
713 unsigned char *pProfTableCopy;
715 /* Size of JIT hash table in entries. Must be a power of 2 */
716 unsigned int jitTableSize;
718 /* Mask used in hash function for JitTable. Should be jitTableSize-1 */
719 unsigned int jitTableMask;
721 /* How many entries in the JitEntryTable are in use */
722 unsigned int jitTableEntriesUsed;
724 /* Bytes allocated for the code cache */
725 unsigned int codeCacheSize;
727 /* Trigger for trace selection */
728 unsigned short threshold;
730 /* JIT Compiler Control */
731 bool haltCompilerThread;
733 pthread_t compilerHandle;
734 pthread_mutex_t compilerLock;
735 pthread_mutex_t compilerICPatchLock;
736 pthread_cond_t compilerQueueActivity;
737 pthread_cond_t compilerQueueEmpty;
738 volatile int compilerQueueLength;
739 int compilerHighWater;
740 int compilerWorkEnqueueIndex;
741 int compilerWorkDequeueIndex;
742 int compilerICPatchIndex;
744 /* JIT internal stats */
745 int compilerMaxQueued;
746 int translationChains;
748 /* Compiled code cache */
751 /* Bytes used by the code templates */
752 unsigned int templateSize;
754 /* Bytes already used in the code cache */
755 unsigned int codeCacheByteUsed;
757 /* Number of installed compilations in the cache */
758 unsigned int numCompilations;
760 /* Flag to indicate that the code cache is full */
764 unsigned int pageSizeMask;
766 /* Lock to change the protection type of the code cache */
767 pthread_mutex_t codeCacheProtectionLock;
769 /* Number of times that the code cache has been reset */
770 int numCodeCacheReset;
772 /* Number of times that the code cache reset request has been delayed */
773 int numCodeCacheResetDelayed;
775 /* true/false: compile/reject opcodes specified in the -Xjitop list */
776 bool includeSelectedOp;
778 /* true/false: compile/reject methods specified in the -Xjitmethod list */
779 bool includeSelectedMethod;
781 /* Disable JIT for selected opcodes - one bit for each opcode */
784 /* Disable JIT for selected methods */
785 HashTable *methodTable;
787 /* Flag to dump all compiled code */
790 /* Flag to count trace execution */
793 /* Vector to disable selected optimizations */
796 /* Table to track the overall and trace statistics of hot methods */
797 HashTable* methodStatsTable;
799 /* Filter method compilation blacklist with call-graph information */
802 /* New translation chain has been set up */
803 volatile bool hasNewChain;
805 #if defined(WITH_SELF_VERIFICATION)
806 /* Spin when error is detected, volatile so GDB can reset it */
807 volatile bool selfVerificationSpin;
810 /* Framework or stand-alone? */
811 bool runningInAndroidFramework;
813 /* Framework callback happened? */
814 bool alreadyEnabledViaFramework;
816 /* Framework requests to disable the JIT for good */
819 #if defined(SIGNATURE_BREAKPOINT)
820 /* Signature breakpoint */
821 u4 signatureBreakpointSize; // # of words
822 u4 *signatureBreakpoint; // Signature content
825 #if defined(WITH_JIT_TUNING)
826 /* Performance tuning counters */
827 int addrLookupsFound;
828 int addrLookupsNotFound;
829 int noChainExit[kNoChainExitLast];
832 int invokeMonomorphic;
833 int invokePolymorphic;
842 int codeCachePatches;
845 /* Place arrays at the end to ease the display in gdb sessions */
847 /* Work order queue for compilations */
848 CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
850 /* Work order queue for predicted chain patching */
851 ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
854 extern struct DvmJitGlobals gDvmJit;
856 #if defined(WITH_JIT_TUNING)
857 extern int gDvmICHitCount;
862 #endif /*_DALVIK_GLOBALS*/