Globals.h revision 7a86c44bde10b37d8df17d0613072c4ef134189c
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    int         initExceptionCount;
182    bool        optimizing;
183
184    /*
185     * java.lang.System properties set from the command line with -D.
186     * This is effectively a set, where later entries override earlier
187     * ones.
188     */
189    Array*      properties;
190
191    /*
192     * Where the VM goes to find system classes.
193     */
194    ClassPathEntry* bootClassPath;
195    /* used by the DEX optimizer to load classes from an unfinished DEX */
196    DvmDex*     bootClassPathOptExtra;
197    bool        optimizingBootstrapClass;
198
199    /*
200     * Loaded classes, hashed by class name.  Each entry is a ClassObject*,
201     * allocated in GC space.
202     */
203    HashTable*  loadedClasses;
204
205    /*
206     * Value for the next class serial number to be assigned.  This is
207     * incremented as we load classes.  Failed loads and races may result
208     * in some numbers being skipped, and the serial number is not
209     * guaranteed to start at 1, so the current value should not be used
210     * as a count of loaded classes.
211     */
212    volatile int classSerialNumber;
213
214    /*
215     * Classes with a low classSerialNumber are probably in the zygote, and
216     * their InitiatingLoaderList is not used, to promote sharing. The list is
217     * kept here instead.
218     */
219    InitiatingLoaderList* initiatingLoaderList;
220
221    /*
222     * Interned strings.
223     */
224
225    /* A mutex that guards access to the interned string tables. */
226    pthread_mutex_t internLock;
227
228    /* Hash table of strings interned by the user. */
229    HashTable*  internedStrings;
230
231    /* Hash table of strings interned by the class loader. */
232    HashTable*  literalStrings;
233
234    /*
235     * Quick lookups for popular classes used internally.
236     */
237    ClassObject* classJavaLangClass;
238    ClassObject* classJavaLangClassArray;
239    ClassObject* classJavaLangObject;
240    ClassObject* classJavaLangObjectArray;
241    ClassObject* classJavaLangString;
242    ClassObject* classJavaLangThread;
243    ClassObject* classJavaLangVMThread;
244    ClassObject* classJavaLangThreadGroup;
245    ClassObject* classJavaLangStackTraceElement;
246    ClassObject* classJavaLangStackTraceElementArray;
247    ClassObject* classJavaLangAnnotationAnnotationArray;
248    ClassObject* classJavaLangAnnotationAnnotationArrayArray;
249    ClassObject* classJavaLangReflectAccessibleObject;
250    ClassObject* classJavaLangReflectConstructor;
251    ClassObject* classJavaLangReflectConstructorArray;
252    ClassObject* classJavaLangReflectField;
253    ClassObject* classJavaLangReflectFieldArray;
254    ClassObject* classJavaLangReflectMethod;
255    ClassObject* classJavaLangReflectMethodArray;
256    ClassObject* classJavaLangReflectProxy;
257    ClassObject* classJavaLangRefPhantomReference;
258    ClassObject* classJavaLangRefReference;
259    ClassObject* classJavaNioReadWriteDirectByteBuffer;
260    ClassObject* classJavaSecurityAccessController;
261    ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
262    ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
263    ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
264
265    /*
266     * classes representing exception types. The names here don't include
267     * packages, just to keep the use sites a bit less verbose. All are
268     * in java.lang, except where noted.
269     */
270    ClassObject* exArithmeticException;
271    ClassObject* exArrayIndexOutOfBoundsException;
272    ClassObject* exArrayStoreException;
273    ClassObject* exClassCastException;
274    ClassObject* exClassFormatError;
275    ClassObject* exError;
276    ClassObject* exExceptionInInitializerError;
277    ClassObject* exFileNotFoundException; /* in java.io */
278    ClassObject* exIOException;           /* in java.io */
279    ClassObject* exNegativeArraySizeException;
280    ClassObject* exNullPointerException;
281    ClassObject* exRuntimeException;
282    ClassObject* exStackOverflowError;
283    ClassObject* exStringIndexOutOfBoundsException;
284    ClassObject* exThrowable;
285    ClassObject* exUnsupportedOperationException;
286    ClassObject* exVirtualMachineError;
287
288    /* synthetic classes for arrays of primitives */
289    ClassObject* classArrayBoolean;
290    ClassObject* classArrayChar;
291    ClassObject* classArrayFloat;
292    ClassObject* classArrayDouble;
293    ClassObject* classArrayByte;
294    ClassObject* classArrayShort;
295    ClassObject* classArrayInt;
296    ClassObject* classArrayLong;
297
298    /* method offsets - Object */
299    int         voffJavaLangObject_equals;
300    int         voffJavaLangObject_hashCode;
301    int         voffJavaLangObject_toString;
302    int         voffJavaLangObject_finalize;
303
304    /* field offsets - Class */
305    int         offJavaLangClass_pd;
306
307    /* field offsets - String */
308    int         javaLangStringReady;    /* 0=not init, 1=ready, -1=initing */
309    int         offJavaLangString_value;
310    int         offJavaLangString_count;
311    int         offJavaLangString_offset;
312    int         offJavaLangString_hashCode;
313
314    /* field offsets - Thread */
315    int         offJavaLangThread_vmThread;
316    int         offJavaLangThread_group;
317    int         offJavaLangThread_daemon;
318    int         offJavaLangThread_name;
319    int         offJavaLangThread_priority;
320
321    /* method offsets - Thread */
322    int         voffJavaLangThread_run;
323
324    /* field offsets - VMThread */
325    int         offJavaLangVMThread_thread;
326    int         offJavaLangVMThread_vmData;
327
328    /* method offsets - ThreadGroup */
329    int         voffJavaLangThreadGroup_removeThread;
330
331    /* field offsets - Throwable */
332    int         offJavaLangThrowable_stackState;
333    int         offJavaLangThrowable_cause;
334
335    /* method offsets - ClassLoader */
336    int         voffJavaLangClassLoader_loadClass;
337
338    /* field offsets - java.lang.reflect.* */
339    int         offJavaLangReflectAccessibleObject_flag;
340    int         offJavaLangReflectConstructor_slot;
341    int         offJavaLangReflectConstructor_declClass;
342    int         offJavaLangReflectField_slot;
343    int         offJavaLangReflectField_declClass;
344    int         offJavaLangReflectMethod_slot;
345    int         offJavaLangReflectMethod_declClass;
346
347    /* field offsets - java.lang.ref.Reference */
348    int         offJavaLangRefReference_referent;
349    int         offJavaLangRefReference_queue;
350    int         offJavaLangRefReference_queueNext;
351    int         offJavaLangRefReference_pendingNext;
352
353    /* method pointers - java.lang.ref.Reference */
354    Method*     methJavaLangRefReference_enqueueInternal;
355
356    /* method pointers - java.security.AccessController */
357    volatile int javaSecurityAccessControllerReady;
358    Method*     methJavaSecurityAccessController_doPrivileged[4];
359
360    /* constructor method pointers; no vtable involved, so use Method* */
361    Method*     methJavaLangStackTraceElement_init;
362    Method*     methJavaLangExceptionInInitializerError_init;
363    Method*     methJavaLangRefPhantomReference_init;
364    Method*     methJavaLangReflectConstructor_init;
365    Method*     methJavaLangReflectField_init;
366    Method*     methJavaLangReflectMethod_init;
367    Method*     methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
368
369    /* static method pointers - android.lang.annotation.* */
370    Method*
371        methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
372
373    /* direct method pointers - java.lang.reflect.Proxy */
374    Method*     methJavaLangReflectProxy_constructorPrototype;
375
376    /* field offsets - java.lang.reflect.Proxy */
377    int         offJavaLangReflectProxy_h;
378
379    /* fake native entry point method */
380    Method*     methFakeNativeEntry;
381
382    /* assorted direct buffer helpers */
383    Method*     methJavaNioReadWriteDirectByteBuffer_init;
384    int         offJavaNioBuffer_capacity;
385    int         offJavaNioBuffer_effectiveDirectAddress;
386
387    /*
388     * VM-synthesized primitive classes, for arrays.
389     */
390    ClassObject* volatile primitiveClass[PRIM_MAX];
391
392    /*
393     * Thread list.  This always has at least one element in it (main),
394     * and main is always the first entry.
395     *
396     * The threadListLock is used for several things, including the thread
397     * start condition variable.  Generally speaking, you must hold the
398     * threadListLock when:
399     *  - adding/removing items from the list
400     *  - waiting on or signaling threadStartCond
401     *  - examining the Thread struct for another thread (this is to avoid
402     *    one thread freeing the Thread struct while another thread is
403     *    perusing it)
404     */
405    Thread*     threadList;
406    pthread_mutex_t threadListLock;
407
408    pthread_cond_t threadStartCond;
409
410    /*
411     * The thread code grabs this before suspending all threads.  There
412     * are a few things that can cause a "suspend all":
413     *  (1) the GC is starting;
414     *  (2) the debugger has sent a "suspend all" request;
415     *  (3) a thread has hit a breakpoint or exception that the debugger
416     *      has marked as a "suspend all" event;
417     *  (4) the SignalCatcher caught a signal that requires suspension.
418     *  (5) (if implemented) the JIT needs to perform a heavyweight
419     *      rearrangement of the translation cache or JitTable.
420     *
421     * Because we use "safe point" self-suspension, it is never safe to
422     * do a blocking "lock" call on this mutex -- if it has been acquired,
423     * somebody is probably trying to put you to sleep.  The leading '_' is
424     * intended as a reminder that this lock is special.
425     */
426    pthread_mutex_t _threadSuspendLock;
427
428    /*
429     * Guards Thread->suspendCount for all threads, and provides the lock
430     * for the condition variable that all suspended threads sleep on
431     * (threadSuspendCountCond).
432     *
433     * This has to be separate from threadListLock because of the way
434     * threads put themselves to sleep.
435     */
436    pthread_mutex_t threadSuspendCountLock;
437
438    /*
439     * Suspended threads sleep on this.  They should sleep on the condition
440     * variable until their "suspend count" is zero.
441     *
442     * Paired with "threadSuspendCountLock".
443     */
444    pthread_cond_t  threadSuspendCountCond;
445
446    /*
447     * Sum of all threads' suspendCount fields. Guarded by
448     * threadSuspendCountLock.
449     */
450    int  sumThreadSuspendCount;
451
452    /*
453     * MUTEX ORDERING: when locking multiple mutexes, always grab them in
454     * this order to avoid deadlock:
455     *
456     *  (1) _threadSuspendLock      (use lockThreadSuspend())
457     *  (2) threadListLock          (use dvmLockThreadList())
458     *  (3) threadSuspendCountLock  (use lockThreadSuspendCount())
459     */
460
461
462    /*
463     * Thread ID bitmap.  We want threads to have small integer IDs so
464     * we can use them in "thin locks".
465     */
466    BitVector*  threadIdMap;
467
468    /*
469     * Manage exit conditions.  The VM exits when all non-daemon threads
470     * have exited.  If the main thread returns early, we need to sleep
471     * on a condition variable.
472     */
473    int         nonDaemonThreadCount;   /* must hold threadListLock to access */
474    //pthread_mutex_t vmExitLock;
475    pthread_cond_t  vmExitCond;
476
477    /*
478     * The set of DEX files loaded by custom class loaders.
479     */
480    HashTable*  userDexFiles;
481
482    /*
483     * JNI global reference table.
484     */
485#ifdef USE_INDIRECT_REF
486    IndirectRefTable jniGlobalRefTable;
487#else
488    ReferenceTable  jniGlobalRefTable;
489#endif
490    pthread_mutex_t jniGlobalRefLock;
491    int         jniGlobalRefHiMark;
492    int         jniGlobalRefLoMark;
493
494    /*
495     * JNI pinned object table (used for primitive arrays).
496     */
497    ReferenceTable  jniPinRefTable;
498    pthread_mutex_t jniPinRefLock;
499
500    /*
501     * Native shared library table.
502     */
503    HashTable*  nativeLibs;
504
505    /*
506     * GC heap lock.  Functions like gcMalloc() acquire this before making
507     * any changes to the heap.  It is held throughout garbage collection.
508     */
509    pthread_mutex_t gcHeapLock;
510
511    /*
512     * Condition variable to queue threads waiting to retry an
513     * allocation.  Signaled after a concurrent GC is completed.
514     */
515    pthread_cond_t gcHeapCond;
516
517    /* Opaque pointer representing the heap. */
518    GcHeap*     gcHeap;
519
520    /* The card table base, modified as needed for marking cards. */
521    u1*         biasedCardTableBase;
522
523    /*
524     * Pre-allocated throwables.
525     */
526    Object*     outOfMemoryObj;
527    Object*     internalErrorObj;
528    Object*     noClassDefFoundErrorObj;
529
530    /* Monitor list, so we can free them */
531    /*volatile*/ Monitor* monitorList;
532
533    /* Monitor for Thread.sleep() implementation */
534    Monitor*    threadSleepMon;
535
536    /* set when we create a second heap inside the zygote */
537    bool        newZygoteHeapAllocated;
538
539    /*
540     * TLS keys.
541     */
542    pthread_key_t pthreadKeySelf;       /* Thread*, for dvmThreadSelf */
543
544    /*
545     * JNI allows you to have multiple VMs, but we limit ourselves to 1,
546     * so "vmList" is really just a pointer to the one and only VM.
547     */
548    JavaVM*     vmList;
549
550    /*
551     * Cache results of "A instanceof B".
552     */
553    AtomicCache* instanceofCache;
554
555    /* inline substitution table, used during optimization */
556    InlineSub*          inlineSubs;
557
558    /*
559     * Bootstrap class loader linear allocator.
560     */
561    LinearAllocHdr* pBootLoaderAlloc;
562
563
564    /*
565     * Heap worker thread.
566     */
567    bool            heapWorkerInitialized;
568    bool            heapWorkerReady;
569    bool            haltHeapWorker;
570    pthread_t       heapWorkerHandle;
571    pthread_mutex_t heapWorkerLock;
572    pthread_cond_t  heapWorkerCond;
573    pthread_cond_t  heapWorkerIdleCond;
574    pthread_mutex_t heapWorkerListLock;
575
576    /*
577     * Compute some stats on loaded classes.
578     */
579    int         numLoadedClasses;
580    int         numDeclaredMethods;
581    int         numDeclaredInstFields;
582    int         numDeclaredStaticFields;
583
584    /* when using a native debugger, set this to suppress watchdog timers */
585    bool        nativeDebuggerActive;
586
587    /*
588     * JDWP debugger support.
589     */
590    bool        debuggerConnected;      /* debugger or DDMS is connected */
591    JdwpState*  jdwpState;
592
593    /*
594     * Registry of objects known to the debugger.
595     */
596    HashTable*  dbgRegistry;
597
598    /*
599     * Debugger breakpoint table.
600     */
601    BreakpointSet*  breakpointSet;
602
603    /*
604     * Single-step control struct.  We currently only allow one thread to
605     * be single-stepping at a time, which is all that really makes sense,
606     * but it's possible we may need to expand this to be per-thread.
607     */
608    StepControl stepControl;
609
610    /*
611     * DDM features embedded in the VM.
612     */
613    bool        ddmThreadNotification;
614
615    /*
616     * Zygote (partially-started process) support
617     */
618    bool        zygote;
619
620    /*
621     * Used for tracking allocations that we report to DDMS.  When the feature
622     * is enabled (through a DDMS request) the "allocRecords" pointer becomes
623     * non-NULL.
624     */
625    pthread_mutex_t allocTrackerLock;
626    AllocRecord*    allocRecords;
627    int             allocRecordHead;        /* most-recently-added entry */
628    int             allocRecordCount;       /* #of valid entries */
629
630    /*
631     * When normal control flow needs to be interrupted because
632     * of an attached debugger, profiler, thread stop request, etc.,
633     * a bit is set here.  We collapse all stop reasons into
634     * a single location for performance reasons.
635     */
636    volatile int interpBreak;
637
638    /*
639     * State for method-trace profiling.
640     */
641    MethodTraceState methodTrace;
642
643    /*
644     * State for emulator tracing.
645     */
646    void*       emulatorTracePage;
647    int         emulatorTraceEnableCount;
648
649    /*
650     * Global state for memory allocation profiling.
651     */
652    AllocProfState allocProf;
653
654    /*
655     * Pointers to the original methods for things that have been inlined.
656     * This makes it easy for us to output method entry/exit records for
657     * the method calls we're not actually making.  (Used by method
658     * profiling.)
659     */
660    Method**    inlinedMethods;
661
662    /*
663     * Dalvik instruction counts (kNumPackedOpcodes entries).
664     */
665    int*        executedInstrCounts;
666    int         instructionCountEnableCount;
667
668    /*
669     * Signal catcher thread (for SIGQUIT).
670     */
671    pthread_t   signalCatcherHandle;
672    bool        haltSignalCatcher;
673
674    /*
675     * Stdout/stderr conversion thread.
676     */
677    bool            haltStdioConverter;
678    bool            stdioConverterReady;
679    pthread_t       stdioConverterHandle;
680    pthread_mutex_t stdioConverterLock;
681    pthread_cond_t  stdioConverterCond;
682
683    /*
684     * pid of the system_server process. We track it so that when system server
685     * crashes the Zygote process will be killed and restarted.
686     */
687    pid_t systemServerPid;
688
689    int kernelGroupScheduling;
690
691//#define COUNT_PRECISE_METHODS
692#ifdef COUNT_PRECISE_METHODS
693    PointerSet* preciseMethods;
694#endif
695
696    /* some RegisterMap statistics, useful during development */
697    void*       registerMapStats;
698
699#ifdef VERIFIER_STATS
700    VerifierStats verifierStats;
701#endif
702};
703
704extern struct DvmGlobals gDvm;
705
706#if defined(WITH_JIT)
707
708/* Trace profiling modes.  Ordering matters - off states before on states */
709typedef enum TraceProfilingModes {
710    kTraceProfilingDisabled = 0,      // Not profiling
711    kTraceProfilingPeriodicOff = 1,   // Periodic profiling, off phase
712    kTraceProfilingContinuous = 2,    // Always profiling
713    kTraceProfilingPeriodicOn = 3     // Periodic profiling, on phase
714} TraceProfilingModes;
715
716/*
717 * Exiting the compiled code w/o chaining will incur overhead to look up the
718 * target in the code cache which is extra work only when JIT is enabled. So
719 * we want to monitor it closely to make sure we don't have performance bugs.
720 */
721typedef enum NoChainExits {
722    kInlineCacheMiss = 0,
723    kCallsiteInterpreted,
724    kSwitchOverflow,
725    kHeavyweightMonitor,
726    kNoChainExitLast,
727} NoChainExits;
728
729/*
730 * JIT-specific global state
731 */
732struct DvmJitGlobals {
733    /*
734     * Guards writes to Dalvik PC (dPC), translated code address (codeAddr) and
735     * chain fields within the JIT hash table.  Note carefully the access
736     * mechanism.
737     * Only writes are guarded, and the guarded fields must be updated in a
738     * specific order using atomic operations.  Further, once a field is
739     * written it cannot be changed without halting all threads.
740     *
741     * The write order is:
742     *    1) codeAddr
743     *    2) dPC
744     *    3) chain [if necessary]
745     *
746     * This mutex also guards both read and write of curJitTableEntries.
747     */
748    pthread_mutex_t tableLock;
749
750    /* The JIT hash table.  Note that for access speed, copies of this pointer
751     * are stored in each thread. */
752    struct JitEntry *pJitEntryTable;
753
754    /* Array of compilation trigger threshold counters */
755    unsigned char *pProfTable;
756
757    /* Trace profiling counters */
758    struct JitTraceProfCounters *pJitTraceProfCounters;
759
760    /* Copy of pProfTable used for temporarily disabling the Jit */
761    unsigned char *pProfTableCopy;
762
763    /* Size of JIT hash table in entries.  Must be a power of 2 */
764    unsigned int jitTableSize;
765
766    /* Mask used in hash function for JitTable.  Should be jitTableSize-1 */
767    unsigned int jitTableMask;
768
769    /* How many entries in the JitEntryTable are in use */
770    unsigned int jitTableEntriesUsed;
771
772    /* Bytes allocated for the code cache */
773    unsigned int codeCacheSize;
774
775    /* Trigger for trace selection */
776    unsigned short threshold;
777
778    /* JIT Compiler Control */
779    bool               haltCompilerThread;
780    bool               blockingMode;
781    bool               methodTraceSupport;
782    bool               genSuspendPoll;
783    pthread_t          compilerHandle;
784    pthread_mutex_t    compilerLock;
785    pthread_mutex_t    compilerICPatchLock;
786    pthread_cond_t     compilerQueueActivity;
787    pthread_cond_t     compilerQueueEmpty;
788    volatile int       compilerQueueLength;
789    int                compilerHighWater;
790    int                compilerWorkEnqueueIndex;
791    int                compilerWorkDequeueIndex;
792    int                compilerICPatchIndex;
793
794    /* JIT internal stats */
795    int                compilerMaxQueued;
796    int                translationChains;
797
798    /* Compiled code cache */
799    void* codeCache;
800
801    /* Translation cache version (protected by compilerLock */
802    int cacheVersion;
803
804    /* Bytes used by the code templates */
805    unsigned int templateSize;
806
807    /* Bytes already used in the code cache */
808    unsigned int codeCacheByteUsed;
809
810    /* Number of installed compilations in the cache */
811    unsigned int numCompilations;
812
813    /* Flag to indicate that the code cache is full */
814    bool codeCacheFull;
815
816    /* Page size  - 1 */
817    unsigned int pageSizeMask;
818
819    /* Lock to change the protection type of the code cache */
820    pthread_mutex_t    codeCacheProtectionLock;
821
822    /* Number of times that the code cache has been reset */
823    int numCodeCacheReset;
824
825    /* Number of times that the code cache reset request has been delayed */
826    int numCodeCacheResetDelayed;
827
828    /* true/false: compile/reject opcodes specified in the -Xjitop list */
829    bool includeSelectedOp;
830
831    /* true/false: compile/reject methods specified in the -Xjitmethod list */
832    bool includeSelectedMethod;
833
834    /* Disable JIT for selected opcodes - one bit for each opcode */
835    char opList[32];
836
837    /* Disable JIT for selected methods */
838    HashTable *methodTable;
839
840    /* Flag to dump all compiled code */
841    bool printMe;
842
843    /* Trace profiling mode */
844    TraceProfilingModes profileMode;
845
846    /* Periodic trace profiling countdown timer */
847    int profileCountdown;
848
849    /* Vector to disable selected optimizations */
850    int disableOpt;
851
852    /* Table to track the overall and trace statistics of hot methods */
853    HashTable*  methodStatsTable;
854
855    /* Filter method compilation blacklist with call-graph information */
856    bool checkCallGraph;
857
858    /* New translation chain has been set up */
859    volatile bool hasNewChain;
860
861#if defined(WITH_SELF_VERIFICATION)
862    /* Spin when error is detected, volatile so GDB can reset it */
863    volatile bool selfVerificationSpin;
864#endif
865
866    /* Framework or stand-alone? */
867    bool runningInAndroidFramework;
868
869    /* Framework callback happened? */
870    bool alreadyEnabledViaFramework;
871
872    /* Framework requests to disable the JIT for good */
873    bool disableJit;
874
875#if defined(SIGNATURE_BREAKPOINT)
876    /* Signature breakpoint */
877    u4 signatureBreakpointSize;         // # of words
878    u4 *signatureBreakpoint;            // Signature content
879#endif
880
881#if defined(WITH_JIT_TUNING)
882    /* Performance tuning counters */
883    int                addrLookupsFound;
884    int                addrLookupsNotFound;
885    int                noChainExit[kNoChainExitLast];
886    int                normalExit;
887    int                puntExit;
888    int                invokeMonomorphic;
889    int                invokePolymorphic;
890    int                invokeNative;
891    int                invokeMonoGetterInlined;
892    int                invokeMonoSetterInlined;
893    int                invokePolyGetterInlined;
894    int                invokePolySetterInlined;
895    int                returnOp;
896    int                icPatchInit;
897    int                icPatchLockFree;
898    int                icPatchQueued;
899    int                icPatchRejected;
900    int                icPatchDropped;
901    u8                 jitTime;
902    int                codeCachePatches;
903#endif
904
905    /* Place arrays at the end to ease the display in gdb sessions */
906
907    /* Work order queue for compilations */
908    CompilerWorkOrder compilerWorkQueue[COMPILER_WORK_QUEUE_SIZE];
909
910    /* Work order queue for predicted chain patching */
911    ICPatchWorkOrder compilerICPatchQueue[COMPILER_IC_PATCH_QUEUE_SIZE];
912};
913
914extern struct DvmJitGlobals gDvmJit;
915
916#if defined(WITH_JIT_TUNING)
917extern int gDvmICHitCount;
918#endif
919
920#endif
921
922#endif /*_DALVIK_GLOBALS*/
923