• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stdarg.h>
33 #include <pthread.h>
34 
35 #define MAX_BREAKPOINTS 20      /* used for a debugger optimization */
36 
37 // fwd
38 typedef struct GcHeap GcHeap;   /* heap internal structure */
39 
40 /*
41  * One of these for each -ea/-da/-esa/-dsa on the command line.
42  */
43 typedef struct AssertionControl {
44     char*   pkgOrClass;         /* package/class string, or NULL for esa/dsa */
45     int     pkgOrClassLen;      /* string length, for quick compare */
46     bool    enable;             /* enable or disable */
47     bool    isPackage;          /* string ended with "..."? */
48 } AssertionControl;
49 
50 /*
51  * Execution mode, e.g. interpreter vs. JIT.
52  */
53 typedef enum ExecutionMode {
54     kExecutionModeUnknown = 0,
55     kExecutionModeInterpPortable,
56     kExecutionModeInterpFast,
57 } ExecutionMode;
58 
59 /*
60  * All fields are initialized to zero.
61  *
62  * Storage allocated here must be freed by a subsystem shutdown function or
63  * from within freeGlobals().
64  */
65 struct DvmGlobals {
66     /*
67      * Some options from the command line or environment.
68      */
69     char*       bootClassPathStr;
70     char*       classPathStr;
71 
72     unsigned int    heapSizeStart;
73     unsigned int    heapSizeMax;
74     unsigned int    stackSize;
75 
76     bool        verboseGc;
77     bool        verboseJni;
78     bool        verboseClass;
79 
80     bool        jdwpAllowed;        // debugging allowed for this process?
81     bool        jdwpConfigured;     // has debugging info been provided?
82     int         jdwpTransport;
83     bool        jdwpServer;
84     char*       jdwpHost;
85     int         jdwpPort;
86     bool        jdwpSuspend;
87 
88     int         (*vfprintfHook)(FILE*, const char*, va_list);
89     void        (*exitHook)(int);
90     void        (*abortHook)(void);
91 
92     int         jniGrefLimit;       // 0 means no limit
93     bool        reduceSignals;
94     bool        noQuitHandler;
95     bool        verifyDexChecksum;
96     char*       stackTraceFile;     // for SIGQUIT-inspired output
97 
98     bool        logStdio;
99 
100     DexOptimizerMode    dexOptMode;
101     DexClassVerifyMode  classVerifyMode;
102     bool        generateRegisterMaps;
103 
104     int         assertionCtrlCount;
105     AssertionControl*   assertionCtrl;
106 
107     ExecutionMode   executionMode;
108 
109     /*
110      * VM init management.
111      */
112     bool        initializing;
113     int         initExceptionCount;
114     bool        optimizing;
115 
116     /*
117      * java.lang.System properties set from the command line.
118      */
119     int         numProps;
120     int         maxProps;
121     char**      propList;
122 
123     /*
124      * Where the VM goes to find system classes.
125      */
126     ClassPathEntry* bootClassPath;
127     /* used by the DEX optimizer to load classes from an unfinished DEX */
128     DvmDex*     bootClassPathOptExtra;
129     bool        optimizingBootstrapClass;
130 
131     /*
132      * Loaded classes, hashed by class name.  Each entry is a ClassObject*,
133      * allocated in GC space.
134      */
135     HashTable*  loadedClasses;
136 
137     /*
138      * Value for the next class serial number to be assigned.  This is
139      * incremented as we load classes.  Failed loads and races may result
140      * in some numbers being skipped, and the serial number is not
141      * guaranteed to start at 1, so the current value should not be used
142      * as a count of loaded classes.
143      */
144     volatile int classSerialNumber;
145 
146     /*
147      * Classes with a low classSerialNumber are probably in the zygote, and
148      * their InitiatingLoaderList is not used, to promote sharing. The list is
149      * kept here instead.
150      */
151     InitiatingLoaderList* initiatingLoaderList;
152 
153     /*
154      * Interned strings.
155      */
156     HashTable*  internedStrings;
157 
158     /*
159      * Quick lookups for popular classes used internally.
160      */
161     ClassObject* unlinkedJavaLangClass;    // see unlinkedJavaLangClassObject
162     ClassObject* classJavaLangClass;
163     ClassObject* classJavaLangClassArray;
164     ClassObject* classJavaLangError;
165     ClassObject* classJavaLangObject;
166     ClassObject* classJavaLangObjectArray;
167     ClassObject* classJavaLangRuntimeException;
168     ClassObject* classJavaLangString;
169     ClassObject* classJavaLangThread;
170     ClassObject* classJavaLangVMThread;
171     ClassObject* classJavaLangThreadGroup;
172     ClassObject* classJavaLangThrowable;
173     ClassObject* classJavaLangStackTraceElement;
174     ClassObject* classJavaLangStackTraceElementArray;
175     ClassObject* classJavaLangAnnotationAnnotationArray;
176     ClassObject* classJavaLangAnnotationAnnotationArrayArray;
177     ClassObject* classJavaLangReflectAccessibleObject;
178     ClassObject* classJavaLangReflectConstructor;
179     ClassObject* classJavaLangReflectConstructorArray;
180     ClassObject* classJavaLangReflectField;
181     ClassObject* classJavaLangReflectFieldArray;
182     ClassObject* classJavaLangReflectMethod;
183     ClassObject* classJavaLangReflectMethodArray;
184     ClassObject* classJavaLangReflectProxy;
185     ClassObject* classJavaLangExceptionInInitializerError;
186     ClassObject* classJavaLangRefReference;
187     ClassObject* classJavaNioReadWriteDirectByteBuffer;
188     ClassObject* classJavaSecurityAccessController;
189     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationFactory;
190     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMember;
191     ClassObject* classOrgApacheHarmonyLangAnnotationAnnotationMemberArray;
192     ClassObject* classOrgApacheHarmonyNioInternalDirectBuffer;
193 
194     /* synthetic classes for arrays of primitives */
195     ClassObject* classArrayBoolean;
196     ClassObject* classArrayChar;
197     ClassObject* classArrayFloat;
198     ClassObject* classArrayDouble;
199     ClassObject* classArrayByte;
200     ClassObject* classArrayShort;
201     ClassObject* classArrayInt;
202     ClassObject* classArrayLong;
203 
204     /* method offsets - Object */
205     int         voffJavaLangObject_equals;
206     int         voffJavaLangObject_hashCode;
207     int         voffJavaLangObject_toString;
208     int         voffJavaLangObject_finalize;
209 
210     /* field offsets - Class */
211     int         offJavaLangClass_pd;
212 
213     /* field offsets - String */
214     volatile int javaLangStringReady;   /* 0=not init, 1=ready, -1=initing */
215     int         offJavaLangString_value;
216     int         offJavaLangString_count;
217     int         offJavaLangString_offset;
218     int         offJavaLangString_hashCode;
219 
220     /* field offsets - Thread */
221     int         offJavaLangThread_vmThread;
222     int         offJavaLangThread_group;
223     int         offJavaLangThread_daemon;
224     int         offJavaLangThread_name;
225     int         offJavaLangThread_priority;
226 
227     /* method offsets - Thread */
228     int         voffJavaLangThread_run;
229 
230     /* field offsets - VMThread */
231     int         offJavaLangVMThread_thread;
232     int         offJavaLangVMThread_vmData;
233 
234     /* method offsets - ThreadGroup */
235     int         voffJavaLangThreadGroup_removeThread;
236 
237     /* field offsets - Throwable */
238     int         offJavaLangThrowable_stackState;
239     int         offJavaLangThrowable_message;
240     int         offJavaLangThrowable_cause;
241 
242     /* field offsets - java.lang.reflect.* */
243     int         offJavaLangReflectAccessibleObject_flag;
244     int         offJavaLangReflectConstructor_slot;
245     int         offJavaLangReflectConstructor_declClass;
246     int         offJavaLangReflectField_slot;
247     int         offJavaLangReflectField_declClass;
248     int         offJavaLangReflectMethod_slot;
249     int         offJavaLangReflectMethod_declClass;
250 
251     /* field offsets - java.lang.ref.Reference */
252     int         offJavaLangRefReference_referent;
253     int         offJavaLangRefReference_queue;
254     int         offJavaLangRefReference_queueNext;
255     int         offJavaLangRefReference_vmData;
256 
257 #if FANCY_REFERENCE_SUBCLASS
258     /* method offsets - java.lang.ref.Reference */
259     int         voffJavaLangRefReference_clear;
260     int         voffJavaLangRefReference_enqueue;
261 #else
262     /* method pointers - java.lang.ref.Reference */
263     Method*     methJavaLangRefReference_enqueueInternal;
264 #endif
265 
266     /* field offsets - java.nio.Buffer and java.nio.DirectByteBufferImpl */
267     //int         offJavaNioBuffer_capacity;
268     //int         offJavaNioDirectByteBufferImpl_pointer;
269 
270     /* method pointers - java.security.AccessController */
271     volatile bool javaSecurityAccessControllerReady;
272     Method*     methJavaSecurityAccessController_doPrivileged[4];
273 
274     /* constructor method pointers; no vtable involved, so use Method* */
275     Method*     methJavaLangStackTraceElement_init;
276     Method*     methJavaLangExceptionInInitializerError_init;
277     Method*     methJavaLangReflectConstructor_init;
278     Method*     methJavaLangReflectField_init;
279     Method*     methJavaLangReflectMethod_init;
280     Method*     methOrgApacheHarmonyLangAnnotationAnnotationMember_init;
281 
282     /* static method pointers - android.lang.annotation.* */
283     Method*
284         methOrgApacheHarmonyLangAnnotationAnnotationFactory_createAnnotation;
285 
286     /* direct method pointers - java.lang.reflect.Proxy */
287     Method*     methJavaLangReflectProxy_constructorPrototype;
288 
289     /* field offsets - java.lang.reflect.Proxy */
290     int         offJavaLangReflectProxy_h;
291 
292     /* fake native entry point method */
293     Method*     methFakeNativeEntry;
294 
295     /* assorted direct buffer helpers */
296     Method*     methJavaNioReadWriteDirectByteBuffer_init;
297     Method*     methOrgApacheHarmonyLuniPlatformPlatformAddress_on;
298     Method*     methOrgApacheHarmonyNioInternalDirectBuffer_getEffectiveAddress;
299     int         offJavaNioBuffer_capacity;
300     int         offJavaNioBuffer_effectiveDirectAddress;
301     int         offOrgApacheHarmonyLuniPlatformPlatformAddress_osaddr;
302     int         voffOrgApacheHarmonyLuniPlatformPlatformAddress_toLong;
303 
304     /*
305      * VM-synthesized primitive classes, for arrays.
306      */
307     ClassObject* volatile primitiveClass[PRIM_MAX];
308 
309     /*
310      * A placeholder ClassObject used during ClassObject
311      * construction.
312      */
313     ClassObject  unlinkedJavaLangClassObject;
314 
315     /*
316      * Thread list.  This always has at least one element in it (main),
317      * and main is always the first entry.
318      *
319      * The threadListLock is used for several things, including the thread
320      * start condition variable.  Generally speaking, you must hold the
321      * threadListLock when:
322      *  - adding/removing items from the list
323      *  - waiting on or signaling threadStartCond
324      *  - examining the Thread struct for another thread (this is to avoid
325      *    one thread freeing the Thread struct while another thread is
326      *    perusing it)
327      */
328     Thread*     threadList;
329     pthread_mutex_t threadListLock;
330 
331     pthread_cond_t threadStartCond;
332 
333     /*
334      * The thread code grabs this before suspending all threads.  There
335      * are a few things that can cause a "suspend all":
336      *  (1) the GC is starting;
337      *  (2) the debugger has sent a "suspend all" request;
338      *  (3) a thread has hit a breakpoint or exception that the debugger
339      *      has marked as a "suspend all" event;
340      *  (4) the SignalCatcher caught a signal that requires suspension.
341      *
342      * Because we use "safe point" self-suspension, it is never safe to
343      * do a blocking "lock" call on this mutex -- if it has been acquired,
344      * somebody is probably trying to put you to sleep.  The leading '_' is
345      * intended as a reminder that this lock is special.
346      */
347     pthread_mutex_t _threadSuspendLock;
348 
349     /*
350      * Guards Thread->suspendCount for all threads, and provides the lock
351      * for the condition variable that all suspended threads sleep on
352      * (threadSuspendCountCond).
353      *
354      * This has to be separate from threadListLock because of the way
355      * threads put themselves to sleep.
356      */
357     pthread_mutex_t threadSuspendCountLock;
358 
359     /*
360      * Suspended threads sleep on this.  They should sleep on the condition
361      * variable until their "suspend count" is zero.
362      *
363      * Paired with "threadSuspendCountLock".
364      */
365     pthread_cond_t  threadSuspendCountCond;
366 
367     /*
368      * MUTEX ORDERING: when locking multiple mutexes, always grab them in
369      * this order to avoid deadlock:
370      *
371      *  (1) _threadSuspendLock      (use lockThreadSuspend())
372      *  (2) threadListLock          (use dvmLockThreadList())
373      *  (3) threadSuspendCountLock  (use lockThreadSuspendCount())
374      */
375 
376 
377     /*
378      * Thread ID bitmap.  We want threads to have small integer IDs so
379      * we can use them in "thin locks".
380      */
381     BitVector*  threadIdMap;
382 
383     /*
384      * Manage exit conditions.  The VM exits when all non-daemon threads
385      * have exited.  If the main thread returns early, we need to sleep
386      * on a condition variable.
387      */
388     int         nonDaemonThreadCount;   /* must hold threadListLock to access */
389     //pthread_mutex_t vmExitLock;
390     pthread_cond_t  vmExitCond;
391 
392     /*
393      * The set of DEX files loaded by custom class loaders.
394      */
395     HashTable*  userDexFiles;
396 
397     /*
398      * JNI global reference table.
399      */
400     ReferenceTable  jniGlobalRefTable;
401     pthread_mutex_t jniGlobalRefLock;
402     int         jniGlobalRefHiMark;
403     int         jniGlobalRefLoMark;
404 
405     /*
406      * Native shared library table.
407      */
408     HashTable*  nativeLibs;
409 
410     /*
411      * GC heap lock.  Functions like gcMalloc() acquire this before making
412      * any changes to the heap.  It is held throughout garbage collection.
413      */
414     pthread_mutex_t gcHeapLock;
415 
416     /* Opaque pointer representing the heap. */
417     GcHeap*     gcHeap;
418 
419     /*
420      * Pre-allocated object for out-of-memory errors.
421      */
422     Object*     outOfMemoryObj;
423 
424     /* pre-allocated general failure exception */
425     Object*     internalErrorObj;
426 
427     /* Monitor list, so we can free them */
428     /*volatile*/ Monitor* monitorList;
429 
430     /* Monitor for Thread.sleep() implementation */
431     Monitor*    threadSleepMon;
432 
433     /* set when we create a second heap inside the zygote */
434     bool        newZygoteHeapAllocated;
435 
436     /*
437      * TLS keys.
438      */
439     pthread_key_t pthreadKeySelf;       /* Thread*, for dvmThreadSelf */
440 
441     /*
442      * JNI allows you to have multiple VMs, but we limit ourselves to 1,
443      * so "vmList" is really just a pointer to the one and only VM.
444      */
445     JavaVM*     vmList;
446 
447     /*
448      * Cache results of "A instanceof B".
449      */
450     AtomicCache* instanceofCache;
451 
452     /* instruction width table, used for optimization and verification */
453     InstructionWidth*   instrWidth;
454     /* instruction flags table, used for verification */
455     InstructionFlags*   instrFlags;
456     /* instruction format table, used for verification */
457     InstructionFormat*  instrFormat;
458 
459     /*
460      * Bootstrap class loader linear allocator.
461      */
462     LinearAllocHdr* pBootLoaderAlloc;
463 
464 
465     /*
466      * Heap worker thread.
467      */
468     bool            heapWorkerInitialized;
469     bool            heapWorkerReady;
470     bool            haltHeapWorker;
471     pthread_t       heapWorkerHandle;
472     pthread_mutex_t heapWorkerLock;
473     pthread_cond_t  heapWorkerCond;
474     pthread_cond_t  heapWorkerIdleCond;
475     pthread_mutex_t heapWorkerListLock;
476 
477     /*
478      * Compute some stats on loaded classes.
479      */
480     int         numLoadedClasses;
481     int         numDeclaredMethods;
482     int         numDeclaredInstFields;
483     int         numDeclaredStaticFields;
484 
485     /* when using a native debugger, set this to suppress watchdog timers */
486     bool        nativeDebuggerActive;
487 
488     /*
489      * JDWP debugger support.
490      */
491     bool        debuggerConnected;      /* debugger or DDMS is connected */
492     bool        debuggerActive;         /* debugger is making requests */
493     JdwpState*  jdwpState;
494 
495     /*
496      * Registry of objects known to the debugger.
497      */
498     HashTable*  dbgRegistry;
499 
500     /*
501      * Breakpoint optimization table.  This is global and NOT explicitly
502      * synchronized, but all operations that modify the table are made
503      * from relatively-synchronized functions.  False-positives are
504      * possible, false-negatives (i.e. missing a breakpoint) should not be.
505      */
506     const u2*   debugBreakAddr[MAX_BREAKPOINTS];
507 
508     /*
509      * Single-step control struct.  We currently only allow one thread to
510      * be single-stepping at a time, which is all that really makes sense,
511      * but it's possible we may need to expand this to be per-thread.
512      */
513     StepControl stepControl;
514 
515     /*
516      * DDM features embedded in the VM.
517      */
518     bool        ddmThreadNotification;
519 
520     /*
521      * Zygote (partially-started process) support
522      */
523     bool        zygote;
524 
525     /*
526      * Used for tracking allocations that we report to DDMS.  When the feature
527      * is enabled (through a DDMS request) the "allocRecords" pointer becomes
528      * non-NULL.
529      */
530     pthread_mutex_t allocTrackerLock;
531     AllocRecord*    allocRecords;
532     int             allocRecordHead;        /* most-recently-added entry */
533     int             allocRecordCount;       /* #of valid entries */
534 
535 #ifdef WITH_ALLOC_LIMITS
536     /* set on first use of an alloc limit, never cleared */
537     bool        checkAllocLimits;
538     /* allocation limit, for setGlobalAllocationLimit() regression testing */
539     int         allocationLimit;
540 #endif
541 
542 #ifdef WITH_DEADLOCK_PREDICTION
543     /* global lock on history tree accesses */
544     pthread_mutex_t deadlockHistoryLock;
545 
546     enum { kDPOff=0, kDPWarn, kDPErr, kDPAbort } deadlockPredictMode;
547 #endif
548 
549 #ifdef WITH_PROFILER
550     /*
551      * When a profiler is enabled, this is incremented.  Distinct profilers
552      * include "dmtrace" method tracing, emulator method tracing, and
553      * possibly instruction counting.
554      *
555      * The purpose of this is to have a single value that the interpreter
556      * can check to see if any profiling activity is enabled.
557      */
558     volatile int activeProfilers;
559 
560     /*
561      * State for method-trace profiling.
562      */
563     MethodTraceState methodTrace;
564 
565     /*
566      * State for emulator tracing.
567      */
568     void*       emulatorTracePage;
569     int         emulatorTraceEnableCount;
570 
571     /*
572      * Global state for memory allocation profiling.
573      */
574     AllocProfState allocProf;
575 
576     /*
577      * Pointers to the original methods for things that have been inlined.
578      * This makes it easy for us to output method entry/exit records for
579      * the method calls we're not actually making.
580      */
581     Method**    inlinedMethods;
582 
583     /*
584      * Dalvik instruction counts (256 entries).
585      */
586     int*        executedInstrCounts;
587     bool        instructionCountEnableCount;
588 #endif
589 
590     /*
591      * Signal catcher thread (for SIGQUIT).
592      */
593     pthread_t   signalCatcherHandle;
594     bool        haltSignalCatcher;
595 
596     /*
597      * Stdout/stderr conversion thread.
598      */
599     bool            haltStdioConverter;
600     bool            stdioConverterReady;
601     pthread_t       stdioConverterHandle;
602     pthread_mutex_t stdioConverterLock;
603     pthread_cond_t  stdioConverterCond;
604 
605     /*
606      * pid of the system_server process. We track it so that when system server
607      * crashes the Zygote process will be killed and restarted.
608      */
609     pid_t systemServerPid;
610 
611 //#define COUNT_PRECISE_METHODS
612 #ifdef COUNT_PRECISE_METHODS
613     PointerSet* preciseMethods;
614 #endif
615 };
616 
617 extern struct DvmGlobals gDvm;
618 
619 #endif /*_DALVIK_GLOBALS*/
620