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