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;
126 bool verifyCardTable;
128 int assertionCtrlCount;
129 AssertionControl* assertionCtrl;
131 ExecutionMode executionMode;
134 * VM init management.
137 int initExceptionCount;
141 * java.lang.System properties set from the command line.
148 * Where the VM goes to find system classes.
150 ClassPathEntry* bootClassPath;
151 /* used by the DEX optimizer to load classes from an unfinished DEX */
152 DvmDex* bootClassPathOptExtra;
153 bool optimizingBootstrapClass;
156 * Loaded classes, hashed by class name. Each entry is a ClassObject*,
157 * allocated in GC space.
159 HashTable* loadedClasses;
162 * Value for the next class serial number to be assigned. This is
163 * incremented as we load classes. Failed loads and races may result
164 * in some numbers being skipped, and the serial number is not
165 * guaranteed to start at 1, so the current value should not be used
166 * as a count of loaded classes.
168 volatile int classSerialNumber;
171 * Classes with a low classSerialNumber are probably in the zygote, and
172 * their InitiatingLoaderList is not used, to promote sharing. The list is
175 InitiatingLoaderList* initiatingLoaderList;
180 HashTable* internedStrings;
183 * Quick lookups for popular classes used internally.
185 ClassObject* classJavaLangClass;
186 ClassObject* classJavaLangClassArray;
187 ClassObject* classJavaLangError;
188 ClassObject* classJavaLangObject;
189 ClassObject* classJavaLangObjectArray;
190 ClassObject* classJavaLangRuntimeException;
191 ClassObject* classJavaLangString;
192 ClassObject* classJavaLangThread;
193 ClassObject* classJavaLangVMThread;
194 ClassObject* classJavaLangThreadGroup;
195 ClassObject* classJavaLangThrowable;
196 ClassObject* classJavaLangStackOverflowError;
197 ClassObject* classJavaLangStackTraceElement;
198 ClassObject* classJavaLangStackTraceElementArray;
199 ClassObject* classJavaLangAnnotationAnnotationArray;
200 ClassObject* classJavaLangAnnotationAnnotationArrayArray;
201 ClassObject* classJavaLangReflectAccessibleObject;
202 ClassObject* classJavaLangReflectConstructor;
203 ClassObject* classJavaLangReflectConstructorArray;
204 ClassObject* classJavaLangReflectField;
205 ClassObject* classJavaLangReflectFieldArray;
206 ClassObject* classJavaLangReflectMethod;
207 ClassObject* classJavaLangReflectMethodArray;
208 ClassObject* classJavaLangReflectProxy;
209 ClassObject* classJavaLangExceptionInInitializerError;
210 ClassObject* classJavaLangRefPhantomReference;
211 ClassObject* classJavaLangRefReference;
212 ClassObject* classJavaNioReadWriteDirectByteBuffer;
213 ClassObject* classJavaSecurityAccessController;
214 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
215 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
216 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
217 ClassObject* classOrgApacheHarmonyNioInternalDirectBuffer;
218 jclass jclassOrgApacheHarmonyNioInternalDirectBuffer;
220 /* synthetic classes for arrays of primitives */
221 ClassObject* classArrayBoolean;
222 ClassObject* classArrayChar;
223 ClassObject* classArrayFloat;
224 ClassObject* classArrayDouble;
225 ClassObject* classArrayByte;
226 ClassObject* classArrayShort;
227 ClassObject* classArrayInt;
228 ClassObject* classArrayLong;
230 /* method offsets - Object */
231 int voffJavaLangObject_equals;
232 int voffJavaLangObject_hashCode;
233 int voffJavaLangObject_toString;
234 int voffJavaLangObject_finalize;
236 /* field offsets - Class */
237 int offJavaLangClass_pd;
239 /* field offsets - String */
240 int javaLangStringReady; /* 0=not init, 1=ready, -1=initing */
241 int offJavaLangString_value;
242 int offJavaLangString_count;
243 int offJavaLangString_offset;
244 int offJavaLangString_hashCode;
246 /* field offsets - Thread */
247 int offJavaLangThread_vmThread;
248 int offJavaLangThread_group;
249 int offJavaLangThread_daemon;
250 int offJavaLangThread_name;
251 int offJavaLangThread_priority;
253 /* method offsets - Thread */
254 int voffJavaLangThread_run;
256 /* field offsets - VMThread */
257 int offJavaLangVMThread_thread;
258 int offJavaLangVMThread_vmData;
260 /* method offsets - ThreadGroup */
261 int voffJavaLangThreadGroup_removeThread;
263 /* field offsets - Throwable */
264 int offJavaLangThrowable_stackState;
265 int offJavaLangThrowable_message;
266 int offJavaLangThrowable_cause;
268 /* field offsets - java.lang.reflect.* */
269 int offJavaLangReflectAccessibleObject_flag;
270 int offJavaLangReflectConstructor_slot;
271 int offJavaLangReflectConstructor_declClass;
272 int offJavaLangReflectField_slot;
273 int offJavaLangReflectField_declClass;
274 int offJavaLangReflectMethod_slot;
275 int offJavaLangReflectMethod_declClass;
277 /* field offsets - java.lang.ref.Reference */
278 int offJavaLangRefReference_referent;
279 int offJavaLangRefReference_queue;
280 int offJavaLangRefReference_queueNext;
281 int offJavaLangRefReference_pendingNext;
283 /* method pointers - java.lang.ref.Reference */
284 Method* methJavaLangRefReference_enqueueInternal;
286 /* field offsets - java.nio.Buffer and java.nio.DirectByteBufferImpl */
287 //int offJavaNioBuffer_capacity;
288 //int offJavaNioDirectByteBufferImpl_pointer;
290 /* method pointers - java.security.AccessController */
291 volatile bool javaSecurityAccessControllerReady;
292 Method* methJavaSecurityAccessController_doPrivileged[4];
294 /* constructor method pointers; no vtable involved, so use Method* */
295 Method* methJavaLangStackTraceElement_init;
296 Method* methJavaLangExceptionInInitializerError_init;
297 Method* methJavaLangRefPhantomReference_init;
298 Method* methJavaLangReflectConstructor_init;
299 Method* methJavaLangReflectField_init;
300 Method* methJavaLangReflectMethod_init;
301 Method* methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
303 /* static method pointers - android.lang.annotation.* */
305 methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
307 /* direct method pointers - java.lang.reflect.Proxy */
308 Method* methJavaLangReflectProxy_constructorPrototype;
310 /* field offsets - java.lang.reflect.Proxy */
311 int offJavaLangReflectProxy_h;
313 /* fake native entry point method */
314 Method* methFakeNativeEntry;
316 /* assorted direct buffer helpers */
317 Method* methJavaNioReadWriteDirectByteBuffer_init;
318 Method* methOrgApacheHarmonyLuniPlatformPlatformAddress_on;
319 Method* methOrgApacheHarmonyNioInternalDirectBuffer_getEffectiveAddress;
320 int offJavaNioBuffer_capacity;
321 int offJavaNioBuffer_effectiveDirectAddress;
322 int offOrgApacheHarmonyLuniPlatformPlatformAddress_osaddr;
323 int voffOrgApacheHarmonyLuniPlatformPlatformAddress_toLong;
326 * VM-synthesized primitive classes, for arrays.
328 ClassObject* volatile primitiveClass[PRIM_MAX];
331 * Thread list. This always has at least one element in it (main),
332 * and main is always the first entry.
334 * The threadListLock is used for several things, including the thread
335 * start condition variable. Generally speaking, you must hold the
336 * threadListLock when:
337 * - adding/removing items from the list
338 * - waiting on or signaling threadStartCond
339 * - examining the Thread struct for another thread (this is to avoid
340 * one thread freeing the Thread struct while another thread is
344 pthread_mutex_t threadListLock;
346 pthread_cond_t threadStartCond;
349 * The thread code grabs this before suspending all threads. There
350 * are a few things that can cause a "suspend all":
351 * (1) the GC is starting;
352 * (2) the debugger has sent a "suspend all" request;
353 * (3) a thread has hit a breakpoint or exception that the debugger
354 * has marked as a "suspend all" event;
355 * (4) the SignalCatcher caught a signal that requires suspension.
356 * (5) (if implemented) the JIT needs to perform a heavyweight
357 * rearrangement of the translation cache or JitTable.
359 * Because we use "safe point" self-suspension, it is never safe to
360 * do a blocking "lock" call on this mutex -- if it has been acquired,
361 * somebody is probably trying to put you to sleep. The leading '_' is
362 * intended as a reminder that this lock is special.
364 pthread_mutex_t _threadSuspendLock;
367 * Guards Thread->suspendCount for all threads, and provides the lock
368 * for the condition variable that all suspended threads sleep on
369 * (threadSuspendCountCond).
371 * This has to be separate from threadListLock because of the way
372 * threads put themselves to sleep.
374 pthread_mutex_t threadSuspendCountLock;
377 * Suspended threads sleep on this. They should sleep on the condition
378 * variable until their "suspend count" is zero.
380 * Paired with "threadSuspendCountLock".
382 pthread_cond_t threadSuspendCountCond;
385 * Sum of all threads' suspendCount fields. The JIT needs to know if any
386 * thread is suspended. Guarded by threadSuspendCountLock.
388 int sumThreadSuspendCount;
391 * MUTEX ORDERING: when locking multiple mutexes, always grab them in
392 * this order to avoid deadlock:
394 * (1) _threadSuspendLock (use lockThreadSuspend())
395 * (2) threadListLock (use dvmLockThreadList())
396 * (3) threadSuspendCountLock (use lockThreadSuspendCount())
401 * Thread ID bitmap. We want threads to have small integer IDs so
402 * we can use them in "thin locks".
404 BitVector* threadIdMap;
407 * Manage exit conditions. The VM exits when all non-daemon threads
408 * have exited. If the main thread returns early, we need to sleep
409 * on a condition variable.
411 int nonDaemonThreadCount; /* must hold threadListLock to access */
412 //pthread_mutex_t vmExitLock;
413 pthread_cond_t vmExitCond;
416 * The set of DEX files loaded by custom class loaders.
418 HashTable* userDexFiles;
421 * JNI global reference table.
423 #ifdef USE_INDIRECT_REF
424 IndirectRefTable jniGlobalRefTable;
426 ReferenceTable jniGlobalRefTable;
428 pthread_mutex_t jniGlobalRefLock;
429 int jniGlobalRefHiMark;
430 int jniGlobalRefLoMark;
433 * JNI pinned object table (used for primitive arrays).
435 ReferenceTable jniPinRefTable;
436 pthread_mutex_t jniPinRefLock;
439 * Native shared library table.
441 HashTable* nativeLibs;
444 * GC heap lock. Functions like gcMalloc() acquire this before making
445 * any changes to the heap. It is held throughout garbage collection.
447 pthread_mutex_t gcHeapLock;
450 * Condition variable to queue threads waiting to retry an
451 * allocation. Signaled after a concurrent GC is completed.
453 pthread_cond_t gcHeapCond;
455 /* Opaque pointer representing the heap. */
458 /* The card table base, modified as needed for marking cards. */
459 u1* biasedCardTableBase;
462 * Pre-allocated throwables.
464 Object* outOfMemoryObj;
465 Object* internalErrorObj;
466 Object* noClassDefFoundErrorObj;
468 /* Monitor list, so we can free them */
469 /*volatile*/ Monitor* monitorList;
471 /* Monitor for Thread.sleep() implementation */
472 Monitor* threadSleepMon;
474 /* set when we create a second heap inside the zygote */
475 bool newZygoteHeapAllocated;
480 pthread_key_t pthreadKeySelf; /* Thread*, for dvmThreadSelf */
483 * JNI allows you to have multiple VMs, but we limit ourselves to 1,
484 * so "vmList" is really just a pointer to the one and only VM.
489 * Cache results of "A instanceof B".
491 AtomicCache* instanceofCache;
493 /* instruction width table, used for optimization and verification */
494 InstructionWidth* instrWidth;
495 /* instruction flags table, used for verification */
496 InstructionFlags* instrFlags;
497 /* instruction format table, used for verification */
498 InstructionFormat* instrFormat;
500 /* inline substitution table, used during optimization */
501 InlineSub* inlineSubs;
504 * Bootstrap class loader linear allocator.
506 LinearAllocHdr* pBootLoaderAlloc;
510 * Heap worker thread.
512 bool heapWorkerInitialized;
513 bool heapWorkerReady;
515 pthread_t heapWorkerHandle;
516 pthread_mutex_t heapWorkerLock;
517 pthread_cond_t heapWorkerCond;
518 pthread_cond_t heapWorkerIdleCond;
519 pthread_mutex_t heapWorkerListLock;
522 * Compute some stats on loaded classes.
524 int numLoadedClasses;
525 int numDeclaredMethods;
526 int numDeclaredInstFields;
527 int numDeclaredStaticFields;
529 /* when using a native debugger, set this to suppress watchdog timers */
530 bool nativeDebuggerActive;
533 * JDWP debugger support.
535 * Note "debuggerActive" is accessed from mterp, so its storage size and
536 * meaning must not be changed without updating the assembly sources.
538 bool debuggerConnected; /* debugger or DDMS is connected */
539 u1 debuggerActive; /* debugger is making requests */
540 JdwpState* jdwpState;
543 * Registry of objects known to the debugger.
545 HashTable* dbgRegistry;
548 * Debugger breakpoint table.
550 BreakpointSet* breakpointSet;
553 * Single-step control struct. We currently only allow one thread to
554 * be single-stepping at a time, which is all that really makes sense,
555 * but it's possible we may need to expand this to be per-thread.
557 StepControl stepControl;
560 * DDM features embedded in the VM.
562 bool ddmThreadNotification;
565 * Zygote (partially-started process) support
570 * Used for tracking allocations that we report to DDMS. When the feature
571 * is enabled (through a DDMS request) the "allocRecords" pointer becomes
574 pthread_mutex_t allocTrackerLock;
575 AllocRecord* allocRecords;
576 int allocRecordHead; /* most-recently-added entry */
577 int allocRecordCount; /* #of valid entries */
579 #ifdef WITH_ALLOC_LIMITS
580 /* set on first use of an alloc limit, never cleared */
581 bool checkAllocLimits;
582 /* allocation limit, for setGlobalAllocationLimit() regression testing */
586 #ifdef WITH_DEADLOCK_PREDICTION
587 /* global lock on history tree accesses */
588 pthread_mutex_t deadlockHistoryLock;
590 enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
595 * When a profiler is enabled, this is incremented. Distinct profilers
596 * include "dmtrace" method tracing, emulator method tracing, and
597 * possibly instruction counting.
599 * The purpose of this is to have a single value that the interpreter
600 * can check to see if any profiling activity is enabled.
602 volatile int activeProfilers;
605 * State for method-trace profiling.
607 MethodTraceState methodTrace;
610 * State for emulator tracing.
612 void* emulatorTracePage;
613 int emulatorTraceEnableCount;
616 * Global state for memory allocation profiling.
618 AllocProfState allocProf;
621 * Pointers to the original methods for things that have been inlined.
622 * This makes it easy for us to output method entry/exit records for
623 * the method calls we're not actually making.
625 Method** inlinedMethods;
628 * Dalvik instruction counts (256 entries).
630 int* executedInstrCounts;
631 bool instructionCountEnableCount;
635 * Signal catcher thread (for SIGQUIT).
637 pthread_t signalCatcherHandle;
638 bool haltSignalCatcher;
641 * Stdout/stderr conversion thread.
643 bool haltStdioConverter;
644 bool stdioConverterReady;
645 pthread_t stdioConverterHandle;
646 pthread_mutex_t stdioConverterLock;
647 pthread_cond_t stdioConverterCond;
650 * pid of the system_server process. We track it so that when system server
651 * crashes the Zygote process will be killed and restarted.
653 pid_t systemServerPid;
655 int kernelGroupScheduling;
657 //#define COUNT_PRECISE_METHODS
658 #ifdef COUNT_PRECISE_METHODS
659 PointerSet* preciseMethods;
662 /* some RegisterMap statistics, useful during development */
663 void* registerMapStats;
666 extern struct DvmGlobals gDvm;
668 #if defined(WITH_JIT)
671 * Exiting the compiled code w/o chaining will incur overhead to look up the
672 * target in the code cache which is extra work only when JIT is enabled. So
673 * we want to monitor it closely to make sure we don't have performance bugs.
675 typedef enum NoChainExits {
676 kInlineCacheMiss = 0,
677 kCallsiteInterpreted,
684 * JIT-specific global state
686 struct DvmJitGlobals {
688 * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
689 * chain fields within the JIT hash table. Note carefully the access
691 * Only writes are guarded, and the guarded fields must be updated in a
692 * specific order using atomic operations. Further, once a field is
693 * written it cannot be changed without halting all threads.
695 * The write order is:
698 * 3) chain [if necessary]
700 * This mutex also guards both read and write of curJitTableEntries.
702 pthread_mutex_t tableLock;
704 /* The JIT hash table. Note that for access speed, copies of this pointer
705 * are stored in each thread. */
706 struct JitEntry *pJitEntryTable;
708 /* Array of profile threshold counters */
709 unsigned char *pProfTable;
711 /* Copy of pProfTable used for temporarily disabling the Jit */
712 unsigned char *pProfTableCopy;
714 /* Size of JIT hash table in entries. Must be a power of 2 */
715 unsigned int jitTableSize;
717 /* Mask used in hash function for JitTable. Should be jitTableSize-1 */
718 unsigned int jitTableMask;
720 /* How many entries in the JitEntryTable are in use */
721 unsigned int jitTableEntriesUsed;
723 /* Bytes allocated for the code cache */
724 unsigned int codeCacheSize;
726 /* Trigger for trace selection */
727 unsigned short threshold;
729 /* JIT Compiler Control */
730 bool haltCompilerThread;
732 pthread_t compilerHandle;
733 pthread_mutex_t compilerLock;
734 pthread_mutex_t compilerICPatchLock;
735 pthread_cond_t compilerQueueActivity;
736 pthread_cond_t compilerQueueEmpty;
737 volatile int compilerQueueLength;
738 int compilerHighWater;
739 int compilerWorkEnqueueIndex;
740 int compilerWorkDequeueIndex;
741 int compilerICPatchIndex;
743 /* JIT internal stats */
744 int compilerMaxQueued;
745 int translationChains;
747 /* Compiled code cache */
750 /* Bytes used by the code templates */
751 unsigned int templateSize;
753 /* Bytes already used in the code cache */
754 unsigned int codeCacheByteUsed;
756 /* Number of installed compilations in the cache */
757 unsigned int numCompilations;
759 /* Flag to indicate that the code cache is full */
763 unsigned int pageSizeMask;
765 /* Lock to change the protection type of the code cache */
766 pthread_mutex_t codeCacheProtectionLock;
768 /* Number of times that the code cache has been reset */
769 int numCodeCacheReset;
771 /* Number of times that the code cache reset request has been delayed */
772 int numCodeCacheResetDelayed;
774 /* true/false: compile/reject opcodes specified in the -Xjitop list */
775 bool includeSelectedOp;
777 /* true/false: compile/reject methods specified in the -Xjitmethod list */
778 bool includeSelectedMethod;
780 /* Disable JIT for selected opcodes - one bit for each opcode */
783 /* Disable JIT for selected methods */
784 HashTable *methodTable;
786 /* Flag to dump all compiled code */
789 /* Flag to count trace execution */
792 /* Vector to disable selected optimizations */
795 /* Table to track the overall and trace statistics of hot methods */
796 HashTable* methodStatsTable;
798 /* Filter method compilation blacklist with call-graph information */
801 /* New translation chain has been set up */
802 volatile bool hasNewChain;
804 #if defined(WITH_SELF_VERIFICATION)
805 /* Spin when error is detected, volatile so GDB can reset it */
806 volatile bool selfVerificationSpin;
809 /* Framework or stand-alone? */
810 bool runningInAndroidFramework;
812 /* Framework callback happened? */
813 bool alreadyEnabledViaFramework;
815 /* Framework requests to disable the JIT for good */
818 #if defined(SIGNATURE_BREAKPOINT)
819 /* Signature breakpoint */
820 u4 signatureBreakpointSize; // # of words
821 u4 *signatureBreakpoint; // Signature content
824 #if defined(WITH_JIT_TUNING)
825 /* Performance tuning counters */
826 int addrLookupsFound;
827 int addrLookupsNotFound;
828 int noChainExit[kNoChainExitLast];
831 int invokeMonomorphic;
832 int invokePolymorphic;
841 int codeCachePatches;
844 /* Place arrays at the end to ease the display in gdb sessions */
846 /* Work order queue for compilations */
847 CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
849 /* Work order queue for predicted chain patching */
850 ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
853 extern struct DvmJitGlobals gDvmJit;
855 #if defined(WITH_JIT_TUNING)
856 extern int gDvmICHitCount;
861 #endif /*_DALVIK_GLOBALS*/