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;
447 /* Opaque pointer representing the heap. */
451 * Pre-allocated throwables.
453 Object* outOfMemoryObj;
454 Object* internalErrorObj;
455 Object* noClassDefFoundErrorObj;
457 /* Monitor list, so we can free them */
458 /*volatile*/ Monitor* monitorList;
460 /* Monitor for Thread.sleep() implementation */
461 Monitor* threadSleepMon;
463 /* set when we create a second heap inside the zygote */
464 bool newZygoteHeapAllocated;
469 pthread_key_t pthreadKeySelf; /* Thread*, for dvmThreadSelf */
472 * JNI allows you to have multiple VMs, but we limit ourselves to 1,
473 * so "vmList" is really just a pointer to the one and only VM.
478 * Cache results of "A instanceof B".
480 AtomicCache* instanceofCache;
482 /* instruction width table, used for optimization and verification */
483 InstructionWidth* instrWidth;
484 /* instruction flags table, used for verification */
485 InstructionFlags* instrFlags;
486 /* instruction format table, used for verification */
487 InstructionFormat* instrFormat;
489 /* inline substitution table, used during optimization */
490 InlineSub* inlineSubs;
493 * Bootstrap class loader linear allocator.
495 LinearAllocHdr* pBootLoaderAlloc;
499 * Heap worker thread.
501 bool heapWorkerInitialized;
502 bool heapWorkerReady;
504 pthread_t heapWorkerHandle;
505 pthread_mutex_t heapWorkerLock;
506 pthread_cond_t heapWorkerCond;
507 pthread_cond_t heapWorkerIdleCond;
508 pthread_mutex_t heapWorkerListLock;
511 * Compute some stats on loaded classes.
513 int numLoadedClasses;
514 int numDeclaredMethods;
515 int numDeclaredInstFields;
516 int numDeclaredStaticFields;
518 /* when using a native debugger, set this to suppress watchdog timers */
519 bool nativeDebuggerActive;
522 * JDWP debugger support.
524 * Note "debuggerActive" is accessed from mterp, so its storage size and
525 * meaning must not be changed without updating the assembly sources.
527 bool debuggerConnected; /* debugger or DDMS is connected */
528 u1 debuggerActive; /* debugger is making requests */
529 JdwpState* jdwpState;
532 * Registry of objects known to the debugger.
534 HashTable* dbgRegistry;
537 * Debugger breakpoint table.
539 BreakpointSet* breakpointSet;
542 * Single-step control struct. We currently only allow one thread to
543 * be single-stepping at a time, which is all that really makes sense,
544 * but it's possible we may need to expand this to be per-thread.
546 StepControl stepControl;
549 * DDM features embedded in the VM.
551 bool ddmThreadNotification;
554 * Zygote (partially-started process) support
559 * Used for tracking allocations that we report to DDMS. When the feature
560 * is enabled (through a DDMS request) the "allocRecords" pointer becomes
563 pthread_mutex_t allocTrackerLock;
564 AllocRecord* allocRecords;
565 int allocRecordHead; /* most-recently-added entry */
566 int allocRecordCount; /* #of valid entries */
568 #ifdef WITH_ALLOC_LIMITS
569 /* set on first use of an alloc limit, never cleared */
570 bool checkAllocLimits;
571 /* allocation limit, for setGlobalAllocationLimit() regression testing */
575 #ifdef WITH_DEADLOCK_PREDICTION
576 /* global lock on history tree accesses */
577 pthread_mutex_t deadlockHistoryLock;
579 enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
584 * When a profiler is enabled, this is incremented. Distinct profilers
585 * include "dmtrace" method tracing, emulator method tracing, and
586 * possibly instruction counting.
588 * The purpose of this is to have a single value that the interpreter
589 * can check to see if any profiling activity is enabled.
591 volatile int activeProfilers;
594 * State for method-trace profiling.
596 MethodTraceState methodTrace;
599 * State for emulator tracing.
601 void* emulatorTracePage;
602 int emulatorTraceEnableCount;
605 * Global state for memory allocation profiling.
607 AllocProfState allocProf;
610 * Pointers to the original methods for things that have been inlined.
611 * This makes it easy for us to output method entry/exit records for
612 * the method calls we're not actually making.
614 Method** inlinedMethods;
617 * Dalvik instruction counts (256 entries).
619 int* executedInstrCounts;
620 bool instructionCountEnableCount;
624 * Signal catcher thread (for SIGQUIT).
626 pthread_t signalCatcherHandle;
627 bool haltSignalCatcher;
630 * Stdout/stderr conversion thread.
632 bool haltStdioConverter;
633 bool stdioConverterReady;
634 pthread_t stdioConverterHandle;
635 pthread_mutex_t stdioConverterLock;
636 pthread_cond_t stdioConverterCond;
639 * pid of the system_server process. We track it so that when system server
640 * crashes the Zygote process will be killed and restarted.
642 pid_t systemServerPid;
644 int kernelGroupScheduling;
646 //#define COUNT_PRECISE_METHODS
647 #ifdef COUNT_PRECISE_METHODS
648 PointerSet* preciseMethods;
651 /* some RegisterMap statistics, useful during development */
652 void* registerMapStats;
655 extern struct DvmGlobals gDvm;
657 #if defined(WITH_JIT)
660 * Exiting the compiled code w/o chaining will incur overhead to look up the
661 * target in the code cache which is extra work only when JIT is enabled. So
662 * we want to monitor it closely to make sure we don't have performance bugs.
664 typedef enum NoChainExits {
665 kInlineCacheMiss = 0,
666 kCallsiteInterpreted,
673 * JIT-specific global state
675 struct DvmJitGlobals {
677 * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
678 * chain fields within the JIT hash table. Note carefully the access
680 * Only writes are guarded, and the guarded fields must be updated in a
681 * specific order using atomic operations. Further, once a field is
682 * written it cannot be changed without halting all threads.
684 * The write order is:
687 * 3) chain [if necessary]
689 * This mutex also guards both read and write of curJitTableEntries.
691 pthread_mutex_t tableLock;
693 /* The JIT hash table. Note that for access speed, copies of this pointer
694 * are stored in each thread. */
695 struct JitEntry *pJitEntryTable;
697 /* Array of profile threshold counters */
698 unsigned char *pProfTable;
700 /* Copy of pProfTable used for temporarily disabling the Jit */
701 unsigned char *pProfTableCopy;
703 /* Size of JIT hash table in entries. Must be a power of 2 */
704 unsigned int jitTableSize;
706 /* Mask used in hash function for JitTable. Should be jitTableSize-1 */
707 unsigned int jitTableMask;
709 /* How many entries in the JitEntryTable are in use */
710 unsigned int jitTableEntriesUsed;
712 /* Bytes allocated for the code cache */
713 unsigned int codeCacheSize;
715 /* Trigger for trace selection */
716 unsigned short threshold;
718 /* JIT Compiler Control */
719 bool haltCompilerThread;
721 pthread_t compilerHandle;
722 pthread_mutex_t compilerLock;
723 pthread_mutex_t compilerICPatchLock;
724 pthread_cond_t compilerQueueActivity;
725 pthread_cond_t compilerQueueEmpty;
726 volatile int compilerQueueLength;
727 int compilerHighWater;
728 int compilerWorkEnqueueIndex;
729 int compilerWorkDequeueIndex;
730 int compilerICPatchIndex;
732 /* JIT internal stats */
733 int compilerMaxQueued;
734 int translationChains;
736 /* Compiled code cache */
739 /* Bytes used by the code templates */
740 unsigned int templateSize;
742 /* Bytes already used in the code cache */
743 unsigned int codeCacheByteUsed;
745 /* Number of installed compilations in the cache */
746 unsigned int numCompilations;
748 /* Flag to indicate that the code cache is full */
752 unsigned int pageSizeMask;
754 /* Lock to change the protection type of the code cache */
755 pthread_mutex_t codeCacheProtectionLock;
757 /* Number of times that the code cache has been reset */
758 int numCodeCacheReset;
760 /* Number of times that the code cache reset request has been delayed */
761 int numCodeCacheResetDelayed;
763 /* true/false: compile/reject opcodes specified in the -Xjitop list */
764 bool includeSelectedOp;
766 /* true/false: compile/reject methods specified in the -Xjitmethod list */
767 bool includeSelectedMethod;
769 /* Disable JIT for selected opcodes - one bit for each opcode */
772 /* Disable JIT for selected methods */
773 HashTable *methodTable;
775 /* Flag to dump all compiled code */
778 /* Flag to count trace execution */
781 /* Vector to disable selected optimizations */
784 /* Table to track the overall and trace statistics of hot methods */
785 HashTable* methodStatsTable;
787 /* Filter method compilation blacklist with call-graph information */
790 /* New translation chain has been set up */
791 volatile bool hasNewChain;
793 #if defined(WITH_SELF_VERIFICATION)
794 /* Spin when error is detected, volatile so GDB can reset it */
795 volatile bool selfVerificationSpin;
798 /* Framework or stand-alone? */
799 bool runningInAndroidFramework;
801 /* Framework callback happened? */
802 bool alreadyEnabledViaFramework;
804 /* Framework requests to disable the JIT for good */
807 #if defined(SIGNATURE_BREAKPOINT)
808 /* Signature breakpoint */
809 u4 signatureBreakpointSize; // # of words
810 u4 *signatureBreakpoint; // Signature content
813 #if defined(WITH_JIT_TUNING)
814 /* Performance tuning counters */
815 int addrLookupsFound;
816 int addrLookupsNotFound;
817 int noChainExit[kNoChainExitLast];
820 int invokeMonomorphic;
821 int invokePolymorphic;
830 int codeCachePatches;
833 /* Place arrays at the end to ease the display in gdb sessions */
835 /* Work order queue for compilations */
836 CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
838 /* Work order queue for predicted chain patching */
839 ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
842 extern struct DvmJitGlobals gDvmJit;
844 #if defined(WITH_JIT_TUNING)
845 extern int gDvmICHitCount;
850 #endif /*_DALVIK_GLOBALS*/