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     double      heapTargetUtilization;
     94     size_t      heapMinFree;
     95     size_t      heapMaxFree;
     96     size_t      stackSize;
     97     size_t      mainThreadStackSize;
     98 
     99     bool        verboseGc;
    100     bool        verboseJni;
    101     bool        verboseClass;
    102     bool        verboseShutdown;
    103 
    104     bool        jdwpAllowed;        // debugging allowed for this process?
    105     bool        jdwpConfigured;     // has debugging info been provided?
    106     JdwpTransportType jdwpTransport;
    107     bool        jdwpServer;
    108     char*       jdwpHost;
    109     int         jdwpPort;
    110     bool        jdwpSuspend;
    111 
    112     ProfilerClockSource profilerClockSource;
    113 
    114     /*
    115      * Lock profiling threshold value in milliseconds.  Acquires that
    116      * exceed threshold are logged.  Acquires within the threshold are
    117      * logged with a probability of $\frac{time}{threshold}$ .  If the
    118      * threshold is unset no additional logging occurs.
    119      */
    120     u4          lockProfThreshold;
    121 
    122     int         (*vfprintfHook)(FILE*, const char*, va_list);
    123     void        (*exitHook)(int);
    124     void        (*abortHook)(void);
    125     bool        (*isSensitiveThreadHook)(void);
    126 
    127     int         jniGrefLimit;       // 0 means no limit
    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* classJavaNioDirectByteBuffer;
    272     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
    273     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
    274     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
    275     ClassObject* classOrgApacheHarmonyDalvikDdmcChunk;
    276     ClassObject* classOrgApacheHarmonyDalvikDdmcDdmServer;
    277     ClassObject* classJavaLangRefFinalizerReference;
    278 
    279     /*
    280      * classes representing exception types. The names here don't include
    281      * packages, just to keep the use sites a bit less verbose. All are
    282      * in java.lang, except where noted.
    283      */
    284     ClassObject* exAbstractMethodError;
    285     ClassObject* exArithmeticException;
    286     ClassObject* exArrayIndexOutOfBoundsException;
    287     ClassObject* exArrayStoreException;
    288     ClassObject* exClassCastException;
    289     ClassObject* exClassCircularityError;
    290     ClassObject* exClassFormatError;
    291     ClassObject* exClassNotFoundException;
    292     ClassObject* exError;
    293     ClassObject* exExceptionInInitializerError;
    294     ClassObject* exFileNotFoundException; /* in java.io */
    295     ClassObject* exIOException;           /* in java.io */
    296     ClassObject* exIllegalAccessError;
    297     ClassObject* exIllegalAccessException;
    298     ClassObject* exIllegalArgumentException;
    299     ClassObject* exIllegalMonitorStateException;
    300     ClassObject* exIllegalStateException;
    301     ClassObject* exIllegalThreadStateException;
    302     ClassObject* exIncompatibleClassChangeError;
    303     ClassObject* exInstantiationError;
    304     ClassObject* exInstantiationException;
    305     ClassObject* exInternalError;
    306     ClassObject* exInterruptedException;
    307     ClassObject* exLinkageError;
    308     ClassObject* exNegativeArraySizeException;
    309     ClassObject* exNoClassDefFoundError;
    310     ClassObject* exNoSuchFieldError;
    311     ClassObject* exNoSuchFieldException;
    312     ClassObject* exNoSuchMethodError;
    313     ClassObject* exNullPointerException;
    314     ClassObject* exOutOfMemoryError;
    315     ClassObject* exRuntimeException;
    316     ClassObject* exStackOverflowError;
    317     ClassObject* exStaleDexCacheError;    /* in dalvik.system */
    318     ClassObject* exStringIndexOutOfBoundsException;
    319     ClassObject* exThrowable;
    320     ClassObject* exTypeNotPresentException;
    321     ClassObject* exUnsatisfiedLinkError;
    322     ClassObject* exUnsupportedOperationException;
    323     ClassObject* exVerifyError;
    324     ClassObject* exVirtualMachineError;
    325 
    326     /* method offsets - Object */
    327     int         voffJavaLangObject_equals;
    328     int         voffJavaLangObject_hashCode;
    329     int         voffJavaLangObject_toString;
    330 
    331     /* field offsets - String */
    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     int         offJavaLangThread_uncaughtHandler;
    344     int         offJavaLangThread_contextClassLoader;
    345 
    346     /* method offsets - Thread */
    347     int         voffJavaLangThread_run;
    348 
    349     /* field offsets - ThreadGroup */
    350     int         offJavaLangThreadGroup_name;
    351     int         offJavaLangThreadGroup_parent;
    352 
    353     /* field offsets - VMThread */
    354     int         offJavaLangVMThread_thread;
    355     int         offJavaLangVMThread_vmData;
    356 
    357     /* method offsets - ThreadGroup */
    358     int         voffJavaLangThreadGroup_removeThread;
    359 
    360     /* field offsets - Throwable */
    361     int         offJavaLangThrowable_stackState;
    362     int         offJavaLangThrowable_cause;
    363 
    364     /* method offsets - ClassLoader */
    365     int         voffJavaLangClassLoader_loadClass;
    366 
    367     /* direct method pointers - ClassLoader */
    368     Method*     methJavaLangClassLoader_getSystemClassLoader;
    369 
    370     /* field offsets - java.lang.reflect.* */
    371     int         offJavaLangReflectConstructor_slot;
    372     int         offJavaLangReflectConstructor_declClass;
    373     int         offJavaLangReflectField_slot;
    374     int         offJavaLangReflectField_declClass;
    375     int         offJavaLangReflectMethod_slot;
    376     int         offJavaLangReflectMethod_declClass;
    377 
    378     /* field offsets - java.lang.ref.Reference */
    379     int         offJavaLangRefReference_referent;
    380     int         offJavaLangRefReference_queue;
    381     int         offJavaLangRefReference_queueNext;
    382     int         offJavaLangRefReference_pendingNext;
    383 
    384     /* field offsets - java.lang.ref.FinalizerReference */
    385     int offJavaLangRefFinalizerReference_zombie;
    386 
    387     /* method pointers - java.lang.ref.ReferenceQueue */
    388     Method* methJavaLangRefReferenceQueueAdd;
    389 
    390     /* method pointers - java.lang.ref.FinalizerReference */
    391     Method* methJavaLangRefFinalizerReferenceAdd;
    392 
    393     /* constructor method pointers; no vtable involved, so use Method* */
    394     Method*     methJavaLangStackTraceElement_init;
    395     Method*     methJavaLangReflectConstructor_init;
    396     Method*     methJavaLangReflectField_init;
    397     Method*     methJavaLangReflectMethod_init;
    398     Method*     methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
    399 
    400     /* static method pointers - android.lang.annotation.* */
    401     Method*
    402         methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
    403 
    404     /* direct method pointers - java.lang.reflect.Proxy */
    405     Method*     methJavaLangReflectProxy_constructorPrototype;
    406 
    407     /* field offsets - java.lang.reflect.Proxy */
    408     int         offJavaLangReflectProxy_h;
    409 
    410     /* field offsets - java.io.FileDescriptor */
    411     int         offJavaIoFileDescriptor_descriptor;
    412 
    413     /* direct method pointers - dalvik.system.NativeStart */
    414     Method*     methDalvikSystemNativeStart_main;
    415     Method*     methDalvikSystemNativeStart_run;
    416 
    417     /* assorted direct buffer helpers */
    418     Method*     methJavaNioDirectByteBuffer_init;
    419     int         offJavaNioBuffer_capacity;
    420     int         offJavaNioBuffer_effectiveDirectAddress;
    421 
    422     /* direct method pointers - org.apache.harmony.dalvik.ddmc.DdmServer */
    423     Method*     methDalvikDdmcServer_dispatch;
    424     Method*     methDalvikDdmcServer_broadcast;
    425 
    426     /* field offsets - org.apache.harmony.dalvik.ddmc.Chunk */
    427     int         offDalvikDdmcChunk_type;
    428     int         offDalvikDdmcChunk_data;
    429     int         offDalvikDdmcChunk_offset;
    430     int         offDalvikDdmcChunk_length;
    431 
    432     /*
    433      * Thread list.  This always has at least one element in it (main),
    434      * and main is always the first entry.
    435      *
    436      * The threadListLock is used for several things, including the thread
    437      * start condition variable.  Generally speaking, you must hold the
    438      * threadListLock when:
    439      *  - adding/removing items from the list
    440      *  - waiting on or signaling threadStartCond
    441      *  - examining the Thread struct for another thread (this is to avoid
    442      *    one thread freeing the Thread struct while another thread is
    443      *    perusing it)
    444      */
    445     Thread*     threadList;
    446     pthread_mutex_t threadListLock;
    447 
    448     pthread_cond_t threadStartCond;
    449 
    450     /*
    451      * The thread code grabs this before suspending all threads.  There
    452      * are a few things that can cause a "suspend all":
    453      *  (1) the GC is starting;
    454      *  (2) the debugger has sent a "suspend all" request;
    455      *  (3) a thread has hit a breakpoint or exception that the debugger
    456      *      has marked as a "suspend all" event;
    457      *  (4) the SignalCatcher caught a signal that requires suspension.
    458      *  (5) (if implemented) the JIT needs to perform a heavyweight
    459      *      rearrangement of the translation cache or JitTable.
    460      *
    461      * Because we use "safe point" self-suspension, it is never safe to
    462      * do a blocking "lock" call on this mutex -- if it has been acquired,
    463      * somebody is probably trying to put you to sleep.  The leading '_' is
    464      * intended as a reminder that this lock is special.
    465      */
    466     pthread_mutex_t _threadSuspendLock;
    467 
    468     /*
    469      * Guards Thread->suspendCount for all threads, and
    470      * provides the lock for the condition variable that all suspended threads
    471      * sleep on (threadSuspendCountCond).
    472      *
    473      * This has to be separate from threadListLock because of the way
    474      * threads put themselves to sleep.
    475      */
    476     pthread_mutex_t threadSuspendCountLock;
    477 
    478     /*
    479      * Suspended threads sleep on this.  They should sleep on the condition
    480      * variable until their "suspend count" is zero.
    481      *
    482      * Paired with "threadSuspendCountLock".
    483      */
    484     pthread_cond_t  threadSuspendCountCond;
    485 
    486     /*
    487      * Sum of all threads' suspendCount fields. Guarded by
    488      * threadSuspendCountLock.
    489      */
    490     int  sumThreadSuspendCount;
    491 
    492     /*
    493      * MUTEX ORDERING: when locking multiple mutexes, always grab them in
    494      * this order to avoid deadlock:
    495      *
    496      *  (1) _threadSuspendLock      (use lockThreadSuspend())
    497      *  (2) threadListLock          (use dvmLockThreadList())
    498      *  (3) threadSuspendCountLock  (use lockThreadSuspendCount())
    499      */
    500 
    501 
    502     /*
    503      * Thread ID bitmap.  We want threads to have small integer IDs so
    504      * we can use them in "thin locks".
    505      */
    506     BitVector*  threadIdMap;
    507 
    508     /*
    509      * Manage exit conditions.  The VM exits when all non-daemon threads
    510      * have exited.  If the main thread returns early, we need to sleep
    511      * on a condition variable.
    512      */
    513     int         nonDaemonThreadCount;   /* must hold threadListLock to access */
    514     pthread_cond_t  vmExitCond;
    515 
    516     /*
    517      * The set of DEX files loaded by custom class loaders.
    518      */
    519     HashTable*  userDexFiles;
    520 
    521     /*
    522      * JNI global reference table.
    523      */
    524     IndirectRefTable jniGlobalRefTable;
    525     IndirectRefTable jniWeakGlobalRefTable;
    526     pthread_mutex_t jniGlobalRefLock;
    527     pthread_mutex_t jniWeakGlobalRefLock;
    528     int         jniGlobalRefHiMark;
    529     int         jniGlobalRefLoMark;
    530 
    531     /*
    532      * JNI pinned object table (used for primitive arrays).
    533      */
    534     ReferenceTable  jniPinRefTable;
    535     pthread_mutex_t jniPinRefLock;
    536 
    537     /*
    538      * Native shared library table.
    539      */
    540     HashTable*  nativeLibs;
    541 
    542     /*
    543      * GC heap lock.  Functions like gcMalloc() acquire this before making
    544      * any changes to the heap.  It is held throughout garbage collection.
    545      */
    546     pthread_mutex_t gcHeapLock;
    547 
    548     /*
    549      * Condition variable to queue threads waiting to retry an
    550      * allocation.  Signaled after a concurrent GC is completed.
    551      */
    552     pthread_cond_t gcHeapCond;
    553 
    554     /* Opaque pointer representing the heap. */
    555     GcHeap*     gcHeap;
    556 
    557     /* The card table base, modified as needed for marking cards. */
    558     u1*         biasedCardTableBase;
    559 
    560     /*
    561      * Pre-allocated throwables.
    562      */
    563     Object*     outOfMemoryObj;
    564     Object*     internalErrorObj;
    565     Object*     noClassDefFoundErrorObj;
    566 
    567     /* Monitor list, so we can free them */
    568     /*volatile*/ Monitor* monitorList;
    569 
    570     /* Monitor for Thread.sleep() implementation */
    571     Monitor*    threadSleepMon;
    572 
    573     /* set when we create a second heap inside the zygote */
    574     bool        newZygoteHeapAllocated;
    575 
    576     /*
    577      * TLS keys.
    578      */
    579     pthread_key_t pthreadKeySelf;       /* Thread*, for dvmThreadSelf */
    580 
    581     /*
    582      * Cache results of "A instanceof B".
    583      */
    584     AtomicCache* instanceofCache;
    585 
    586     /* inline substitution table, used during optimization */
    587     InlineSub*          inlineSubs;
    588 
    589     /*
    590      * Bootstrap class loader linear allocator.
    591      */
    592     LinearAllocHdr* pBootLoaderAlloc;
    593 
    594     /*
    595      * Compute some stats on loaded classes.
    596      */
    597     int         numLoadedClasses;
    598     int         numDeclaredMethods;
    599     int         numDeclaredInstFields;
    600     int         numDeclaredStaticFields;
    601 
    602     /* when using a native debugger, set this to suppress watchdog timers */
    603     bool        nativeDebuggerActive;
    604 
    605     /*
    606      * JDWP debugger support.
    607      *
    608      * Note: Each thread will normally determine whether the debugger is active
    609      * for it by referring to its subMode flags.  "debuggerActive" here should be
    610      * seen as "debugger is making requests of 1 or more threads".
    611      */
    612     bool        debuggerConnected;      /* debugger or DDMS is connected */
    613     bool        debuggerActive;         /* debugger is making requests */
    614     JdwpState*  jdwpState;
    615 
    616     /*
    617      * Registry of objects known to the debugger.
    618      */
    619     HashTable*  dbgRegistry;
    620 
    621     /*
    622      * Debugger breakpoint table.
    623      */
    624     BreakpointSet*  breakpointSet;
    625 
    626     /*
    627      * Single-step control struct.  We currently only allow one thread to
    628      * be single-stepping at a time, which is all that really makes sense,
    629      * but it's possible we may need to expand this to be per-thread.
    630      */
    631     StepControl stepControl;
    632 
    633     /*
    634      * DDM features embedded in the VM.
    635      */
    636     bool        ddmThreadNotification;
    637 
    638     /*
    639      * Zygote (partially-started process) support
    640      */
    641     bool        zygote;
    642 
    643     /*
    644      * Used for tracking allocations that we report to DDMS.  When the feature
    645      * is enabled (through a DDMS request) the "allocRecords" pointer becomes
    646      * non-NULL.
    647      */
    648     pthread_mutex_t allocTrackerLock;
    649     AllocRecord*    allocRecords;
    650     int             allocRecordHead;        /* most-recently-added entry */
    651     int             allocRecordCount;       /* #of valid entries */
    652 
    653     /*
    654      * When a profiler is enabled, this is incremented.  Distinct profilers
    655      * include "dmtrace" method tracing, emulator method tracing, and
    656      * possibly instruction counting.
    657      *
    658      * The purpose of this is to have a single value that shows whether any
    659      * profiling is going on.  Individual thread will normally check their
    660      * thread-private subMode flags to take any profiling action.
    661      */
    662     volatile int activeProfilers;
    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     int             stdoutPipe[2];
    711     int             stderrPipe[2];
    712 
    713     /*
    714      * pid of the system_server process. We track it so that when system server
    715      * crashes the Zygote process will be killed and restarted.
    716      */
    717     pid_t systemServerPid;
    718 
    719     int kernelGroupScheduling;
    720 
    721 //#define COUNT_PRECISE_METHODS
    722 #ifdef COUNT_PRECISE_METHODS
    723     PointerSet* preciseMethods;
    724 #endif
    725 
    726     /* some RegisterMap statistics, useful during development */
    727     void*       registerMapStats;
    728 
    729 #ifdef VERIFIER_STATS
    730     VerifierStats verifierStats;
    731 #endif
    732 
    733     /* String pointed here will be deposited on the stack frame of dvmAbort */
    734     const char *lastMessage;
    735 };
    736 
    737 extern struct DvmGlobals gDvm;
    738 
    739 #if defined(WITH_JIT)
    740 
    741 /* Trace profiling modes.  Ordering matters - off states before on states */
    742 enum TraceProfilingModes {
    743     kTraceProfilingDisabled = 0,      // Not profiling
    744     kTraceProfilingPeriodicOff = 1,   // Periodic profiling, off phase
    745     kTraceProfilingContinuous = 2,    // Always profiling
    746     kTraceProfilingPeriodicOn = 3     // Periodic profiling, on phase
    747 };
    748 
    749 /*
    750  * Exiting the compiled code w/o chaining will incur overhead to look up the
    751  * target in the code cache which is extra work only when JIT is enabled. So
    752  * we want to monitor it closely to make sure we don't have performance bugs.
    753  */
    754 enum NoChainExits {
    755     kInlineCacheMiss = 0,
    756     kCallsiteInterpreted,
    757     kSwitchOverflow,
    758     kHeavyweightMonitor,
    759     kNoChainExitLast,
    760 };
    761 
    762 /*
    763  * JIT-specific global state
    764  */
    765 struct DvmJitGlobals {
    766     /*
    767      * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
    768      * chain fields within the JIT hash table.  Note carefully the access
    769      * mechanism.
    770      * Only writes are guarded, and the guarded fields must be updated in a
    771      * specific order using atomic operations.  Further, once a field is
    772      * written it cannot be changed without halting all threads.
    773      *
    774      * The write order is:
    775      *    1) codeAddr
    776      *    2) dPC
    777      *    3) chain [if necessary]
    778      *
    779      * This mutex also guards both read and write of curJitTableEntries.
    780      */
    781     pthread_mutex_t tableLock;
    782 
    783     /* The JIT hash table.  Note that for access speed, copies of this pointer
    784      * are stored in each thread. */
    785     struct JitEntry *pJitEntryTable;
    786 
    787     /* Array of compilation trigger threshold counters */
    788     unsigned char *pProfTable;
    789 
    790     /* Trace profiling counters */
    791     struct JitTraceProfCounters *pJitTraceProfCounters;
    792 
    793     /* Copy of pProfTable used for temporarily disabling the Jit */
    794     unsigned char *pProfTableCopy;
    795 
    796     /* Size of JIT hash table in entries.  Must be a power of 2 */
    797     unsigned int jitTableSize;
    798 
    799     /* Mask used in hash function for JitTable.  Should be jitTableSize-1 */
    800     unsigned int jitTableMask;
    801 
    802     /* How many entries in the JitEntryTable are in use */
    803     unsigned int jitTableEntriesUsed;
    804 
    805     /* Bytes allocated for the code cache */
    806     unsigned int codeCacheSize;
    807 
    808     /* Trigger for trace selection */
    809     unsigned short threshold;
    810 
    811     /* JIT Compiler Control */
    812     bool               haltCompilerThread;
    813     bool               blockingMode;
    814     bool               methodTraceSupport;
    815     bool               genSuspendPoll;
    816     Thread*            compilerThread;
    817     pthread_t          compilerHandle;
    818     pthread_mutex_t    compilerLock;
    819     pthread_mutex_t    compilerICPatchLock;
    820     pthread_cond_t     compilerQueueActivity;
    821     pthread_cond_t     compilerQueueEmpty;
    822     volatile int       compilerQueueLength;
    823     int                compilerHighWater;
    824     int                compilerWorkEnqueueIndex;
    825     int                compilerWorkDequeueIndex;
    826     int                compilerICPatchIndex;
    827 
    828     /* JIT internal stats */
    829     int                compilerMaxQueued;
    830     int                translationChains;
    831 
    832     /* Compiled code cache */
    833     void* codeCache;
    834 
    835     /*
    836      * This is used to store the base address of an in-flight compilation whose
    837      * class object pointers have been calculated to populate literal pool.
    838      * Once the compiler thread has changed its status to VM_WAIT, we cannot
    839      * guarantee whether GC has happened before the code address has been
    840      * installed to the JIT table. Because of that, this field can only
    841      * been cleared/overwritten by the compiler thread if it is in the
    842      * THREAD_RUNNING state or in a safe point.
    843      */
    844     void *inflightBaseAddr;
    845 
    846     /* Translation cache version (protected by compilerLock */
    847     int cacheVersion;
    848 
    849     /* Bytes used by the code templates */
    850     unsigned int templateSize;
    851 
    852     /* Bytes already used in the code cache */
    853     unsigned int codeCacheByteUsed;
    854 
    855     /* Number of installed compilations in the cache */
    856     unsigned int numCompilations;
    857 
    858     /* Flag to indicate that the code cache is full */
    859     bool codeCacheFull;
    860 
    861     /* Page size  - 1 */
    862     unsigned int pageSizeMask;
    863 
    864     /* Lock to change the protection type of the code cache */
    865     pthread_mutex_t    codeCacheProtectionLock;
    866 
    867     /* Number of times that the code cache has been reset */
    868     int numCodeCacheReset;
    869 
    870     /* Number of times that the code cache reset request has been delayed */
    871     int numCodeCacheResetDelayed;
    872 
    873     /* true/false: compile/reject opcodes specified in the -Xjitop list */
    874     bool includeSelectedOp;
    875 
    876     /* true/false: compile/reject methods specified in the -Xjitmethod list */
    877     bool includeSelectedMethod;
    878 
    879     /* true/false: compile/reject traces with offset specified in the -Xjitoffset list */
    880     bool includeSelectedOffset;
    881 
    882     /* Disable JIT for selected opcodes - one bit for each opcode */
    883     char opList[(kNumPackedOpcodes+7)/8];
    884 
    885     /* Disable JIT for selected methods */
    886     HashTable *methodTable;
    887 
    888     /* Disable JIT for selected classes */
    889     HashTable *classTable;
    890 
    891     /* Disable JIT for selected offsets */
    892     unsigned int pcTable[COMPILER_PC_OFFSET_SIZE];
    893     int num_entries_pcTable;
    894 
    895     /* Flag to dump all compiled code */
    896     bool printMe;
    897 
    898     /* Flag to dump compiled binary code in bytes */
    899     bool printBinary;
    900 
    901     /* Per-process debug flag toggled when receiving a SIGUSR2 */
    902     bool receivedSIGUSR2;
    903 
    904     /* Trace profiling mode */
    905     TraceProfilingModes profileMode;
    906 
    907     /* Periodic trace profiling countdown timer */
    908     int profileCountdown;
    909 
    910     /* Vector to disable selected optimizations */
    911     int disableOpt;
    912 
    913     /* Table to track the overall and trace statistics of hot methods */
    914     HashTable*  methodStatsTable;
    915 
    916     /* Filter method compilation blacklist with call-graph information */
    917     bool checkCallGraph;
    918 
    919     /* New translation chain has been set up */
    920     volatile bool hasNewChain;
    921 
    922 #if defined(WITH_SELF_VERIFICATION)
    923     /* Spin when error is detected, volatile so GDB can reset it */
    924     volatile bool selfVerificationSpin;
    925 #endif
    926 
    927     /* Framework or stand-alone? */
    928     bool runningInAndroidFramework;
    929 
    930     /* Framework callback happened? */
    931     bool alreadyEnabledViaFramework;
    932 
    933     /* Framework requests to disable the JIT for good */
    934     bool disableJit;
    935 
    936 #if defined(SIGNATURE_BREAKPOINT)
    937     /* Signature breakpoint */
    938     u4 signatureBreakpointSize;         // # of words
    939     u4 *signatureBreakpoint;            // Signature content
    940 #endif
    941 
    942 #if defined(WITH_JIT_TUNING)
    943     /* Performance tuning counters */
    944     int                addrLookupsFound;
    945     int                addrLookupsNotFound;
    946     int                noChainExit[kNoChainExitLast];
    947     int                normalExit;
    948     int                puntExit;
    949     int                invokeMonomorphic;
    950     int                invokePolymorphic;
    951     int                invokeNative;
    952     int                invokeMonoGetterInlined;
    953     int                invokeMonoSetterInlined;
    954     int                invokePolyGetterInlined;
    955     int                invokePolySetterInlined;
    956     int                returnOp;
    957     int                icPatchInit;
    958     int                icPatchLockFree;
    959     int                icPatchQueued;
    960     int                icPatchRejected;
    961     int                icPatchDropped;
    962     int                codeCachePatches;
    963     int                numCompilerThreadBlockGC;
    964     u8                 jitTime;
    965     u8                 compilerThreadBlockGCStart;
    966     u8                 compilerThreadBlockGCTime;
    967     u8                 maxCompilerThreadBlockGCTime;
    968 #endif
    969 
    970 #if defined(ARCH_IA32)
    971     JitOptLevel        optLevel;
    972 #endif
    973 
    974     /* Place arrays at the end to ease the display in gdb sessions */
    975 
    976     /* Work order queue for compilations */
    977     CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
    978 
    979     /* Work order queue for predicted chain patching */
    980     ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
    981 };
    982 
    983 extern struct DvmJitGlobals gDvmJit;
    984 
    985 #if defined(WITH_JIT_TUNING)
    986 extern int gDvmICHitCount;
    987 #endif
    988 
    989 #endif
    990 
    991 struct DvmJniGlobals {
    992     bool useCheckJni;
    993     bool warnOnly;
    994     bool forceCopy;
    995 
    996     // Provide backwards compatibility for pre-ICS apps on ICS.
    997     bool workAroundAppJniBugs;
    998 
    999     // Debugging help for third-party developers. Similar to -Xjnitrace.
   1000     bool logThirdPartyJni;
   1001 
   1002     // We only support a single JavaVM per process.
   1003     JavaVM*     jniVm;
   1004 };
   1005 
   1006 extern struct DvmJniGlobals gDvmJni;
   1007 
   1008 #endif  // DALVIK_GLOBALS_H_
   1009