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