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