OSDN Git Service

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