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?
94 /* use wall clock as method profiler clock source? */
95 bool profilerWallClock;
98 * Lock profiling threshold value in milliseconds. Acquires that
99 * exceed threshold are logged. Acquires within the threshold are
100 * logged with a probability of $\frac{time}{threshold}$ . If the
101 * threshold is unset no additional logging occurs.
103 u4 lockProfThreshold;
105 int (*vfprintfHook)(FILE*, const char*, va_list);
106 void (*exitHook)(int);
107 void (*abortHook)(void);
108 bool (*isSensitiveThreadHook)(void);
110 int jniGrefLimit; // 0 means no limit
114 bool verifyDexChecksum;
115 char* stackTraceFile; // for SIGQUIT-inspired output
119 DexOptimizerMode dexOptMode;
120 DexClassVerifyMode classVerifyMode;
122 bool monitorVerification;
132 bool generateRegisterMaps;
133 bool concurrentMarkSweep;
134 bool verifyCardTable;
136 int assertionCtrlCount;
137 AssertionControl* assertionCtrl;
139 ExecutionMode executionMode;
142 * VM init management.
145 int initExceptionCount;
149 * java.lang.System properties set from the command line.
156 * Where the VM goes to find system classes.
158 ClassPathEntry* bootClassPath;
159 /* used by the DEX optimizer to load classes from an unfinished DEX */
160 DvmDex* bootClassPathOptExtra;
161 bool optimizingBootstrapClass;
164 * Loaded classes, hashed by class name. Each entry is a ClassObject*,
165 * allocated in GC space.
167 HashTable* loadedClasses;
170 * Value for the next class serial number to be assigned. This is
171 * incremented as we load classes. Failed loads and races may result
172 * in some numbers being skipped, and the serial number is not
173 * guaranteed to start at 1, so the current value should not be used
174 * as a count of loaded classes.
176 volatile int classSerialNumber;
179 * Classes with a low classSerialNumber are probably in the zygote, and
180 * their InitiatingLoaderList is not used, to promote sharing. The list is
183 InitiatingLoaderList* initiatingLoaderList;
189 /* A mutex that guards access to the interned string tables. */
190 pthread_mutex_t internLock;
192 /* Hash table of strings interned by the user. */
193 HashTable* internedStrings;
195 /* Hash table of strings interned by the class loader. */
196 HashTable* literalStrings;
199 * Quick lookups for popular classes used internally.
201 ClassObject* classJavaLangClass;
202 ClassObject* classJavaLangClassArray;
203 ClassObject* classJavaLangError;
204 ClassObject* classJavaLangObject;
205 ClassObject* classJavaLangObjectArray;
206 ClassObject* classJavaLangRuntimeException;
207 ClassObject* classJavaLangString;
208 ClassObject* classJavaLangThread;
209 ClassObject* classJavaLangVMThread;
210 ClassObject* classJavaLangThreadGroup;
211 ClassObject* classJavaLangThrowable;
212 ClassObject* classJavaLangStackOverflowError;
213 ClassObject* classJavaLangStackTraceElement;
214 ClassObject* classJavaLangStackTraceElementArray;
215 ClassObject* classJavaLangAnnotationAnnotationArray;
216 ClassObject* classJavaLangAnnotationAnnotationArrayArray;
217 ClassObject* classJavaLangReflectAccessibleObject;
218 ClassObject* classJavaLangReflectConstructor;
219 ClassObject* classJavaLangReflectConstructorArray;
220 ClassObject* classJavaLangReflectField;
221 ClassObject* classJavaLangReflectFieldArray;
222 ClassObject* classJavaLangReflectMethod;
223 ClassObject* classJavaLangReflectMethodArray;
224 ClassObject* classJavaLangReflectProxy;
225 ClassObject* classJavaLangExceptionInInitializerError;
226 ClassObject* classJavaLangRefPhantomReference;
227 ClassObject* classJavaLangRefReference;
228 ClassObject* classJavaNioReadWriteDirectByteBuffer;
229 ClassObject* classJavaSecurityAccessController;
230 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
231 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
232 ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
234 /* synthetic classes for arrays of primitives */
235 ClassObject* classArrayBoolean;
236 ClassObject* classArrayChar;
237 ClassObject* classArrayFloat;
238 ClassObject* classArrayDouble;
239 ClassObject* classArrayByte;
240 ClassObject* classArrayShort;
241 ClassObject* classArrayInt;
242 ClassObject* classArrayLong;
244 /* method offsets - Object */
245 int voffJavaLangObject_equals;
246 int voffJavaLangObject_hashCode;
247 int voffJavaLangObject_toString;
248 int voffJavaLangObject_finalize;
250 /* field offsets - Class */
251 int offJavaLangClass_pd;
253 /* field offsets - String */
254 int javaLangStringReady; /* 0=not init, 1=ready, -1=initing */
255 int offJavaLangString_value;
256 int offJavaLangString_count;
257 int offJavaLangString_offset;
258 int offJavaLangString_hashCode;
260 /* field offsets - Thread */
261 int offJavaLangThread_vmThread;
262 int offJavaLangThread_group;
263 int offJavaLangThread_daemon;
264 int offJavaLangThread_name;
265 int offJavaLangThread_priority;
267 /* method offsets - Thread */
268 int voffJavaLangThread_run;
270 /* field offsets - VMThread */
271 int offJavaLangVMThread_thread;
272 int offJavaLangVMThread_vmData;
274 /* method offsets - ThreadGroup */
275 int voffJavaLangThreadGroup_removeThread;
277 /* field offsets - Throwable */
278 int offJavaLangThrowable_stackState;
279 int offJavaLangThrowable_cause;
281 /* method offsets - ClassLoader */
282 int voffJavaLangClassLoader_loadClass;
284 /* field offsets - java.lang.reflect.* */
285 int offJavaLangReflectAccessibleObject_flag;
286 int offJavaLangReflectConstructor_slot;
287 int offJavaLangReflectConstructor_declClass;
288 int offJavaLangReflectField_slot;
289 int offJavaLangReflectField_declClass;
290 int offJavaLangReflectMethod_slot;
291 int offJavaLangReflectMethod_declClass;
293 /* field offsets - java.lang.ref.Reference */
294 int offJavaLangRefReference_referent;
295 int offJavaLangRefReference_queue;
296 int offJavaLangRefReference_queueNext;
297 int offJavaLangRefReference_pendingNext;
299 /* method pointers - java.lang.ref.Reference */
300 Method* methJavaLangRefReference_enqueueInternal;
302 /* method pointers - java.security.AccessController */
303 volatile int javaSecurityAccessControllerReady;
304 Method* methJavaSecurityAccessController_doPrivileged[4];
306 /* constructor method pointers; no vtable involved, so use Method* */
307 Method* methJavaLangStackTraceElement_init;
308 Method* methJavaLangExceptionInInitializerError_init;
309 Method* methJavaLangRefPhantomReference_init;
310 Method* methJavaLangReflectConstructor_init;
311 Method* methJavaLangReflectField_init;
312 Method* methJavaLangReflectMethod_init;
313 Method* methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
315 /* static method pointers - android.lang.annotation.* */
317 methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
319 /* direct method pointers - java.lang.reflect.Proxy */
320 Method* methJavaLangReflectProxy_constructorPrototype;
322 /* field offsets - java.lang.reflect.Proxy */
323 int offJavaLangReflectProxy_h;
325 /* fake native entry point method */
326 Method* methFakeNativeEntry;
328 /* assorted direct buffer helpers */
329 Method* methJavaNioReadWriteDirectByteBuffer_init;
330 int offJavaNioBuffer_capacity;
331 int offJavaNioBuffer_effectiveDirectAddress;
334 * VM-synthesized primitive classes, for arrays.
336 ClassObject* volatile primitiveClass[PRIM_MAX];
339 * Thread list. This always has at least one element in it (main),
340 * and main is always the first entry.
342 * The threadListLock is used for several things, including the thread
343 * start condition variable. Generally speaking, you must hold the
344 * threadListLock when:
345 * - adding/removing items from the list
346 * - waiting on or signaling threadStartCond
347 * - examining the Thread struct for another thread (this is to avoid
348 * one thread freeing the Thread struct while another thread is
352 pthread_mutex_t threadListLock;
354 pthread_cond_t threadStartCond;
357 * The thread code grabs this before suspending all threads. There
358 * are a few things that can cause a "suspend all":
359 * (1) the GC is starting;
360 * (2) the debugger has sent a "suspend all" request;
361 * (3) a thread has hit a breakpoint or exception that the debugger
362 * has marked as a "suspend all" event;
363 * (4) the SignalCatcher caught a signal that requires suspension.
364 * (5) (if implemented) the JIT needs to perform a heavyweight
365 * rearrangement of the translation cache or JitTable.
367 * Because we use "safe point" self-suspension, it is never safe to
368 * do a blocking "lock" call on this mutex -- if it has been acquired,
369 * somebody is probably trying to put you to sleep. The leading '_' is
370 * intended as a reminder that this lock is special.
372 pthread_mutex_t _threadSuspendLock;
375 * Guards Thread->suspendCount for all threads, and provides the lock
376 * for the condition variable that all suspended threads sleep on
377 * (threadSuspendCountCond).
379 * This has to be separate from threadListLock because of the way
380 * threads put themselves to sleep.
382 pthread_mutex_t threadSuspendCountLock;
385 * Suspended threads sleep on this. They should sleep on the condition
386 * variable until their "suspend count" is zero.
388 * Paired with "threadSuspendCountLock".
390 pthread_cond_t threadSuspendCountCond;
393 * Sum of all threads' suspendCount fields. The JIT needs to know if any
394 * thread is suspended. Guarded by threadSuspendCountLock.
396 int sumThreadSuspendCount;
399 * MUTEX ORDERING: when locking multiple mutexes, always grab them in
400 * this order to avoid deadlock:
402 * (1) _threadSuspendLock (use lockThreadSuspend())
403 * (2) threadListLock (use dvmLockThreadList())
404 * (3) threadSuspendCountLock (use lockThreadSuspendCount())
409 * Thread ID bitmap. We want threads to have small integer IDs so
410 * we can use them in "thin locks".
412 BitVector* threadIdMap;
415 * Manage exit conditions. The VM exits when all non-daemon threads
416 * have exited. If the main thread returns early, we need to sleep
417 * on a condition variable.
419 int nonDaemonThreadCount; /* must hold threadListLock to access */
420 //pthread_mutex_t vmExitLock;
421 pthread_cond_t vmExitCond;
424 * The set of DEX files loaded by custom class loaders.
426 HashTable* userDexFiles;
429 * JNI global reference table.
431 #ifdef USE_INDIRECT_REF
432 IndirectRefTable jniGlobalRefTable;
434 ReferenceTable jniGlobalRefTable;
436 pthread_mutex_t jniGlobalRefLock;
437 int jniGlobalRefHiMark;
438 int jniGlobalRefLoMark;
441 * JNI pinned object table (used for primitive arrays).
443 ReferenceTable jniPinRefTable;
444 pthread_mutex_t jniPinRefLock;
447 * Native shared library table.
449 HashTable* nativeLibs;
452 * GC heap lock. Functions like gcMalloc() acquire this before making
453 * any changes to the heap. It is held throughout garbage collection.
455 pthread_mutex_t gcHeapLock;
458 * Condition variable to queue threads waiting to retry an
459 * allocation. Signaled after a concurrent GC is completed.
461 pthread_cond_t gcHeapCond;
463 /* Opaque pointer representing the heap. */
466 /* The card table base, modified as needed for marking cards. */
467 u1* biasedCardTableBase;
470 * Pre-allocated throwables.
472 Object* outOfMemoryObj;
473 Object* internalErrorObj;
474 Object* noClassDefFoundErrorObj;
476 /* Monitor list, so we can free them */
477 /*volatile*/ Monitor* monitorList;
479 /* Monitor for Thread.sleep() implementation */
480 Monitor* threadSleepMon;
482 /* set when we create a second heap inside the zygote */
483 bool newZygoteHeapAllocated;
488 pthread_key_t pthreadKeySelf; /* Thread*, for dvmThreadSelf */
491 * JNI allows you to have multiple VMs, but we limit ourselves to 1,
492 * so "vmList" is really just a pointer to the one and only VM.
497 * Cache results of "A instanceof B".
499 AtomicCache* instanceofCache;
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_DEADLOCK_PREDICTION
581 /* global lock on history tree accesses */
582 pthread_mutex_t deadlockHistoryLock;
584 enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
588 * When a profiler is enabled, this is incremented. Distinct profilers
589 * include "dmtrace" method tracing, emulator method tracing, and
590 * possibly instruction counting.
592 * The purpose of this is to have a single value that the interpreter
593 * can check to see if any profiling activity is enabled.
595 volatile int activeProfilers;
598 * State for method-trace profiling.
600 MethodTraceState methodTrace;
603 * State for emulator tracing.
605 void* emulatorTracePage;
606 int emulatorTraceEnableCount;
609 * Global state for memory allocation profiling.
611 AllocProfState allocProf;
614 * Pointers to the original methods for things that have been inlined.
615 * This makes it easy for us to output method entry/exit records for
616 * the method calls we're not actually making. (Used by method
619 Method** inlinedMethods;
622 * Dalvik instruction counts (kNumPackedOpcodes entries).
624 int* executedInstrCounts;
625 int instructionCountEnableCount;
628 * Signal catcher thread (for SIGQUIT).
630 pthread_t signalCatcherHandle;
631 bool haltSignalCatcher;
634 * Stdout/stderr conversion thread.
636 bool haltStdioConverter;
637 bool stdioConverterReady;
638 pthread_t stdioConverterHandle;
639 pthread_mutex_t stdioConverterLock;
640 pthread_cond_t stdioConverterCond;
643 * pid of the system_server process. We track it so that when system server
644 * crashes the Zygote process will be killed and restarted.
646 pid_t systemServerPid;
648 int kernelGroupScheduling;
650 //#define COUNT_PRECISE_METHODS
651 #ifdef COUNT_PRECISE_METHODS
652 PointerSet* preciseMethods;
655 /* some RegisterMap statistics, useful during development */
656 void* registerMapStats;
658 #ifdef VERIFIER_STATS
659 VerifierStats verifierStats;
663 extern struct DvmGlobals gDvm;
665 #if defined(WITH_JIT)
668 * Exiting the compiled code w/o chaining will incur overhead to look up the
669 * target in the code cache which is extra work only when JIT is enabled. So
670 * we want to monitor it closely to make sure we don't have performance bugs.
672 typedef enum NoChainExits {
673 kInlineCacheMiss = 0,
674 kCallsiteInterpreted,
681 * JIT-specific global state
683 struct DvmJitGlobals {
685 * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
686 * chain fields within the JIT hash table. Note carefully the access
688 * Only writes are guarded, and the guarded fields must be updated in a
689 * specific order using atomic operations. Further, once a field is
690 * written it cannot be changed without halting all threads.
692 * The write order is:
695 * 3) chain [if necessary]
697 * This mutex also guards both read and write of curJitTableEntries.
699 pthread_mutex_t tableLock;
701 /* The JIT hash table. Note that for access speed, copies of this pointer
702 * are stored in each thread. */
703 struct JitEntry *pJitEntryTable;
705 /* Array of profile threshold counters */
706 unsigned char *pProfTable;
708 /* Copy of pProfTable used for temporarily disabling the Jit */
709 unsigned char *pProfTableCopy;
711 /* Size of JIT hash table in entries. Must be a power of 2 */
712 unsigned int jitTableSize;
714 /* Mask used in hash function for JitTable. Should be jitTableSize-1 */
715 unsigned int jitTableMask;
717 /* How many entries in the JitEntryTable are in use */
718 unsigned int jitTableEntriesUsed;
720 /* Bytes allocated for the code cache */
721 unsigned int codeCacheSize;
723 /* Trigger for trace selection */
724 unsigned short threshold;
726 /* JIT Compiler Control */
727 bool haltCompilerThread;
729 pthread_t compilerHandle;
730 pthread_mutex_t compilerLock;
731 pthread_mutex_t compilerICPatchLock;
732 pthread_cond_t compilerQueueActivity;
733 pthread_cond_t compilerQueueEmpty;
734 volatile int compilerQueueLength;
735 int compilerHighWater;
736 int compilerWorkEnqueueIndex;
737 int compilerWorkDequeueIndex;
738 int compilerICPatchIndex;
740 /* JIT internal stats */
741 int compilerMaxQueued;
742 int translationChains;
744 /* Compiled code cache */
747 /* Bytes used by the code templates */
748 unsigned int templateSize;
750 /* Bytes already used in the code cache */
751 unsigned int codeCacheByteUsed;
753 /* Number of installed compilations in the cache */
754 unsigned int numCompilations;
756 /* Flag to indicate that the code cache is full */
760 unsigned int pageSizeMask;
762 /* Lock to change the protection type of the code cache */
763 pthread_mutex_t codeCacheProtectionLock;
765 /* Number of times that the code cache has been reset */
766 int numCodeCacheReset;
768 /* Number of times that the code cache reset request has been delayed */
769 int numCodeCacheResetDelayed;
771 /* true/false: compile/reject opcodes specified in the -Xjitop list */
772 bool includeSelectedOp;
774 /* true/false: compile/reject methods specified in the -Xjitmethod list */
775 bool includeSelectedMethod;
777 /* Disable JIT for selected opcodes - one bit for each opcode */
780 /* Disable JIT for selected methods */
781 HashTable *methodTable;
783 /* Flag to dump all compiled code */
786 /* Flag to count trace execution */
789 /* Vector to disable selected optimizations */
792 /* Table to track the overall and trace statistics of hot methods */
793 HashTable* methodStatsTable;
795 /* Filter method compilation blacklist with call-graph information */
798 /* New translation chain has been set up */
799 volatile bool hasNewChain;
801 #if defined(WITH_SELF_VERIFICATION)
802 /* Spin when error is detected, volatile so GDB can reset it */
803 volatile bool selfVerificationSpin;
806 /* Framework or stand-alone? */
807 bool runningInAndroidFramework;
809 /* Framework callback happened? */
810 bool alreadyEnabledViaFramework;
812 /* Framework requests to disable the JIT for good */
815 #if defined(SIGNATURE_BREAKPOINT)
816 /* Signature breakpoint */
817 u4 signatureBreakpointSize; // # of words
818 u4 *signatureBreakpoint; // Signature content
821 #if defined(WITH_JIT_TUNING)
822 /* Performance tuning counters */
823 int addrLookupsFound;
824 int addrLookupsNotFound;
825 int noChainExit[kNoChainExitLast];
828 int invokeMonomorphic;
829 int invokePolymorphic;
831 int invokeMonoGetterInlined;
832 int invokeMonoSetterInlined;
833 int invokePolyGetterInlined;
834 int invokePolySetterInlined;
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*/