Globals.h revision 2ff04ab635eeba79c2dad82850c34188abcdfe62
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17/*
18 * Variables with library scope.
19 *
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.
24 *
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.
28 */
29#ifndef _DALVIK_GLOBALS
30#define _DALVIK_GLOBALS
31
32#include <cutils/array.h>
33#include <stdarg.h>
34#include <pthread.h>
35
36#define MAX_BREAKPOINTS 20      /* used for a debugger optimization */
37
38/* private structures */
39typedef struct GcHeap GcHeap;
40typedef struct BreakpointSet BreakpointSet;
41typedef struct InlineSub InlineSub;
42
43/*
44 * One of these for each -ea/-da/-esa/-dsa on the command line.
45 */
46typedef struct AssertionControl {
47    char*   pkgOrClass;         /* package/class string, or NULL for esa/dsa */
48    int     pkgOrClassLen;      /* string length, for quick compare */
49    bool    enable;             /* enable or disable */
50    bool    isPackage;          /* string ended with "..."? */
51} AssertionControl;
52
53/*
54 * Execution mode, e.g. interpreter vs. JIT.
55 */
56typedef enum ExecutionMode {
57    kExecutionModeUnknown = 0,
58    kExecutionModeInterpPortable,
59    kExecutionModeInterpFast,
60#if defined(WITH_JIT)
61    kExecutionModeJit,
62#endif
63} ExecutionMode;
64
65/*
66 * Execution sub modes, e.g. debugging, profiling, etc.
67 * Treated as bit flags for fast access.  These values are used directly
68 * by assembly code in the mterp interpeter and may also be used by
69 * code generated by the JIT.  Take care when changing.
70 */
71typedef enum ExecutionSubModes {
72    kSubModeNormal         = 0x00,
73    kSubModeMethodTrace    = 0x01,
74    kSubModeEmulatorTrace  = 0x02,
75    kSubModeInstCounting   = 0x04,
76    kSubModeDebuggerActive = 0x08,
77    kSubModeSuspendRequest = 0x10,  /* Set if any suspend request active */
78} ExecutionSubModes;
79
80/*
81 * Register map generation mode.  Only applicable when generateRegisterMaps
82 * is enabled.  (The "disabled" state is not folded into this because
83 * there are callers like dexopt that want to enable/disable without
84 * specifying the configuration details.)
85 *
86 * "TypePrecise" is slower and requires additional storage for the register
87 * maps, but allows type-precise GC.  "LivePrecise" is even slower and
88 * requires additional heap during processing, but allows live-precise GC.
89 */
90typedef enum {
91    kRegisterMapModeUnknown = 0,
92    kRegisterMapModeTypePrecise,
93    kRegisterMapModeLivePrecise
94} RegisterMapMode;
95
96/*
97 * All fields are initialized to zero.
98 *
99 * Storage allocated here must be freed by a subsystem shutdown function or
100 * from within freeGlobals().
101 */
102struct DvmGlobals {
103    /*
104     * Some options from the command line or environment.
105     */
106    char*       bootClassPathStr;
107    char*       classPathStr;
108
109    size_t      heapStartingSize;
110    size_t      heapMaximumSize;
111    size_t      heapGrowthLimit;
112    size_t      stackSize;
113
114    bool        verboseGc;
115    bool        verboseJni;
116    bool        verboseClass;
117    bool        verboseShutdown;
118
119    bool        jdwpAllowed;        // debugging allowed for this process?
120    bool        jdwpConfigured;     // has debugging info been provided?
121    int         jdwpTransport;
122    bool        jdwpServer;
123    char*       jdwpHost;
124    int         jdwpPort;
125    bool        jdwpSuspend;
126
127    /* use wall clock as method profiler clock source? */
128    bool        profilerWallClock;
129
130    /*
131     * Lock profiling threshold value in milliseconds.  Acquires that
132     * exceed threshold are logged.  Acquires within the threshold are
133     * logged with a probability of $\frac{time}{threshold}$ .  If the
134     * threshold is unset no additional logging occurs.
135     */
136    u4          lockProfThreshold;
137
138    int         (*vfprintfHook)(FILE*, const char*, va_list);
139    void        (*exitHook)(int);
140    void        (*abortHook)(void);
141    bool        (*isSensitiveThreadHook)(void);
142
143    int         jniGrefLimit;       // 0 means no limit
144    char*       jniTrace;
145    bool        reduceSignals;
146    bool        noQuitHandler;
147    bool        verifyDexChecksum;
148    char*       stackTraceFile;     // for SIGQUIT-inspired output
149
150    bool        logStdio;
151
152    DexOptimizerMode    dexOptMode;
153    DexClassVerifyMode  classVerifyMode;
154
155    bool        generateRegisterMaps;
156    RegisterMapMode     registerMapMode;
157
158    bool        monitorVerification;
159
160    bool        dexOptForSmp;
161
162    /*
163     * GC option flags.
164     */
165    bool        preciseGc;
166    bool        preVerify;
167    bool        postVerify;
168    bool        concurrentMarkSweep;
169    bool        verifyCardTable;
170    bool        disableExplicitGc;
171
172    int         assertionCtrlCount;
173    AssertionControl*   assertionCtrl;
174
175    ExecutionMode   executionMode;
176
177    /*
178     * VM init management.
179     */
180    bool        initializing;
181    bool        optimizing;
182
183    /*
184     * java.lang.System properties set from the command line with -D.
185     * This is effectively a set, where later entries override earlier
186     * ones.
187     */
188    Array*      properties;
189
190    /*
191     * Where the VM goes to find system classes.
192     */
193    ClassPathEntry* bootClassPath;
194    /* used by the DEX optimizer to load classes from an unfinished DEX */
195    DvmDex*     bootClassPathOptExtra;
196    bool        optimizingBootstrapClass;
197
198    /*
199     * Loaded classes, hashed by class name.  Each entry is a ClassObject*,
200     * allocated in GC space.
201     */
202    HashTable*  loadedClasses;
203
204    /*
205     * Value for the next class serial number to be assigned.  This is
206     * incremented as we load classes.  Failed loads and races may result
207     * in some numbers being skipped, and the serial number is not
208     * guaranteed to start at 1, so the current value should not be used
209     * as a count of loaded classes.
210     */
211    volatile int classSerialNumber;
212
213    /*
214     * Classes with a low classSerialNumber are probably in the zygote, and
215     * their InitiatingLoaderList is not used, to promote sharing. The list is
216     * kept here instead.
217     */
218    InitiatingLoaderList* initiatingLoaderList;
219
220    /*
221     * Interned strings.
222     */
223
224    /* A mutex that guards access to the interned string tables. */
225    pthread_mutex_t internLock;
226
227    /* Hash table of strings interned by the user. */
228    HashTable*  internedStrings;
229
230    /* Hash table of strings interned by the class loader. */
231    HashTable*  literalStrings;
232
233    /*
234     * Quick lookups for popular classes used internally.
235     */
236    ClassObject* classJavaLangClass;
237    ClassObject* classJavaLangClassArray;
238    ClassObject* classJavaLangObject;
239    ClassObject* classJavaLangObjectArray;
240    ClassObject* classJavaLangString;
241    ClassObject* classJavaLangThread;
242    ClassObject* classJavaLangVMThread;
243    ClassObject* classJavaLangThreadGroup;
244    ClassObject* classJavaLangStackTraceElement;
245    ClassObject* classJavaLangStackTraceElementArray;
246    ClassObject* classJavaLangAnnotationAnnotationArray;
247    ClassObject* classJavaLangAnnotationAnnotationArrayArray;
248    ClassObject* classJavaLangReflectAccessibleObject;
249    ClassObject* classJavaLangReflectConstructor;
250    ClassObject* classJavaLangReflectConstructorArray;
251    ClassObject* classJavaLangReflectField;
252    ClassObject* classJavaLangReflectFieldArray;
253    ClassObject* classJavaLangReflectMethod;
254    ClassObject* classJavaLangReflectMethodArray;
255    ClassObject* classJavaLangReflectProxy;
256    ClassObject* classJavaLangRefPhantomReference;
257    ClassObject* classJavaLangRefReference;
258    ClassObject* classJavaNioReadWriteDirectByteBuffer;
259    ClassObject* classJavaSecurityAccessController;
260    ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
261    ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
262    ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
263
264    /*
265     * classes representing exception types. The names here don't include
266     * packages, just to keep the use sites a bit less verbose. All are
267     * in java.lang, except where noted.
268     */
269    ClassObject* exAbstractMethodError;
270    ClassObject* exArithmeticException;
271    ClassObject* exArrayIndexOutOfBoundsException;
272    ClassObject* exArrayStoreException;
273    ClassObject* exClassCastException;
274    ClassObject* exClassCircularityError;
275    ClassObject* exClassFormatError;
276    ClassObject* exClassNotFoundException;
277    ClassObject* exError;
278    ClassObject* exExceptionInInitializerError;
279    ClassObject* exFileNotFoundException; /* in java.io */
280    ClassObject* exIOException;           /* in java.io */
281    ClassObject* exIllegalAccessError;
282    ClassObject* exIllegalAccessException;
283    ClassObject* exIllegalArgumentException;
284    ClassObject* exIllegalMonitorStateException;
285    ClassObject* exIllegalStateException;
286    ClassObject* exIllegalThreadStateException;
287    ClassObject* exIncompatibleClassChangeError;
288    ClassObject* exInstantiationError;
289    ClassObject* exInstantiationException;
290    ClassObject* exInternalError;
291    ClassObject* exInterruptedException;
292    ClassObject* exLinkageError;
293    ClassObject* exNegativeArraySizeException;
294    ClassObject* exNoClassDefFoundError;
295    ClassObject* exNoSuchFieldError;
296    ClassObject* exNoSuchFieldException;
297    ClassObject* exNoSuchMethodError;
298    ClassObject* exNullPointerException;
299    ClassObject* exOutOfMemoryError;
300    ClassObject* exRuntimeException;
301    ClassObject* exStackOverflowError;
302    ClassObject* exStaleDexCacheError;    /* in dalvik.system */
303    ClassObject* exStringIndexOutOfBoundsException;
304    ClassObject* exThrowable;
305    ClassObject* exTypeNotPresentException;
306    ClassObject* exUnsatisfiedLinkError;
307    ClassObject* exUnsupportedOperationException;
308    ClassObject* exVerifyError;
309    ClassObject* exVirtualMachineError;
310
311    /* synthetic classes for arrays of primitives */
312    ClassObject* classArrayBoolean;
313    ClassObject* classArrayChar;
314    ClassObject* classArrayFloat;
315    ClassObject* classArrayDouble;
316    ClassObject* classArrayByte;
317    ClassObject* classArrayShort;
318    ClassObject* classArrayInt;
319    ClassObject* classArrayLong;
320
321    /* method offsets - Object */
322    int         voffJavaLangObject_equals;
323    int         voffJavaLangObject_hashCode;
324    int         voffJavaLangObject_toString;
325    int         voffJavaLangObject_finalize;
326
327    /* field offsets - Class */
328    int         offJavaLangClass_pd;
329
330    /* field offsets - String */
331    int         javaLangStringReady;    /* 0=not init, 1=ready, -1=initing */
332    int         offJavaLangString_value;
333    int         offJavaLangString_count;
334    int         offJavaLangString_offset;
335    int         offJavaLangString_hashCode;
336
337    /* field offsets - Thread */
338    int         offJavaLangThread_vmThread;
339    int         offJavaLangThread_group;
340    int         offJavaLangThread_daemon;
341    int         offJavaLangThread_name;
342    int         offJavaLangThread_priority;
343
344    /* method offsets - Thread */
345    int         voffJavaLangThread_run;
346
347    /* field offsets - VMThread */
348    int         offJavaLangVMThread_thread;
349    int         offJavaLangVMThread_vmData;
350
351    /* method offsets - ThreadGroup */
352    int         voffJavaLangThreadGroup_removeThread;
353
354    /* field offsets - Throwable */
355    int         offJavaLangThrowable_stackState;
356    int         offJavaLangThrowable_cause;
357
358    /* method offsets - ClassLoader */
359    int         voffJavaLangClassLoader_loadClass;
360
361    /* field offsets - java.lang.reflect.* */
362    int         offJavaLangReflectAccessibleObject_flag;
363    int         offJavaLangReflectConstructor_slot;
364    int         offJavaLangReflectConstructor_declClass;
365    int         offJavaLangReflectField_slot;
366    int         offJavaLangReflectField_declClass;
367    int         offJavaLangReflectMethod_slot;
368    int         offJavaLangReflectMethod_declClass;
369
370    /* field offsets - java.lang.ref.Reference */
371    int         offJavaLangRefReference_referent;
372    int         offJavaLangRefReference_queue;
373    int         offJavaLangRefReference_queueNext;
374    int         offJavaLangRefReference_pendingNext;
375
376    /* method pointers - java.lang.ref.Reference */
377    Method*     methJavaLangRefReference_enqueueInternal;
378
379    /* method pointers - java.security.AccessController */
380    volatile int javaSecurityAccessControllerReady;
381    Method*     methJavaSecurityAccessController_doPrivileged[4];
382
383    /* constructor method pointers; no vtable involved, so use Method* */
384    Method*     methJavaLangStackTraceElement_init;
385    Method*     methJavaLangRefPhantomReference_init;
386    Method*     methJavaLangReflectConstructor_init;
387    Method*     methJavaLangReflectField_init;
388    Method*     methJavaLangReflectMethod_init;
389    Method*     methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
390
391    /* static method pointers - android.lang.annotation.* */
392    Method*
393        methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
394
395    /* direct method pointers - java.lang.reflect.Proxy */
396    Method*     methJavaLangReflectProxy_constructorPrototype;
397
398    /* field offsets - java.lang.reflect.Proxy */
399    int         offJavaLangReflectProxy_h;
400
401    /* fake native entry point method */
402    Method*     methFakeNativeEntry;
403
404    /* assorted direct buffer helpers */
405    Method*     methJavaNioReadWriteDirectByteBuffer_init;
406    int         offJavaNioBuffer_capacity;
407    int         offJavaNioBuffer_effectiveDirectAddress;
408
409    /*
410     * VM-synthesized primitive classes, for arrays.
411     */
412    ClassObject* volatile primitiveClass[PRIM_MAX];
413
414    /*
415     * Thread list.  This always has at least one element in it (main),
416     * and main is always the first entry.
417     *
418     * The threadListLock is used for several things, including the thread
419     * start condition variable.  Generally speaking, you must hold the
420     * threadListLock when:
421     *  - adding/removing items from the list
422     *  - waiting on or signaling threadStartCond
423     *  - examining the Thread struct for another thread (this is to avoid
424     *    one thread freeing the Thread struct while another thread is
425     *    perusing it)
426     */
427    Thread*     threadList;
428    pthread_mutex_t threadListLock;
429
430    pthread_cond_t threadStartCond;
431
432    /*
433     * The thread code grabs this before suspending all threads.  There
434     * are a few things that can cause a "suspend all":
435     *  (1) the GC is starting;
436     *  (2) the debugger has sent a "suspend all" request;
437     *  (3) a thread has hit a breakpoint or exception that the debugger
438     *      has marked as a "suspend all" event;
439     *  (4) the SignalCatcher caught a signal that requires suspension.
440     *  (5) (if implemented) the JIT needs to perform a heavyweight
441     *      rearrangement of the translation cache or JitTable.
442     *
443     * Because we use "safe point" self-suspension, it is never safe to
444     * do a blocking "lock" call on this mutex -- if it has been acquired,
445     * somebody is probably trying to put you to sleep.  The leading '_' is
446     * intended as a reminder that this lock is special.
447     */
448    pthread_mutex_t _threadSuspendLock;
449
450    /*
451     * Guards Thread->suspendCount for all threads, and provides the lock
452     * for the condition variable that all suspended threads sleep on
453     * (threadSuspendCountCond).
454     *
455     * This has to be separate from threadListLock because of the way
456     * threads put themselves to sleep.
457     */
458    pthread_mutex_t threadSuspendCountLock;
459
460    /*
461     * Suspended threads sleep on this.  They should sleep on the condition
462     * variable until their "suspend count" is zero.
463     *
464     * Paired with "threadSuspendCountLock".
465     */
466    pthread_cond_t  threadSuspendCountCond;
467
468    /*
469     * Sum of all threads' suspendCount fields. Guarded by
470     * threadSuspendCountLock.
471     */
472    int  sumThreadSuspendCount;
473
474    /*
475     * MUTEX ORDERING: when locking multiple mutexes, always grab them in
476     * this order to avoid deadlock:
477     *
478     *  (1) _threadSuspendLock      (use lockThreadSuspend())
479     *  (2) threadListLock          (use dvmLockThreadList())
480     *  (3) threadSuspendCountLock  (use lockThreadSuspendCount())
481     */
482
483
484    /*
485     * Thread ID bitmap.  We want threads to have small integer IDs so
486     * we can use them in "thin locks".
487     */
488    BitVector*  threadIdMap;
489
490    /*
491     * Manage exit conditions.  The VM exits when all non-daemon threads
492     * have exited.  If the main thread returns early, we need to sleep
493     * on a condition variable.
494     */
495    int         nonDaemonThreadCount;   /* must hold threadListLock to access */
496    //pthread_mutex_t vmExitLock;
497    pthread_cond_t  vmExitCond;
498
499    /*
500     * The set of DEX files loaded by custom class loaders.
501     */
502    HashTable*  userDexFiles;
503
504    /*
505     * JNI global reference table.
506     */
507#ifdef USE_INDIRECT_REF
508    IndirectRefTable jniGlobalRefTable;
509    IndirectRefTable jniWeakGlobalRefTable;
510#else
511    ReferenceTable  jniGlobalRefTable;
512#endif
513    pthread_mutex_t jniGlobalRefLock;
514#ifdef USE_INDIRECT_REF
515    pthread_mutex_t jniWeakGlobalRefLock;
516#endif
517    int         jniGlobalRefHiMark;
518    int         jniGlobalRefLoMark;
519
520    /*
521     * JNI pinned object table (used for primitive arrays).
522     */
523    ReferenceTable  jniPinRefTable;
524    pthread_mutex_t jniPinRefLock;
525
526    /*
527     * Native shared library table.
528     */
529    HashTable*  nativeLibs;
530
531    /*
532     * GC heap lock.  Functions like gcMalloc() acquire this before making
533     * any changes to the heap.  It is held throughout garbage collection.
534     */
535    pthread_mutex_t gcHeapLock;
536
537    /*
538     * Condition variable to queue threads waiting to retry an
539     * allocation.  Signaled after a concurrent GC is completed.
540     */
541    pthread_cond_t gcHeapCond;
542
543    /* Opaque pointer representing the heap. */
544    GcHeap*     gcHeap;
545
546    /* The card table base, modified as needed for marking cards. */
547    u1*         biasedCardTableBase;
548
549    /*
550     * Pre-allocated throwables.
551     */
552    Object*     outOfMemoryObj;
553    Object*     internalErrorObj;
554    Object*     noClassDefFoundErrorObj;
555
556    /* Monitor list, so we can free them */
557    /*volatile*/ Monitor* monitorList;
558
559    /* Monitor for Thread.sleep() implementation */
560    Monitor*    threadSleepMon;
561
562    /* set when we create a second heap inside the zygote */
563    bool        newZygoteHeapAllocated;
564
565    /*
566     * TLS keys.
567     */
568    pthread_key_t pthreadKeySelf;       /* Thread*, for dvmThreadSelf */
569
570    /*
571     * JNI allows you to have multiple VMs, but we limit ourselves to 1,
572     * so "vmList" is really just a pointer to the one and only VM.
573     */
574    JavaVM*     vmList;
575
576    /*
577     * Cache results of "A instanceof B".
578     */
579    AtomicCache* instanceofCache;
580
581    /* inline substitution table, used during optimization */
582    InlineSub*          inlineSubs;
583
584    /*
585     * Bootstrap class loader linear allocator.
586     */
587    LinearAllocHdr* pBootLoaderAlloc;
588
589
590    /*
591     * Heap worker thread.
592     */
593    bool            heapWorkerInitialized;
594    bool            heapWorkerReady;
595    bool            haltHeapWorker;
596    pthread_t       heapWorkerHandle;
597    pthread_mutex_t heapWorkerLock;
598    pthread_cond_t  heapWorkerCond;
599    pthread_cond_t  heapWorkerIdleCond;
600    pthread_mutex_t heapWorkerListLock;
601
602    /*
603     * Compute some stats on loaded classes.
604     */
605    int         numLoadedClasses;
606    int         numDeclaredMethods;
607    int         numDeclaredInstFields;
608    int         numDeclaredStaticFields;
609
610    /* when using a native debugger, set this to suppress watchdog timers */
611    bool        nativeDebuggerActive;
612
613    /*
614     * JDWP debugger support.
615     */
616    bool        debuggerConnected;      /* debugger or DDMS is connected */
617    JdwpState*  jdwpState;
618
619    /*
620     * Registry of objects known to the debugger.
621     */
622    HashTable*  dbgRegistry;
623
624    /*
625     * Debugger breakpoint table.
626     */
627    BreakpointSet*  breakpointSet;
628
629    /*
630     * Single-step control struct.  We currently only allow one thread to
631     * be single-stepping at a time, which is all that really makes sense,
632     * but it's possible we may need to expand this to be per-thread.
633     */
634    StepControl stepControl;
635
636    /*
637     * DDM features embedded in the VM.
638     */
639    bool        ddmThreadNotification;
640
641    /*
642     * Zygote (partially-started process) support
643     */
644    bool        zygote;
645
646    /*
647     * Used for tracking allocations that we report to DDMS.  When the feature
648     * is enabled (through a DDMS request) the "allocRecords" pointer becomes
649     * non-NULL.
650     */
651    pthread_mutex_t allocTrackerLock;
652    AllocRecord*    allocRecords;
653    int             allocRecordHead;        /* most-recently-added entry */
654    int             allocRecordCount;       /* #of valid entries */
655
656    /*
657     * When normal control flow needs to be interrupted because
658     * of an attached debugger, profiler, thread stop request, etc.,
659     * a bit is set here.  We collapse all stop reasons into
660     * a single location for performance reasons.
661     */
662    volatile int interpBreak;
663
664    /*
665     * State for method-trace profiling.
666     */
667    MethodTraceState methodTrace;
668    Method*     methodTraceGcMethod;
669    Method*     methodTraceClassPrepMethod;
670
671    /*
672     * State for emulator tracing.
673     */
674    void*       emulatorTracePage;
675    int         emulatorTraceEnableCount;
676
677    /*
678     * Global state for memory allocation profiling.
679     */
680    AllocProfState allocProf;
681
682    /*
683     * Pointers to the original methods for things that have been inlined.
684     * This makes it easy for us to output method entry/exit records for
685     * the method calls we're not actually making.  (Used by method
686     * profiling.)
687     */
688    Method**    inlinedMethods;
689
690    /*
691     * Dalvik instruction counts (kNumPackedOpcodes entries).
692     */
693    int*        executedInstrCounts;
694    int         instructionCountEnableCount;
695
696    /*
697     * Signal catcher thread (for SIGQUIT).
698     */
699    pthread_t   signalCatcherHandle;
700    bool        haltSignalCatcher;
701
702    /*
703     * Stdout/stderr conversion thread.
704     */
705    bool            haltStdioConverter;
706    bool            stdioConverterReady;
707    pthread_t       stdioConverterHandle;
708    pthread_mutex_t stdioConverterLock;
709    pthread_cond_t  stdioConverterCond;
710
711    /*
712     * pid of the system_server process. We track it so that when system server
713     * crashes the Zygote process will be killed and restarted.
714     */
715    pid_t systemServerPid;
716
717    int kernelGroupScheduling;
718
719//#define COUNT_PRECISE_METHODS
720#ifdef COUNT_PRECISE_METHODS
721    PointerSet* preciseMethods;
722#endif
723
724    /* some RegisterMap statistics, useful during development */
725    void*       registerMapStats;
726
727#ifdef VERIFIER_STATS
728    VerifierStats verifierStats;
729#endif
730};
731
732extern struct DvmGlobals gDvm;
733
734#if defined(WITH_JIT)
735
736/* Trace profiling modes.  Ordering matters - off states before on states */
737typedef enum TraceProfilingModes {
738    kTraceProfilingDisabled = 0,      // Not profiling
739    kTraceProfilingPeriodicOff = 1,   // Periodic profiling, off phase
740    kTraceProfilingContinuous = 2,    // Always profiling
741    kTraceProfilingPeriodicOn = 3     // Periodic profiling, on phase
742} TraceProfilingModes;
743
744/*
745 * Exiting the compiled code w/o chaining will incur overhead to look up the
746 * target in the code cache which is extra work only when JIT is enabled. So
747 * we want to monitor it closely to make sure we don't have performance bugs.
748 */
749typedef enum NoChainExits {
750    kInlineCacheMiss = 0,
751    kCallsiteInterpreted,
752    kSwitchOverflow,
753    kHeavyweightMonitor,
754    kNoChainExitLast,
755} NoChainExits;
756
757/*
758 * JIT-specific global state
759 */
760struct DvmJitGlobals {
761    /*
762     * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
763     * chain fields within the JIT hash table.  Note carefully the access
764     * mechanism.
765     * Only writes are guarded, and the guarded fields must be updated in a
766     * specific order using atomic operations.  Further, once a field is
767     * written it cannot be changed without halting all threads.
768     *
769     * The write order is:
770     *    1) codeAddr
771     *    2) dPC
772     *    3) chain [if necessary]
773     *
774     * This mutex also guards both read and write of curJitTableEntries.
775     */
776    pthread_mutex_t tableLock;
777
778    /* The JIT hash table.  Note that for access speed, copies of this pointer
779     * are stored in each thread. */
780    struct JitEntry *pJitEntryTable;
781
782    /* Array of compilation trigger threshold counters */
783    unsigned char *pProfTable;
784
785    /* Trace profiling counters */
786    struct JitTraceProfCounters *pJitTraceProfCounters;
787
788    /* Copy of pProfTable used for temporarily disabling the Jit */
789    unsigned char *pProfTableCopy;
790
791    /* Size of JIT hash table in entries.  Must be a power of 2 */
792    unsigned int jitTableSize;
793
794    /* Mask used in hash function for JitTable.  Should be jitTableSize-1 */
795    unsigned int jitTableMask;
796
797    /* How many entries in the JitEntryTable are in use */
798    unsigned int jitTableEntriesUsed;
799
800    /* Bytes allocated for the code cache */
801    unsigned int codeCacheSize;
802
803    /* Trigger for trace selection */
804    unsigned short threshold;
805
806    /* JIT Compiler Control */
807    bool               haltCompilerThread;
808    bool               blockingMode;
809    bool               methodTraceSupport;
810    bool               genSuspendPoll;
811    pthread_t          compilerHandle;
812    pthread_mutex_t    compilerLock;
813    pthread_mutex_t    compilerICPatchLock;
814    pthread_cond_t     compilerQueueActivity;
815    pthread_cond_t     compilerQueueEmpty;
816    volatile int       compilerQueueLength;
817    int                compilerHighWater;
818    int                compilerWorkEnqueueIndex;
819    int                compilerWorkDequeueIndex;
820    int                compilerICPatchIndex;
821
822    /* JIT internal stats */
823    int                compilerMaxQueued;
824    int                translationChains;
825
826    /* Compiled code cache */
827    void* codeCache;
828
829    /* Translation cache version (protected by compilerLock */
830    int cacheVersion;
831
832    /* Bytes used by the code templates */
833    unsigned int templateSize;
834
835    /* Bytes already used in the code cache */
836    unsigned int codeCacheByteUsed;
837
838    /* Number of installed compilations in the cache */
839    unsigned int numCompilations;
840
841    /* Flag to indicate that the code cache is full */
842    bool codeCacheFull;
843
844    /* Page size  - 1 */
845    unsigned int pageSizeMask;
846
847    /* Lock to change the protection type of the code cache */
848    pthread_mutex_t    codeCacheProtectionLock;
849
850    /* Number of times that the code cache has been reset */
851    int numCodeCacheReset;
852
853    /* Number of times that the code cache reset request has been delayed */
854    int numCodeCacheResetDelayed;
855
856    /* true/false: compile/reject opcodes specified in the -Xjitop list */
857    bool includeSelectedOp;
858
859    /* true/false: compile/reject methods specified in the -Xjitmethod list */
860    bool includeSelectedMethod;
861
862    /* Disable JIT for selected opcodes - one bit for each opcode */
863    char opList[32];
864
865    /* Disable JIT for selected methods */
866    HashTable *methodTable;
867
868    /* Flag to dump all compiled code */
869    bool printMe;
870
871    /* Trace profiling mode */
872    TraceProfilingModes profileMode;
873
874    /* Periodic trace profiling countdown timer */
875    int profileCountdown;
876
877    /* Vector to disable selected optimizations */
878    int disableOpt;
879
880    /* Table to track the overall and trace statistics of hot methods */
881    HashTable*  methodStatsTable;
882
883    /* Filter method compilation blacklist with call-graph information */
884    bool checkCallGraph;
885
886    /* New translation chain has been set up */
887    volatile bool hasNewChain;
888
889#if defined(WITH_SELF_VERIFICATION)
890    /* Spin when error is detected, volatile so GDB can reset it */
891    volatile bool selfVerificationSpin;
892#endif
893
894    /* Framework or stand-alone? */
895    bool runningInAndroidFramework;
896
897    /* Framework callback happened? */
898    bool alreadyEnabledViaFramework;
899
900    /* Framework requests to disable the JIT for good */
901    bool disableJit;
902
903#if defined(SIGNATURE_BREAKPOINT)
904    /* Signature breakpoint */
905    u4 signatureBreakpointSize;         // # of words
906    u4 *signatureBreakpoint;            // Signature content
907#endif
908
909#if defined(WITH_JIT_TUNING)
910    /* Performance tuning counters */
911    int                addrLookupsFound;
912    int                addrLookupsNotFound;
913    int                noChainExit[kNoChainExitLast];
914    int                normalExit;
915    int                puntExit;
916    int                invokeMonomorphic;
917    int                invokePolymorphic;
918    int                invokeNative;
919    int                invokeMonoGetterInlined;
920    int                invokeMonoSetterInlined;
921    int                invokePolyGetterInlined;
922    int                invokePolySetterInlined;
923    int                returnOp;
924    int                icPatchInit;
925    int                icPatchLockFree;
926    int                icPatchQueued;
927    int                icPatchRejected;
928    int                icPatchDropped;
929    u8                 jitTime;
930    int                codeCachePatches;
931#endif
932
933    /* Place arrays at the end to ease the display in gdb sessions */
934
935    /* Work order queue for compilations */
936    CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
937
938    /* Work order queue for predicted chain patching */
939    ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
940};
941
942extern struct DvmJitGlobals gDvmJit;
943
944#if defined(WITH_JIT_TUNING)
945extern int gDvmICHitCount;
946#endif
947
948#endif
949
950#endif /*_DALVIK_GLOBALS*/
951