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