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