Home | History | Annotate | Download | only in vm
      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 <stdarg.h>
     33 #include <pthread.h>
     34 
     35 #define MAX_BREAKPOINTS 20      /* used for a debugger optimization */
     36 
     37 /* private structures */
     38 typedef struct GcHeap GcHeap;
     39 typedef struct BreakpointSet BreakpointSet;
     40 
     41 /*
     42  * One of these for each -ea/-da/-esa/-dsa on the command line.
     43  */
     44 typedef struct AssertionControl {
     45     char*   pkgOrClass;         /* package/class string, or NULL for esa/dsa */
     46     int     pkgOrClassLen;      /* string length, for quick compare */
     47     bool    enable;             /* enable or disable */
     48     bool    isPackage;          /* string ended with "..."? */
     49 } AssertionControl;
     50 
     51 /*
     52  * Execution mode, e.g. interpreter vs. JIT.
     53  */
     54 typedef enum ExecutionMode {
     55     kExecutionModeUnknown = 0,
     56     kExecutionModeInterpPortable,
     57     kExecutionModeInterpFast,
     58 #if defined(WITH_JIT)
     59     kExecutionModeJit,
     60 #endif
     61 } ExecutionMode;
     62 
     63 /*
     64  * All fields are initialized to zero.
     65  *
     66  * Storage allocated here must be freed by a subsystem shutdown function or
     67  * from within freeGlobals().
     68  */
     69 struct DvmGlobals {
     70     /*
     71      * Some options from the command line or environment.
     72      */
     73     char*       bootClassPathStr;
     74     char*       classPathStr;
     75 
     76     unsigned int    heapSizeStart;
     77     unsigned int    heapSizeMax;
     78     unsigned int    stackSize;
     79 
     80     bool        verboseGc;
     81     bool        verboseJni;
     82     bool        verboseClass;
     83     bool        verboseShutdown;
     84 
     85     bool        jdwpAllowed;        // debugging allowed for this process?
     86     bool        jdwpConfigured;     // has debugging info been provided?
     87     int         jdwpTransport;
     88     bool        jdwpServer;
     89     char*       jdwpHost;
     90     int         jdwpPort;
     91     bool        jdwpSuspend;
     92 
     93     /*
     94      * Lock profiling threshold value in milliseconds.  Acquires that
     95      * exceed threshold are logged.  Acquires within the threshold are
     96      * logged with a probability of $\frac{time}{threshold}$ .  If the
     97      * threshold is unset no additional logging occurs.
     98      */
     99     u4          lockProfThreshold;
    100 
    101     int         (*vfprintfHook)(FILE*, const char*, va_list);
    102     void        (*exitHook)(int);
    103     void        (*abortHook)(void);
    104 
    105     int         jniGrefLimit;       // 0 means no limit
    106     bool        reduceSignals;
    107     bool        noQuitHandler;
    108     bool        verifyDexChecksum;
    109     char*       stackTraceFile;     // for SIGQUIT-inspired output
    110 
    111     bool        logStdio;
    112 
    113     DexOptimizerMode    dexOptMode;
    114     DexClassVerifyMode  classVerifyMode;
    115     bool        preciseGc;
    116     bool        generateRegisterMaps;
    117 
    118     int         assertionCtrlCount;
    119     AssertionControl*   assertionCtrl;
    120 
    121     ExecutionMode   executionMode;
    122 
    123     /*
    124      * VM init management.
    125      */
    126     bool        initializing;
    127     int         initExceptionCount;
    128     bool        optimizing;
    129 
    130     /*
    131      * java.lang.System properties set from the command line.
    132      */
    133     int         numProps;
    134     int         maxProps;
    135     char**      propList;
    136 
    137     /*
    138      * Where the VM goes to find system classes.
    139      */
    140     ClassPathEntry* bootClassPath;
    141     /* used by the DEX optimizer to load classes from an unfinished DEX */
    142     DvmDex*     bootClassPathOptExtra;
    143     bool        optimizingBootstrapClass;
    144 
    145     /*
    146      * Loaded classes, hashed by class name.  Each entry is a ClassObject*,
    147      * allocated in GC space.
    148      */
    149     HashTable*  loadedClasses;
    150 
    151     /*
    152      * Value for the next class serial number to be assigned.  This is
    153      * incremented as we load classes.  Failed loads and races may result
    154      * in some numbers being skipped, and the serial number is not
    155      * guaranteed to start at 1, so the current value should not be used
    156      * as a count of loaded classes.
    157      */
    158     volatile int classSerialNumber;
    159 
    160     /*
    161      * Classes with a low classSerialNumber are probably in the zygote, and
    162      * their InitiatingLoaderList is not used, to promote sharing. The list is
    163      * kept here instead.
    164      */
    165     InitiatingLoaderList* initiatingLoaderList;
    166 
    167     /*
    168      * Interned strings.
    169      */
    170     HashTable*  internedStrings;
    171 
    172     /*
    173      * Quick lookups for popular classes used internally.
    174      */
    175     ClassObject* unlinkedJavaLangClass;    // see unlinkedJavaLangClassObject
    176     ClassObject* classJavaLangClass;
    177     ClassObject* classJavaLangClassArray;
    178     ClassObject* classJavaLangError;
    179     ClassObject* classJavaLangObject;
    180     ClassObject* classJavaLangObjectArray;
    181     ClassObject* classJavaLangRuntimeException;
    182     ClassObject* classJavaLangString;
    183     ClassObject* classJavaLangThread;
    184     ClassObject* classJavaLangVMThread;
    185     ClassObject* classJavaLangThreadGroup;
    186     ClassObject* classJavaLangThrowable;
    187     ClassObject* classJavaLangStackOverflowError;
    188     ClassObject* classJavaLangStackTraceElement;
    189     ClassObject* classJavaLangStackTraceElementArray;
    190     ClassObject* classJavaLangAnnotationAnnotationArray;
    191     ClassObject* classJavaLangAnnotationAnnotationArrayArray;
    192     ClassObject* classJavaLangReflectAccessibleObject;
    193     ClassObject* classJavaLangReflectConstructor;
    194     ClassObject* classJavaLangReflectConstructorArray;
    195     ClassObject* classJavaLangReflectField;
    196     ClassObject* classJavaLangReflectFieldArray;
    197     ClassObject* classJavaLangReflectMethod;
    198     ClassObject* classJavaLangReflectMethodArray;
    199     ClassObject* classJavaLangReflectProxy;
    200     ClassObject* classJavaLangExceptionInInitializerError;
    201     ClassObject* classJavaLangRefPhantomReference;
    202     ClassObject* classJavaLangRefReference;
    203     ClassObject* classJavaNioReadWriteDirectByteBuffer;
    204     ClassObject* classJavaSecurityAccessController;
    205     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
    206     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
    207     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
    208     ClassObject* classOrgApacheHarmonyNioInternalDirectBuffer;
    209     jclass      jclassOrgApacheHarmonyNioInternalDirectBuffer;
    210 
    211     /* synthetic classes for arrays of primitives */
    212     ClassObject* classArrayBoolean;
    213     ClassObject* classArrayChar;
    214     ClassObject* classArrayFloat;
    215     ClassObject* classArrayDouble;
    216     ClassObject* classArrayByte;
    217     ClassObject* classArrayShort;
    218     ClassObject* classArrayInt;
    219     ClassObject* classArrayLong;
    220 
    221     /* method offsets - Object */
    222     int         voffJavaLangObject_equals;
    223     int         voffJavaLangObject_hashCode;
    224     int         voffJavaLangObject_toString;
    225     int         voffJavaLangObject_finalize;
    226 
    227     /* field offsets - Class */
    228     int         offJavaLangClass_pd;
    229 
    230     /* field offsets - String */
    231     volatile int javaLangStringReady;   /* 0=not init, 1=ready, -1=initing */
    232     int         offJavaLangString_value;
    233     int         offJavaLangString_count;
    234     int         offJavaLangString_offset;
    235     int         offJavaLangString_hashCode;
    236 
    237     /* field offsets - Thread */
    238     int         offJavaLangThread_vmThread;
    239     int         offJavaLangThread_group;
    240     int         offJavaLangThread_daemon;
    241     int         offJavaLangThread_name;
    242     int         offJavaLangThread_priority;
    243 
    244     /* method offsets - Thread */
    245     int         voffJavaLangThread_run;
    246 
    247     /* field offsets - VMThread */
    248     int         offJavaLangVMThread_thread;
    249     int         offJavaLangVMThread_vmData;
    250 
    251     /* method offsets - ThreadGroup */
    252     int         voffJavaLangThreadGroup_removeThread;
    253 
    254     /* field offsets - Throwable */
    255     int         offJavaLangThrowable_stackState;
    256     int         offJavaLangThrowable_message;
    257     int         offJavaLangThrowable_cause;
    258 
    259     /* field offsets - java.lang.reflect.* */
    260     int         offJavaLangReflectAccessibleObject_flag;
    261     int         offJavaLangReflectConstructor_slot;
    262     int         offJavaLangReflectConstructor_declClass;
    263     int         offJavaLangReflectField_slot;
    264     int         offJavaLangReflectField_declClass;
    265     int         offJavaLangReflectMethod_slot;
    266     int         offJavaLangReflectMethod_declClass;
    267 
    268     /* field offsets - java.lang.ref.Reference */
    269     int         offJavaLangRefReference_referent;
    270     int         offJavaLangRefReference_queue;
    271     int         offJavaLangRefReference_queueNext;
    272     int         offJavaLangRefReference_vmData;
    273 
    274     /* method pointers - java.lang.ref.Reference */
    275     Method*     methJavaLangRefReference_enqueueInternal;
    276 
    277     /* field offsets - java.nio.Buffer and java.nio.DirectByteBufferImpl */
    278     //int         offJavaNioBuffer_capacity;
    279     //int         offJavaNioDirectByteBufferImpl_pointer;
    280 
    281     /* method pointers - java.security.AccessController */
    282     volatile bool javaSecurityAccessControllerReady;
    283     Method*     methJavaSecurityAccessController_doPrivileged[4];
    284 
    285     /* constructor method pointers; no vtable involved, so use Method* */
    286     Method*     methJavaLangStackTraceElement_init;
    287     Method*     methJavaLangExceptionInInitializerError_init;
    288     Method*     methJavaLangRefPhantomReference_init;
    289     Method*     methJavaLangReflectConstructor_init;
    290     Method*     methJavaLangReflectField_init;
    291     Method*     methJavaLangReflectMethod_init;
    292     Method*     methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
    293 
    294     /* static method pointers - android.lang.annotation.* */
    295     Method*
    296         methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
    297 
    298     /* direct method pointers - java.lang.reflect.Proxy */
    299     Method*     methJavaLangReflectProxy_constructorPrototype;
    300 
    301     /* field offsets - java.lang.reflect.Proxy */
    302     int         offJavaLangReflectProxy_h;
    303 
    304     /* fake native entry point method */
    305     Method*     methFakeNativeEntry;
    306 
    307     /* assorted direct buffer helpers */
    308     Method*     methJavaNioReadWriteDirectByteBuffer_init;
    309     Method*     methOrgApacheHarmonyLuniPlatformPlatformAddress_on;
    310     Method*     methOrgApacheHarmonyNioInternalDirectBuffer_getEffectiveAddress;
    311     int         offJavaNioBuffer_capacity;
    312     int         offJavaNioBuffer_effectiveDirectAddress;
    313     int         offOrgApacheHarmonyLuniPlatformPlatformAddress_osaddr;
    314     int         voffOrgApacheHarmonyLuniPlatformPlatformAddress_toLong;
    315 
    316     /*
    317      * VM-synthesized primitive classes, for arrays.
    318      */
    319     ClassObject* volatile primitiveClass[PRIM_MAX];
    320 
    321     /*
    322      * A placeholder ClassObject used during ClassObject
    323      * construction.
    324      */
    325     ClassObject  unlinkedJavaLangClassObject;
    326 
    327     /*
    328      * Thread list.  This always has at least one element in it (main),
    329      * and main is always the first entry.
    330      *
    331      * The threadListLock is used for several things, including the thread
    332      * start condition variable.  Generally speaking, you must hold the
    333      * threadListLock when:
    334      *  - adding/removing items from the list
    335      *  - waiting on or signaling threadStartCond
    336      *  - examining the Thread struct for another thread (this is to avoid
    337      *    one thread freeing the Thread struct while another thread is
    338      *    perusing it)
    339      */
    340     Thread*     threadList;
    341     pthread_mutex_t threadListLock;
    342 
    343     pthread_cond_t threadStartCond;
    344 
    345     /*
    346      * The thread code grabs this before suspending all threads.  There
    347      * are a few things that can cause a "suspend all":
    348      *  (1) the GC is starting;
    349      *  (2) the debugger has sent a "suspend all" request;
    350      *  (3) a thread has hit a breakpoint or exception that the debugger
    351      *      has marked as a "suspend all" event;
    352      *  (4) the SignalCatcher caught a signal that requires suspension.
    353      *  (5) (if implemented) the JIT needs to perform a heavyweight
    354      *      rearrangement of the translation cache or JitTable.
    355      *
    356      * Because we use "safe point" self-suspension, it is never safe to
    357      * do a blocking "lock" call on this mutex -- if it has been acquired,
    358      * somebody is probably trying to put you to sleep.  The leading '_' is
    359      * intended as a reminder that this lock is special.
    360      */
    361     pthread_mutex_t _threadSuspendLock;
    362 
    363     /*
    364      * Guards Thread->suspendCount for all threads, and provides the lock
    365      * for the condition variable that all suspended threads sleep on
    366      * (threadSuspendCountCond).
    367      *
    368      * This has to be separate from threadListLock because of the way
    369      * threads put themselves to sleep.
    370      */
    371     pthread_mutex_t threadSuspendCountLock;
    372 
    373     /*
    374      * Suspended threads sleep on this.  They should sleep on the condition
    375      * variable until their "suspend count" is zero.
    376      *
    377      * Paired with "threadSuspendCountLock".
    378      */
    379     pthread_cond_t  threadSuspendCountCond;
    380 
    381     /*
    382      * Sum of all threads' suspendCount fields.  The JIT needs to know if any
    383      * thread is suspended.  Guarded by threadSuspendCountLock.
    384      */
    385     int  sumThreadSuspendCount;
    386 
    387     /*
    388      * MUTEX ORDERING: when locking multiple mutexes, always grab them in
    389      * this order to avoid deadlock:
    390      *
    391      *  (1) _threadSuspendLock      (use lockThreadSuspend())
    392      *  (2) threadListLock          (use dvmLockThreadList())
    393      *  (3) threadSuspendCountLock  (use lockThreadSuspendCount())
    394      */
    395 
    396 
    397     /*
    398      * Thread ID bitmap.  We want threads to have small integer IDs so
    399      * we can use them in "thin locks".
    400      */
    401     BitVector*  threadIdMap;
    402 
    403     /*
    404      * Manage exit conditions.  The VM exits when all non-daemon threads
    405      * have exited.  If the main thread returns early, we need to sleep
    406      * on a condition variable.
    407      */
    408     int         nonDaemonThreadCount;   /* must hold threadListLock to access */
    409     //pthread_mutex_t vmExitLock;
    410     pthread_cond_t  vmExitCond;
    411 
    412     /*
    413      * The set of DEX files loaded by custom class loaders.
    414      */
    415     HashTable*  userDexFiles;
    416 
    417     /*
    418      * JNI global reference table.
    419      */
    420 #ifdef USE_INDIRECT_REF
    421     IndirectRefTable jniGlobalRefTable;
    422 #else
    423     ReferenceTable  jniGlobalRefTable;
    424 #endif
    425     pthread_mutex_t jniGlobalRefLock;
    426     int         jniGlobalRefHiMark;
    427     int         jniGlobalRefLoMark;
    428 
    429     /*
    430      * JNI pinned object table (used for primitive arrays).
    431      */
    432     ReferenceTable  jniPinRefTable;
    433     pthread_mutex_t jniPinRefLock;
    434 
    435     /* special ReferenceQueue for JNI weak globals */
    436     Object*     jniWeakGlobalRefQueue;
    437 
    438     /*
    439      * Native shared library table.
    440      */
    441     HashTable*  nativeLibs;
    442 
    443     /*
    444      * GC heap lock.  Functions like gcMalloc() acquire this before making
    445      * any changes to the heap.  It is held throughout garbage collection.
    446      */
    447     pthread_mutex_t gcHeapLock;
    448 
    449     /* Opaque pointer representing the heap. */
    450     GcHeap*     gcHeap;
    451 
    452     /*
    453      * Pre-allocated throwables.
    454      */
    455     Object*     outOfMemoryObj;
    456     Object*     internalErrorObj;
    457     Object*     noClassDefFoundErrorObj;
    458 
    459     /* Monitor list, so we can free them */
    460     /*volatile*/ Monitor* monitorList;
    461 
    462     /* Monitor for Thread.sleep() implementation */
    463     Monitor*    threadSleepMon;
    464 
    465     /* set when we create a second heap inside the zygote */
    466     bool        newZygoteHeapAllocated;
    467 
    468     /*
    469      * TLS keys.
    470      */
    471     pthread_key_t pthreadKeySelf;       /* Thread*, for dvmThreadSelf */
    472 
    473     /*
    474      * JNI allows you to have multiple VMs, but we limit ourselves to 1,
    475      * so "vmList" is really just a pointer to the one and only VM.
    476      */
    477     JavaVM*     vmList;
    478 
    479     /*
    480      * Cache results of "A instanceof B".
    481      */
    482     AtomicCache* instanceofCache;
    483 
    484     /* instruction width table, used for optimization and verification */
    485     InstructionWidth*   instrWidth;
    486     /* instruction flags table, used for verification */
    487     InstructionFlags*   instrFlags;
    488     /* instruction format table, used for verification */
    489     InstructionFormat*  instrFormat;
    490 
    491     /*
    492      * Bootstrap class loader linear allocator.
    493      */
    494     LinearAllocHdr* pBootLoaderAlloc;
    495 
    496 
    497     /*
    498      * Heap worker thread.
    499      */
    500     bool            heapWorkerInitialized;
    501     bool            heapWorkerReady;
    502     bool            haltHeapWorker;
    503     pthread_t       heapWorkerHandle;
    504     pthread_mutex_t heapWorkerLock;
    505     pthread_cond_t  heapWorkerCond;
    506     pthread_cond_t  heapWorkerIdleCond;
    507     pthread_mutex_t heapWorkerListLock;
    508 
    509     /*
    510      * Compute some stats on loaded classes.
    511      */
    512     int         numLoadedClasses;
    513     int         numDeclaredMethods;
    514     int         numDeclaredInstFields;
    515     int         numDeclaredStaticFields;
    516 
    517     /* when using a native debugger, set this to suppress watchdog timers */
    518     bool        nativeDebuggerActive;
    519 
    520     /*
    521      * JDWP debugger support.
    522      *
    523      * Note "debuggerActive" is accessed from mterp, so its storage size and
    524      * meaning must not be changed without updating the assembly sources.
    525      */
    526     bool        debuggerConnected;      /* debugger or DDMS is connected */
    527     u1          debuggerActive;         /* debugger is making requests */
    528     JdwpState*  jdwpState;
    529 
    530     /*
    531      * Registry of objects known to the debugger.
    532      */
    533     HashTable*  dbgRegistry;
    534 
    535     /*
    536      * Debugger breakpoint table.
    537      */
    538     BreakpointSet*  breakpointSet;
    539 
    540     /*
    541      * Single-step control struct.  We currently only allow one thread to
    542      * be single-stepping at a time, which is all that really makes sense,
    543      * but it's possible we may need to expand this to be per-thread.
    544      */
    545     StepControl stepControl;
    546 
    547     /*
    548      * DDM features embedded in the VM.
    549      */
    550     bool        ddmThreadNotification;
    551 
    552     /*
    553      * Zygote (partially-started process) support
    554      */
    555     bool        zygote;
    556 
    557     /*
    558      * Used for tracking allocations that we report to DDMS.  When the feature
    559      * is enabled (through a DDMS request) the "allocRecords" pointer becomes
    560      * non-NULL.
    561      */
    562     pthread_mutex_t allocTrackerLock;
    563     AllocRecord*    allocRecords;
    564     int             allocRecordHead;        /* most-recently-added entry */
    565     int             allocRecordCount;       /* #of valid entries */
    566 
    567 #ifdef WITH_ALLOC_LIMITS
    568     /* set on first use of an alloc limit, never cleared */
    569     bool        checkAllocLimits;
    570     /* allocation limit, for setGlobalAllocationLimit() regression testing */
    571     int         allocationLimit;
    572 #endif
    573 
    574 #ifdef WITH_DEADLOCK_PREDICTION
    575     /* global lock on history tree accesses */
    576     pthread_mutex_t deadlockHistoryLock;
    577 
    578     enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
    579 #endif
    580 
    581 #ifdef WITH_PROFILER
    582     /*
    583      * When a profiler is enabled, this is incremented.  Distinct profilers
    584      * include "dmtrace" method tracing, emulator method tracing, and
    585      * possibly instruction counting.
    586      *
    587      * The purpose of this is to have a single value that the interpreter
    588      * can check to see if any profiling activity is enabled.
    589      */
    590     volatile int activeProfilers;
    591 
    592     /*
    593      * State for method-trace profiling.
    594      */
    595     MethodTraceState methodTrace;
    596 
    597     /*
    598      * State for emulator tracing.
    599      */
    600     void*       emulatorTracePage;
    601     int         emulatorTraceEnableCount;
    602 
    603     /*
    604      * Global state for memory allocation profiling.
    605      */
    606     AllocProfState allocProf;
    607 
    608     /*
    609      * Pointers to the original methods for things that have been inlined.
    610      * This makes it easy for us to output method entry/exit records for
    611      * the method calls we're not actually making.
    612      */
    613     Method**    inlinedMethods;
    614 
    615     /*
    616      * Dalvik instruction counts (256 entries).
    617      */
    618     int*        executedInstrCounts;
    619     bool        instructionCountEnableCount;
    620 #endif
    621 
    622     /*
    623      * Signal catcher thread (for SIGQUIT).
    624      */
    625     pthread_t   signalCatcherHandle;
    626     bool        haltSignalCatcher;
    627 
    628     /*
    629      * Stdout/stderr conversion thread.
    630      */
    631     bool            haltStdioConverter;
    632     bool            stdioConverterReady;
    633     pthread_t       stdioConverterHandle;
    634     pthread_mutex_t stdioConverterLock;
    635     pthread_cond_t  stdioConverterCond;
    636 
    637     /*
    638      * pid of the system_server process. We track it so that when system server
    639      * crashes the Zygote process will be killed and restarted.
    640      */
    641     pid_t systemServerPid;
    642 
    643     int kernelGroupScheduling;
    644 
    645 //#define COUNT_PRECISE_METHODS
    646 #ifdef COUNT_PRECISE_METHODS
    647     PointerSet* preciseMethods;
    648 #endif
    649 
    650     /* some RegisterMap statistics, useful during development */
    651     void*       registerMapStats;
    652 };
    653 
    654 extern struct DvmGlobals gDvm;
    655 
    656 #if defined(WITH_JIT)
    657 
    658 /*
    659  * Exiting the compiled code w/o chaining will incur overhead to look up the
    660  * target in the code cache which is extra work only when JIT is enabled. So
    661  * we want to monitor it closely to make sure we don't have performance bugs.
    662  */
    663 typedef enum NoChainExits {
    664     kInlineCacheMiss = 0,
    665     kCallsiteInterpreted,
    666     kSwitchOverflow,
    667     kHeavyweightMonitor,
    668     kNoChainExitLast,
    669 } NoChainExits;
    670 
    671 /*
    672  * JIT-specific global state
    673  */
    674 struct DvmJitGlobals {
    675     /*
    676      * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
    677      * chain fields within the JIT hash table.  Note carefully the access
    678      * mechanism.
    679      * Only writes are guarded, and the guarded fields must be updated in a
    680      * specific order using atomic operations.  Further, once a field is
    681      * written it cannot be changed without halting all threads.
    682      *
    683      * The write order is:
    684      *    1) codeAddr
    685      *    2) dPC
    686      *    3) chain [if necessary]
    687      *
    688      * This mutex also guards both read and write of curJitTableEntries.
    689      */
    690     pthread_mutex_t tableLock;
    691 
    692     /* The JIT hash table.  Note that for access speed, copies of this pointer
    693      * are stored in each thread. */
    694     struct JitEntry *pJitEntryTable;
    695 
    696     /* Array of profile threshold counters */
    697     unsigned char *pProfTable;
    698 
    699     /* Copy of pProfTable used for temporarily disabling the Jit */
    700     unsigned char *pProfTableCopy;
    701 
    702     /* Size of JIT hash table in entries.  Must be a power of 2 */
    703     unsigned int jitTableSize;
    704 
    705     /* Mask used in hash function for JitTable.  Should be jitTableSize-1 */
    706     unsigned int jitTableMask;
    707 
    708     /* How many entries in the JitEntryTable are in use */
    709     unsigned int jitTableEntriesUsed;
    710 
    711     /* Bytes allocated for the code cache */
    712     unsigned int codeCacheSize;
    713 
    714     /* Trigger for trace selection */
    715     unsigned short threshold;
    716 
    717     /* JIT Compiler Control */
    718     bool               haltCompilerThread;
    719     bool               blockingMode;
    720     pthread_t          compilerHandle;
    721     pthread_mutex_t    compilerLock;
    722     pthread_mutex_t    compilerICPatchLock;
    723     pthread_cond_t     compilerQueueActivity;
    724     pthread_cond_t     compilerQueueEmpty;
    725     volatile int       compilerQueueLength;
    726     int                compilerHighWater;
    727     int                compilerWorkEnqueueIndex;
    728     int                compilerWorkDequeueIndex;
    729     int                compilerICPatchIndex;
    730 
    731     /* JIT internal stats */
    732     int                compilerMaxQueued;
    733     int                addrLookupsFound;
    734     int                addrLookupsNotFound;
    735     int                noChainExit[kNoChainExitLast];
    736     int                normalExit;
    737     int                puntExit;
    738     int                translationChains;
    739     int                invokeMonomorphic;
    740     int                invokePolymorphic;
    741     int                invokeNative;
    742     int                returnOp;
    743     int                icPatchFast;
    744     int                icPatchQueued;
    745     int                icPatchDropped;
    746     u8                 jitTime;
    747 
    748     /* Compiled code cache */
    749     void* codeCache;
    750 
    751     /* Bytes used by the code templates */
    752     unsigned int templateSize;
    753 
    754     /* Bytes already used in the code cache */
    755     unsigned int codeCacheByteUsed;
    756 
    757     /* Number of installed compilations in the cache */
    758     unsigned int numCompilations;
    759 
    760     /* Flag to indicate that the code cache is full */
    761     bool codeCacheFull;
    762 
    763     /* Number of times that the code cache has been reset */
    764     int numCodeCacheReset;
    765 
    766     /* Number of times that the code cache reset request has been delayed */
    767     int numCodeCacheResetDelayed;
    768 
    769     /* true/false: compile/reject opcodes specified in the -Xjitop list */
    770     bool includeSelectedOp;
    771 
    772     /* true/false: compile/reject methods specified in the -Xjitmethod list */
    773     bool includeSelectedMethod;
    774 
    775     /* Disable JIT for selected opcodes - one bit for each opcode */
    776     char opList[32];
    777 
    778     /* Disable JIT for selected methods */
    779     HashTable *methodTable;
    780 
    781     /* Flag to dump all compiled code */
    782     bool printMe;
    783 
    784     /* Flag to count trace execution */
    785     bool profile;
    786 
    787     /* Vector to disable selected optimizations */
    788     int disableOpt;
    789 
    790     /* Code address of special interpret-only pseudo-translation */
    791     void *interpretTemplate;
    792 
    793     /* Table to track the overall and trace statistics of hot methods */
    794     HashTable*  methodStatsTable;
    795 
    796     /* Filter method compilation blacklist with call-graph information */
    797     bool checkCallGraph;
    798 
    799     /* New translation chain has been set up */
    800     volatile bool hasNewChain;
    801 
    802 #if defined(WITH_SELF_VERIFICATION)
    803     /* Spin when error is detected, volatile so GDB can reset it */
    804     volatile bool selfVerificationSpin;
    805 #endif
    806 
    807     /* Framework or stand-alone? */
    808     bool runningInAndroidFramework;
    809 
    810     /* Framework callback happened? */
    811     bool alreadyEnabledViaFramework;
    812 
    813     /* Framework requests to disable the JIT for good */
    814     bool disableJit;
    815 
    816 #if defined(SIGNATURE_BREAKPOINT)
    817     /* Signature breakpoint */
    818     u4 signatureBreakpointSize;         // # of words
    819     u4 *signatureBreakpoint;            // Signature content
    820 #endif
    821 
    822     /* Place arrays at the end to ease the display in gdb sessions */
    823 
    824     /* Work order queue for compilations */
    825     CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
    826 
    827     /* Work order queue for predicted chain patching */
    828     ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
    829 };
    830 
    831 extern struct DvmJitGlobals gDvmJit;
    832 
    833 #endif
    834 
    835 #endif /*_DALVIK_GLOBALS*/
    836