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