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