Debug.java revision b96f58911e412fdb0ebdd2bda7dbe89a0829b5db
1/* 2 * Copyright (C) 2007 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 17package android.os; 18 19import com.android.internal.util.TypedProperties; 20 21import android.util.Config; 22import android.util.Log; 23 24import java.io.FileDescriptor; 25import java.io.FileNotFoundException; 26import java.io.FileOutputStream; 27import java.io.FileReader; 28import java.io.IOException; 29import java.io.OutputStreamWriter; 30import java.io.PrintWriter; 31import java.io.Reader; 32import java.lang.reflect.Field; 33import java.lang.reflect.Modifier; 34import java.lang.annotation.Target; 35import java.lang.annotation.ElementType; 36import java.lang.annotation.Retention; 37import java.lang.annotation.RetentionPolicy; 38 39import org.apache.harmony.dalvik.ddmc.Chunk; 40import org.apache.harmony.dalvik.ddmc.ChunkHandler; 41import org.apache.harmony.dalvik.ddmc.DdmServer; 42 43import dalvik.bytecode.OpcodeInfo; 44import dalvik.bytecode.Opcodes; 45import dalvik.system.VMDebug; 46 47 48/** 49 * Provides various debugging functions for Android applications, including 50 * tracing and allocation counts. 51 * <p><strong>Logging Trace Files</strong></p> 52 * <p>Debug can create log files that give details about an application, such as 53 * a call stack and start/stop times for any running methods. See <a 54href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 55 * information about reading trace files. To start logging trace files, call one 56 * of the startMethodTracing() methods. To stop tracing, call 57 * {@link #stopMethodTracing()}. 58 */ 59public final class Debug 60{ 61 private static final String TAG = "Debug"; 62 63 /** 64 * Flags for startMethodTracing(). These can be ORed together. 65 * 66 * TRACE_COUNT_ALLOCS adds the results from startAllocCounting to the 67 * trace key file. 68 */ 69 public static final int TRACE_COUNT_ALLOCS = VMDebug.TRACE_COUNT_ALLOCS; 70 71 /** 72 * Flags for printLoadedClasses(). Default behavior is to only show 73 * the class name. 74 */ 75 public static final int SHOW_FULL_DETAIL = 1; 76 public static final int SHOW_CLASSLOADER = (1 << 1); 77 public static final int SHOW_INITIALIZED = (1 << 2); 78 79 // set/cleared by waitForDebugger() 80 private static volatile boolean mWaiting = false; 81 82 private Debug() {} 83 84 /* 85 * How long to wait for the debugger to finish sending requests. I've 86 * seen this hit 800msec on the device while waiting for a response 87 * to travel over USB and get processed, so we take that and add 88 * half a second. 89 */ 90 private static final int MIN_DEBUGGER_IDLE = 1300; // msec 91 92 /* how long to sleep when polling for activity */ 93 private static final int SPIN_DELAY = 200; // msec 94 95 /** 96 * Default trace file path and file 97 */ 98 private static final String DEFAULT_TRACE_PATH_PREFIX = 99 Environment.getExternalStorageDirectory().getPath() + "/"; 100 private static final String DEFAULT_TRACE_BODY = "dmtrace"; 101 private static final String DEFAULT_TRACE_EXTENSION = ".trace"; 102 private static final String DEFAULT_TRACE_FILE_PATH = 103 DEFAULT_TRACE_PATH_PREFIX + DEFAULT_TRACE_BODY 104 + DEFAULT_TRACE_EXTENSION; 105 106 107 /** 108 * This class is used to retrieved various statistics about the memory mappings for this 109 * process. The returns info broken down by dalvik, native, and other. All results are in kB. 110 */ 111 public static class MemoryInfo implements Parcelable { 112 /** The proportional set size for dalvik. */ 113 public int dalvikPss; 114 /** The private dirty pages used by dalvik. */ 115 public int dalvikPrivateDirty; 116 /** The shared dirty pages used by dalvik. */ 117 public int dalvikSharedDirty; 118 119 /** The proportional set size for the native heap. */ 120 public int nativePss; 121 /** The private dirty pages used by the native heap. */ 122 public int nativePrivateDirty; 123 /** The shared dirty pages used by the native heap. */ 124 public int nativeSharedDirty; 125 126 /** The proportional set size for everything else. */ 127 public int otherPss; 128 /** The private dirty pages used by everything else. */ 129 public int otherPrivateDirty; 130 /** The shared dirty pages used by everything else. */ 131 public int otherSharedDirty; 132 133 public MemoryInfo() { 134 } 135 136 /** 137 * Return total PSS memory usage in kB. 138 */ 139 public int getTotalPss() { 140 return dalvikPss + nativePss + otherPss; 141 } 142 143 /** 144 * Return total private dirty memory usage in kB. 145 */ 146 public int getTotalPrivateDirty() { 147 return dalvikPrivateDirty + nativePrivateDirty + otherPrivateDirty; 148 } 149 150 /** 151 * Return total shared dirty memory usage in kB. 152 */ 153 public int getTotalSharedDirty() { 154 return dalvikSharedDirty + nativeSharedDirty + otherSharedDirty; 155 } 156 157 public int describeContents() { 158 return 0; 159 } 160 161 public void writeToParcel(Parcel dest, int flags) { 162 dest.writeInt(dalvikPss); 163 dest.writeInt(dalvikPrivateDirty); 164 dest.writeInt(dalvikSharedDirty); 165 dest.writeInt(nativePss); 166 dest.writeInt(nativePrivateDirty); 167 dest.writeInt(nativeSharedDirty); 168 dest.writeInt(otherPss); 169 dest.writeInt(otherPrivateDirty); 170 dest.writeInt(otherSharedDirty); 171 } 172 173 public void readFromParcel(Parcel source) { 174 dalvikPss = source.readInt(); 175 dalvikPrivateDirty = source.readInt(); 176 dalvikSharedDirty = source.readInt(); 177 nativePss = source.readInt(); 178 nativePrivateDirty = source.readInt(); 179 nativeSharedDirty = source.readInt(); 180 otherPss = source.readInt(); 181 otherPrivateDirty = source.readInt(); 182 otherSharedDirty = source.readInt(); 183 } 184 185 public static final Creator<MemoryInfo> CREATOR = new Creator<MemoryInfo>() { 186 public MemoryInfo createFromParcel(Parcel source) { 187 return new MemoryInfo(source); 188 } 189 public MemoryInfo[] newArray(int size) { 190 return new MemoryInfo[size]; 191 } 192 }; 193 194 private MemoryInfo(Parcel source) { 195 readFromParcel(source); 196 } 197 } 198 199 200 /** 201 * Wait until a debugger attaches. As soon as the debugger attaches, 202 * this returns, so you will need to place a breakpoint after the 203 * waitForDebugger() call if you want to start tracing immediately. 204 */ 205 public static void waitForDebugger() { 206 if (!VMDebug.isDebuggingEnabled()) { 207 //System.out.println("debugging not enabled, not waiting"); 208 return; 209 } 210 if (isDebuggerConnected()) 211 return; 212 213 // if DDMS is listening, inform them of our plight 214 System.out.println("Sending WAIT chunk"); 215 byte[] data = new byte[] { 0 }; // 0 == "waiting for debugger" 216 Chunk waitChunk = new Chunk(ChunkHandler.type("WAIT"), data, 0, 1); 217 DdmServer.sendChunk(waitChunk); 218 219 mWaiting = true; 220 while (!isDebuggerConnected()) { 221 try { Thread.sleep(SPIN_DELAY); } 222 catch (InterruptedException ie) {} 223 } 224 mWaiting = false; 225 226 System.out.println("Debugger has connected"); 227 228 /* 229 * There is no "ready to go" signal from the debugger, and we're 230 * not allowed to suspend ourselves -- the debugger expects us to 231 * be running happily, and gets confused if we aren't. We need to 232 * allow the debugger a chance to set breakpoints before we start 233 * running again. 234 * 235 * Sit and spin until the debugger has been idle for a short while. 236 */ 237 while (true) { 238 long delta = VMDebug.lastDebuggerActivity(); 239 if (delta < 0) { 240 System.out.println("debugger detached?"); 241 break; 242 } 243 244 if (delta < MIN_DEBUGGER_IDLE) { 245 System.out.println("waiting for debugger to settle..."); 246 try { Thread.sleep(SPIN_DELAY); } 247 catch (InterruptedException ie) {} 248 } else { 249 System.out.println("debugger has settled (" + delta + ")"); 250 break; 251 } 252 } 253 } 254 255 /** 256 * Returns "true" if one or more threads is waiting for a debugger 257 * to attach. 258 */ 259 public static boolean waitingForDebugger() { 260 return mWaiting; 261 } 262 263 /** 264 * Determine if a debugger is currently attached. 265 */ 266 public static boolean isDebuggerConnected() { 267 return VMDebug.isDebuggerConnected(); 268 } 269 270 /** 271 * Returns an array of strings that identify VM features. This is 272 * used by DDMS to determine what sorts of operations the VM can 273 * perform. 274 * 275 * @hide 276 */ 277 public static String[] getVmFeatureList() { 278 return VMDebug.getVmFeatureList(); 279 } 280 281 /** 282 * Change the JDWP port. 283 * 284 * @deprecated no longer needed or useful 285 */ 286 @Deprecated 287 public static void changeDebugPort(int port) {} 288 289 /** 290 * This is the pathname to the sysfs file that enables and disables 291 * tracing on the qemu emulator. 292 */ 293 private static final String SYSFS_QEMU_TRACE_STATE = "/sys/qemu_trace/state"; 294 295 /** 296 * Enable qemu tracing. For this to work requires running everything inside 297 * the qemu emulator; otherwise, this method will have no effect. The trace 298 * file is specified on the command line when the emulator is started. For 299 * example, the following command line <br /> 300 * <code>emulator -trace foo</code><br /> 301 * will start running the emulator and create a trace file named "foo". This 302 * method simply enables writing the trace records to the trace file. 303 * 304 * <p> 305 * The main differences between this and {@link #startMethodTracing()} are 306 * that tracing in the qemu emulator traces every cpu instruction of every 307 * process, including kernel code, so we have more complete information, 308 * including all context switches. We can also get more detailed information 309 * such as cache misses. The sequence of calls is determined by 310 * post-processing the instruction trace. The qemu tracing is also done 311 * without modifying the application or perturbing the timing of calls 312 * because no instrumentation is added to the application being traced. 313 * </p> 314 * 315 * <p> 316 * One limitation of using this method compared to using 317 * {@link #startMethodTracing()} on the real device is that the emulator 318 * does not model all of the real hardware effects such as memory and 319 * bus contention. The emulator also has a simple cache model and cannot 320 * capture all the complexities of a real cache. 321 * </p> 322 */ 323 public static void startNativeTracing() { 324 // Open the sysfs file for writing and write "1" to it. 325 PrintWriter outStream = null; 326 try { 327 FileOutputStream fos = new FileOutputStream(SYSFS_QEMU_TRACE_STATE); 328 outStream = new PrintWriter(new OutputStreamWriter(fos)); 329 outStream.println("1"); 330 } catch (Exception e) { 331 } finally { 332 if (outStream != null) 333 outStream.close(); 334 } 335 336 VMDebug.startEmulatorTracing(); 337 } 338 339 /** 340 * Stop qemu tracing. See {@link #startNativeTracing()} to start tracing. 341 * 342 * <p>Tracing can be started and stopped as many times as desired. When 343 * the qemu emulator itself is stopped then the buffered trace records 344 * are flushed and written to the trace file. In fact, it is not necessary 345 * to call this method at all; simply killing qemu is sufficient. But 346 * starting and stopping a trace is useful for examining a specific 347 * region of code.</p> 348 */ 349 public static void stopNativeTracing() { 350 VMDebug.stopEmulatorTracing(); 351 352 // Open the sysfs file for writing and write "0" to it. 353 PrintWriter outStream = null; 354 try { 355 FileOutputStream fos = new FileOutputStream(SYSFS_QEMU_TRACE_STATE); 356 outStream = new PrintWriter(new OutputStreamWriter(fos)); 357 outStream.println("0"); 358 } catch (Exception e) { 359 // We could print an error message here but we probably want 360 // to quietly ignore errors if we are not running in the emulator. 361 } finally { 362 if (outStream != null) 363 outStream.close(); 364 } 365 } 366 367 /** 368 * Enable "emulator traces", in which information about the current 369 * method is made available to the "emulator -trace" feature. There 370 * is no corresponding "disable" call -- this is intended for use by 371 * the framework when tracing should be turned on and left that way, so 372 * that traces captured with F9/F10 will include the necessary data. 373 * 374 * This puts the VM into "profile" mode, which has performance 375 * consequences. 376 * 377 * To temporarily enable tracing, use {@link #startNativeTracing()}. 378 */ 379 public static void enableEmulatorTraceOutput() { 380 VMDebug.startEmulatorTracing(); 381 } 382 383 /** 384 * Start method tracing with default log name and buffer size. See <a 385href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 386 * information about reading these files. Call stopMethodTracing() to stop 387 * tracing. 388 */ 389 public static void startMethodTracing() { 390 VMDebug.startMethodTracing(DEFAULT_TRACE_FILE_PATH, 0, 0); 391 } 392 393 /** 394 * Start method tracing, specifying the trace log file name. The trace 395 * file will be put under "/sdcard" unless an absolute path is given. 396 * See <a 397 href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 398 * information about reading trace files. 399 * 400 * @param traceName Name for the trace log file to create. 401 * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". 402 * If the files already exist, they will be truncated. 403 * If the trace file given does not end in ".trace", it will be appended for you. 404 */ 405 public static void startMethodTracing(String traceName) { 406 startMethodTracing(traceName, 0, 0); 407 } 408 409 /** 410 * Start method tracing, specifying the trace log file name and the 411 * buffer size. The trace files will be put under "/sdcard" unless an 412 * absolute path is given. See <a 413 href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 414 * information about reading trace files. 415 * @param traceName Name for the trace log file to create. 416 * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". 417 * If the files already exist, they will be truncated. 418 * If the trace file given does not end in ".trace", it will be appended for you. 419 * 420 * @param bufferSize The maximum amount of trace data we gather. If not given, it defaults to 8MB. 421 */ 422 public static void startMethodTracing(String traceName, int bufferSize) { 423 startMethodTracing(traceName, bufferSize, 0); 424 } 425 426 /** 427 * Start method tracing, specifying the trace log file name and the 428 * buffer size. The trace files will be put under "/sdcard" unless an 429 * absolute path is given. See <a 430 href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 431 * information about reading trace files. 432 * 433 * <p> 434 * When method tracing is enabled, the VM will run more slowly than 435 * usual, so the timings from the trace files should only be considered 436 * in relative terms (e.g. was run #1 faster than run #2). The times 437 * for native methods will not change, so don't try to use this to 438 * compare the performance of interpreted and native implementations of the 439 * same method. As an alternative, consider using "native" tracing 440 * in the emulator via {@link #startNativeTracing()}. 441 * </p> 442 * 443 * @param traceName Name for the trace log file to create. 444 * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". 445 * If the files already exist, they will be truncated. 446 * If the trace file given does not end in ".trace", it will be appended for you. 447 * @param bufferSize The maximum amount of trace data we gather. If not given, it defaults to 8MB. 448 */ 449 public static void startMethodTracing(String traceName, int bufferSize, 450 int flags) { 451 452 String pathName = traceName; 453 if (pathName.charAt(0) != '/') 454 pathName = DEFAULT_TRACE_PATH_PREFIX + pathName; 455 if (!pathName.endsWith(DEFAULT_TRACE_EXTENSION)) 456 pathName = pathName + DEFAULT_TRACE_EXTENSION; 457 458 VMDebug.startMethodTracing(pathName, bufferSize, flags); 459 } 460 461 /** 462 * Like startMethodTracing(String, int, int), but taking an already-opened 463 * FileDescriptor in which the trace is written. The file name is also 464 * supplied simply for logging. Makes a dup of the file descriptor. 465 * 466 * Not exposed in the SDK unless we are really comfortable with supporting 467 * this and find it would be useful. 468 * @hide 469 */ 470 public static void startMethodTracing(String traceName, FileDescriptor fd, 471 int bufferSize, int flags) { 472 VMDebug.startMethodTracing(traceName, fd, bufferSize, flags); 473 } 474 475 /** 476 * Starts method tracing without a backing file. When stopMethodTracing 477 * is called, the result is sent directly to DDMS. (If DDMS is not 478 * attached when tracing ends, the profiling data will be discarded.) 479 * 480 * @hide 481 */ 482 public static void startMethodTracingDdms(int bufferSize, int flags) { 483 VMDebug.startMethodTracingDdms(bufferSize, flags); 484 } 485 486 /** 487 * Determine whether method tracing is currently active. 488 * @hide 489 */ 490 public static boolean isMethodTracingActive() { 491 return VMDebug.isMethodTracingActive(); 492 } 493 494 /** 495 * Stop method tracing. 496 */ 497 public static void stopMethodTracing() { 498 VMDebug.stopMethodTracing(); 499 } 500 501 /** 502 * Get an indication of thread CPU usage. The value returned 503 * indicates the amount of time that the current thread has spent 504 * executing code or waiting for certain types of I/O. 505 * 506 * The time is expressed in nanoseconds, and is only meaningful 507 * when compared to the result from an earlier call. Note that 508 * nanosecond resolution does not imply nanosecond accuracy. 509 * 510 * On system which don't support this operation, the call returns -1. 511 */ 512 public static long threadCpuTimeNanos() { 513 return VMDebug.threadCpuTimeNanos(); 514 } 515 516 /** 517 * Start counting the number and aggregate size of memory allocations. 518 * 519 * <p>The {@link #startAllocCounting() start} function resets the counts and enables counting. 520 * The {@link #stopAllocCounting() stop} function disables the counting so that the analysis 521 * code doesn't cause additional allocations. The various <code>get</code> functions return 522 * the specified value. And the various <code>reset</code> functions reset the specified 523 * count.</p> 524 * 525 * <p>Counts are kept for the system as a whole and for each thread. 526 * The per-thread counts for threads other than the current thread 527 * are not cleared by the "reset" or "start" calls.</p> 528 */ 529 public static void startAllocCounting() { 530 VMDebug.startAllocCounting(); 531 } 532 533 /** 534 * Stop counting the number and aggregate size of memory allocations. 535 * 536 * @see #startAllocCounting() 537 */ 538 public static void stopAllocCounting() { 539 VMDebug.stopAllocCounting(); 540 } 541 542 public static int getGlobalAllocCount() { 543 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_OBJECTS); 544 } 545 public static int getGlobalAllocSize() { 546 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_BYTES); 547 } 548 public static int getGlobalFreedCount() { 549 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_FREED_OBJECTS); 550 } 551 public static int getGlobalFreedSize() { 552 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_FREED_BYTES); 553 } 554 public static int getGlobalClassInitCount() { 555 /* number of classes that have been successfully initialized */ 556 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_COUNT); 557 } 558 public static int getGlobalClassInitTime() { 559 /* cumulative elapsed time for class initialization, in usec */ 560 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_TIME); 561 } 562 public static int getGlobalExternalAllocCount() { 563 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_EXT_ALLOCATED_OBJECTS); 564 } 565 public static int getGlobalExternalAllocSize() { 566 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_EXT_ALLOCATED_BYTES); 567 } 568 public static int getGlobalExternalFreedCount() { 569 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_EXT_FREED_OBJECTS); 570 } 571 public static int getGlobalExternalFreedSize() { 572 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_EXT_FREED_BYTES); 573 } 574 public static int getGlobalGcInvocationCount() { 575 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_GC_INVOCATIONS); 576 } 577 public static int getThreadAllocCount() { 578 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_ALLOCATED_OBJECTS); 579 } 580 public static int getThreadAllocSize() { 581 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_ALLOCATED_BYTES); 582 } 583 public static int getThreadExternalAllocCount() { 584 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_EXT_ALLOCATED_OBJECTS); 585 } 586 public static int getThreadExternalAllocSize() { 587 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_EXT_ALLOCATED_BYTES); 588 } 589 public static int getThreadGcInvocationCount() { 590 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_GC_INVOCATIONS); 591 } 592 593 public static void resetGlobalAllocCount() { 594 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_OBJECTS); 595 } 596 public static void resetGlobalAllocSize() { 597 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_BYTES); 598 } 599 public static void resetGlobalFreedCount() { 600 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_FREED_OBJECTS); 601 } 602 public static void resetGlobalFreedSize() { 603 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_FREED_BYTES); 604 } 605 public static void resetGlobalClassInitCount() { 606 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_COUNT); 607 } 608 public static void resetGlobalClassInitTime() { 609 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_TIME); 610 } 611 public static void resetGlobalExternalAllocCount() { 612 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_EXT_ALLOCATED_OBJECTS); 613 } 614 public static void resetGlobalExternalAllocSize() { 615 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_EXT_ALLOCATED_BYTES); 616 } 617 public static void resetGlobalExternalFreedCount() { 618 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_EXT_FREED_OBJECTS); 619 } 620 public static void resetGlobalExternalFreedSize() { 621 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_EXT_FREED_BYTES); 622 } 623 public static void resetGlobalGcInvocationCount() { 624 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_GC_INVOCATIONS); 625 } 626 public static void resetThreadAllocCount() { 627 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_ALLOCATED_OBJECTS); 628 } 629 public static void resetThreadAllocSize() { 630 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_ALLOCATED_BYTES); 631 } 632 public static void resetThreadExternalAllocCount() { 633 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_EXT_ALLOCATED_OBJECTS); 634 } 635 public static void resetThreadExternalAllocSize() { 636 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_EXT_ALLOCATED_BYTES); 637 } 638 public static void resetThreadGcInvocationCount() { 639 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_GC_INVOCATIONS); 640 } 641 public static void resetAllCounts() { 642 VMDebug.resetAllocCount(VMDebug.KIND_ALL_COUNTS); 643 } 644 645 /** 646 * Returns the size of the native heap. 647 * @return The size of the native heap in bytes. 648 */ 649 public static native long getNativeHeapSize(); 650 651 /** 652 * Returns the amount of allocated memory in the native heap. 653 * @return The allocated size in bytes. 654 */ 655 public static native long getNativeHeapAllocatedSize(); 656 657 /** 658 * Returns the amount of free memory in the native heap. 659 * @return The freed size in bytes. 660 */ 661 public static native long getNativeHeapFreeSize(); 662 663 /** 664 * Retrieves information about this processes memory usages. This information is broken down by 665 * how much is in use by dalivk, the native heap, and everything else. 666 */ 667 public static native void getMemoryInfo(MemoryInfo memoryInfo); 668 669 /** 670 * Note: currently only works when the requested pid has the same UID 671 * as the caller. 672 * @hide 673 */ 674 public static native void getMemoryInfo(int pid, MemoryInfo memoryInfo); 675 676 /** 677 * Establish an object allocation limit in the current thread. Useful 678 * for catching regressions in code that is expected to operate 679 * without causing any allocations. 680 * 681 * <p>Pass in the maximum number of allowed allocations. Use -1 to disable 682 * the limit. Returns the previous limit.</p> 683 * 684 * <p>The preferred way to use this is: 685 * <pre> 686 * int prevLimit = -1; 687 * try { 688 * prevLimit = Debug.setAllocationLimit(0); 689 * ... do stuff that's not expected to allocate memory ... 690 * } finally { 691 * Debug.setAllocationLimit(prevLimit); 692 * } 693 * </pre> 694 * This allows limits to be nested. The try/finally ensures that the 695 * limit is reset if something fails.</p> 696 * 697 * <p>Exceeding the limit causes a dalvik.system.AllocationLimitError to 698 * be thrown from a memory allocation call. The limit is reset to -1 699 * when this happens.</p> 700 * 701 * <p>The feature may be disabled in the VM configuration. If so, this 702 * call has no effect, and always returns -1.</p> 703 */ 704 public static int setAllocationLimit(int limit) { 705 return VMDebug.setAllocationLimit(limit); 706 } 707 708 /** 709 * Establish a global object allocation limit. This is similar to 710 * {@link #setAllocationLimit(int)} but applies to all threads in 711 * the VM. It will coexist peacefully with per-thread limits. 712 * 713 * [ The value of "limit" is currently restricted to 0 (no allocations 714 * allowed) or -1 (no global limit). This may be changed in a future 715 * release. ] 716 */ 717 public static int setGlobalAllocationLimit(int limit) { 718 if (limit != 0 && limit != -1) 719 throw new IllegalArgumentException("limit must be 0 or -1"); 720 return VMDebug.setGlobalAllocationLimit(limit); 721 } 722 723 /** 724 * Dump a list of all currently loaded class to the log file. 725 * 726 * @param flags See constants above. 727 */ 728 public static void printLoadedClasses(int flags) { 729 VMDebug.printLoadedClasses(flags); 730 } 731 732 /** 733 * Get the number of loaded classes. 734 * @return the number of loaded classes. 735 */ 736 public static int getLoadedClassCount() { 737 return VMDebug.getLoadedClassCount(); 738 } 739 740 /** 741 * Dump "hprof" data to the specified file. This may cause a GC. 742 * 743 * @param fileName Full pathname of output file (e.g. "/sdcard/dump.hprof"). 744 * @throws UnsupportedOperationException if the VM was built without 745 * HPROF support. 746 * @throws IOException if an error occurs while opening or writing files. 747 */ 748 public static void dumpHprofData(String fileName) throws IOException { 749 VMDebug.dumpHprofData(fileName); 750 } 751 752 /** 753 * Like dumpHprofData(String), but takes an already-opened 754 * FileDescriptor to which the trace is written. The file name is also 755 * supplied simply for logging. Makes a dup of the file descriptor. 756 * 757 * Primarily for use by the "am" shell command. 758 * 759 * @hide 760 */ 761 public static void dumpHprofData(String fileName, FileDescriptor fd) 762 throws IOException { 763 VMDebug.dumpHprofData(fileName, fd); 764 } 765 766 /** 767 * Collect "hprof" and send it to DDMS. This may cause a GC. 768 * 769 * @throws UnsupportedOperationException if the VM was built without 770 * HPROF support. 771 * @hide 772 */ 773 public static void dumpHprofDataDdms() { 774 VMDebug.dumpHprofDataDdms(); 775 } 776 777 /** 778 * Writes native heap data to the specified file descriptor. 779 * 780 * @hide 781 */ 782 public static native void dumpNativeHeap(FileDescriptor fd); 783 784 /** 785 * Returns a count of the extant instances of a class. 786 * 787 * @hide 788 */ 789 public static long countInstancesOfClass(Class cls) { 790 return VMDebug.countInstancesOfClass(cls, true); 791 } 792 793 /** 794 * Returns the number of sent transactions from this process. 795 * @return The number of sent transactions or -1 if it could not read t. 796 */ 797 public static native int getBinderSentTransactions(); 798 799 /** 800 * Returns the number of received transactions from the binder driver. 801 * @return The number of received transactions or -1 if it could not read the stats. 802 */ 803 public static native int getBinderReceivedTransactions(); 804 805 /** 806 * Returns the number of active local Binder objects that exist in the 807 * current process. 808 */ 809 public static final native int getBinderLocalObjectCount(); 810 811 /** 812 * Returns the number of references to remote proxy Binder objects that 813 * exist in the current process. 814 */ 815 public static final native int getBinderProxyObjectCount(); 816 817 /** 818 * Returns the number of death notification links to Binder objects that 819 * exist in the current process. 820 */ 821 public static final native int getBinderDeathObjectCount(); 822 823 /** 824 * Primes the register map cache. 825 * 826 * Only works for classes in the bootstrap class loader. Does not 827 * cause classes to be loaded if they're not already present. 828 * 829 * The classAndMethodDesc argument is a concatentation of the VM-internal 830 * class descriptor, method name, and method descriptor. Examples: 831 * Landroid/os/Looper;.loop:()V 832 * Landroid/app/ActivityThread;.main:([Ljava/lang/String;)V 833 * 834 * @param classAndMethodDesc the method to prepare 835 * 836 * @hide 837 */ 838 public static final boolean cacheRegisterMap(String classAndMethodDesc) { 839 return VMDebug.cacheRegisterMap(classAndMethodDesc); 840 } 841 842 /** 843 * Dumps the contents of VM reference tables (e.g. JNI locals and 844 * globals) to the log file. 845 * 846 * @hide 847 */ 848 public static final void dumpReferenceTables() { 849 VMDebug.dumpReferenceTables(); 850 } 851 852 /** 853 * API for gathering and querying instruction counts. 854 * 855 * Example usage: 856 * <pre> 857 * Debug.InstructionCount icount = new Debug.InstructionCount(); 858 * icount.resetAndStart(); 859 * [... do lots of stuff ...] 860 * if (icount.collect()) { 861 * System.out.println("Total instructions executed: " 862 * + icount.globalTotal()); 863 * System.out.println("Method invocations: " 864 * + icount.globalMethodInvocations()); 865 * } 866 * </pre> 867 */ 868 public static class InstructionCount { 869 private static final int NUM_INSTR = 870 OpcodeInfo.MAXIMUM_PACKED_VALUE + 1; 871 872 private int[] mCounts; 873 874 public InstructionCount() { 875 mCounts = new int[NUM_INSTR]; 876 } 877 878 /** 879 * Reset counters and ensure counts are running. Counts may 880 * have already been running. 881 * 882 * @return true if counting was started 883 */ 884 public boolean resetAndStart() { 885 try { 886 VMDebug.startInstructionCounting(); 887 VMDebug.resetInstructionCount(); 888 } catch (UnsupportedOperationException uoe) { 889 return false; 890 } 891 return true; 892 } 893 894 /** 895 * Collect instruction counts. May or may not stop the 896 * counting process. 897 */ 898 public boolean collect() { 899 try { 900 VMDebug.stopInstructionCounting(); 901 VMDebug.getInstructionCount(mCounts); 902 } catch (UnsupportedOperationException uoe) { 903 return false; 904 } 905 return true; 906 } 907 908 /** 909 * Return the total number of instructions executed globally (i.e. in 910 * all threads). 911 */ 912 public int globalTotal() { 913 int count = 0; 914 915 for (int i = 0; i < NUM_INSTR; i++) { 916 count += mCounts[i]; 917 } 918 919 return count; 920 } 921 922 /** 923 * Return the total number of method-invocation instructions 924 * executed globally. 925 */ 926 public int globalMethodInvocations() { 927 int count = 0; 928 929 for (int i = 0; i < NUM_INSTR; i++) { 930 if (OpcodeInfo.isInvoke(i)) { 931 count += mCounts[i]; 932 } 933 } 934 935 return count; 936 } 937 } 938 939 /** 940 * A Map of typed debug properties. 941 */ 942 private static final TypedProperties debugProperties; 943 944 /* 945 * Load the debug properties from the standard files into debugProperties. 946 */ 947 static { 948 if (Config.DEBUG) { 949 final String TAG = "DebugProperties"; 950 final String[] files = { "/system/debug.prop", "/debug.prop", "/data/debug.prop" }; 951 final TypedProperties tp = new TypedProperties(); 952 953 // Read the properties from each of the files, if present. 954 for (String file : files) { 955 Reader r; 956 try { 957 r = new FileReader(file); 958 } catch (FileNotFoundException ex) { 959 // It's ok if a file is missing. 960 continue; 961 } 962 963 try { 964 tp.load(r); 965 } catch (Exception ex) { 966 throw new RuntimeException("Problem loading " + file, ex); 967 } finally { 968 try { 969 r.close(); 970 } catch (IOException ex) { 971 // Ignore this error. 972 } 973 } 974 } 975 976 debugProperties = tp.isEmpty() ? null : tp; 977 } else { 978 debugProperties = null; 979 } 980 } 981 982 983 /** 984 * Returns true if the type of the field matches the specified class. 985 * Handles the case where the class is, e.g., java.lang.Boolean, but 986 * the field is of the primitive "boolean" type. Also handles all of 987 * the java.lang.Number subclasses. 988 */ 989 private static boolean fieldTypeMatches(Field field, Class<?> cl) { 990 Class<?> fieldClass = field.getType(); 991 if (fieldClass == cl) { 992 return true; 993 } 994 Field primitiveTypeField; 995 try { 996 /* All of the classes we care about (Boolean, Integer, etc.) 997 * have a Class field called "TYPE" that points to the corresponding 998 * primitive class. 999 */ 1000 primitiveTypeField = cl.getField("TYPE"); 1001 } catch (NoSuchFieldException ex) { 1002 return false; 1003 } 1004 try { 1005 return fieldClass == (Class<?>) primitiveTypeField.get(null); 1006 } catch (IllegalAccessException ex) { 1007 return false; 1008 } 1009 } 1010 1011 1012 /** 1013 * Looks up the property that corresponds to the field, and sets the field's value 1014 * if the types match. 1015 */ 1016 private static void modifyFieldIfSet(final Field field, final TypedProperties properties, 1017 final String propertyName) { 1018 if (field.getType() == java.lang.String.class) { 1019 int stringInfo = properties.getStringInfo(propertyName); 1020 switch (stringInfo) { 1021 case TypedProperties.STRING_SET: 1022 // Handle as usual below. 1023 break; 1024 case TypedProperties.STRING_NULL: 1025 try { 1026 field.set(null, null); // null object for static fields; null string 1027 } catch (IllegalAccessException ex) { 1028 throw new IllegalArgumentException( 1029 "Cannot set field for " + propertyName, ex); 1030 } 1031 return; 1032 case TypedProperties.STRING_NOT_SET: 1033 return; 1034 case TypedProperties.STRING_TYPE_MISMATCH: 1035 throw new IllegalArgumentException( 1036 "Type of " + propertyName + " " + 1037 " does not match field type (" + field.getType() + ")"); 1038 default: 1039 throw new IllegalStateException( 1040 "Unexpected getStringInfo(" + propertyName + ") return value " + 1041 stringInfo); 1042 } 1043 } 1044 Object value = properties.get(propertyName); 1045 if (value != null) { 1046 if (!fieldTypeMatches(field, value.getClass())) { 1047 throw new IllegalArgumentException( 1048 "Type of " + propertyName + " (" + value.getClass() + ") " + 1049 " does not match field type (" + field.getType() + ")"); 1050 } 1051 try { 1052 field.set(null, value); // null object for static fields 1053 } catch (IllegalAccessException ex) { 1054 throw new IllegalArgumentException( 1055 "Cannot set field for " + propertyName, ex); 1056 } 1057 } 1058 } 1059 1060 1061 /** 1062 * Equivalent to <code>setFieldsOn(cl, false)</code>. 1063 * 1064 * @see #setFieldsOn(Class, boolean) 1065 * 1066 * @hide 1067 */ 1068 public static void setFieldsOn(Class<?> cl) { 1069 setFieldsOn(cl, false); 1070 } 1071 1072 /** 1073 * Reflectively sets static fields of a class based on internal debugging 1074 * properties. This method is a no-op if android.util.Config.DEBUG is 1075 * false. 1076 * <p> 1077 * <strong>NOTE TO APPLICATION DEVELOPERS</strong>: Config.DEBUG will 1078 * always be false in release builds. This API is typically only useful 1079 * for platform developers. 1080 * </p> 1081 * Class setup: define a class whose only fields are non-final, static 1082 * primitive types (except for "char") or Strings. In a static block 1083 * after the field definitions/initializations, pass the class to 1084 * this method, Debug.setFieldsOn(). Example: 1085 * <pre> 1086 * package com.example; 1087 * 1088 * import android.os.Debug; 1089 * 1090 * public class MyDebugVars { 1091 * public static String s = "a string"; 1092 * public static String s2 = "second string"; 1093 * public static String ns = null; 1094 * public static boolean b = false; 1095 * public static int i = 5; 1096 * @Debug.DebugProperty 1097 * public static float f = 0.1f; 1098 * @@Debug.DebugProperty 1099 * public static double d = 0.5d; 1100 * 1101 * // This MUST appear AFTER all fields are defined and initialized! 1102 * static { 1103 * // Sets all the fields 1104 * Debug.setFieldsOn(MyDebugVars.class); 1105 * 1106 * // Sets only the fields annotated with @Debug.DebugProperty 1107 * // Debug.setFieldsOn(MyDebugVars.class, true); 1108 * } 1109 * } 1110 * </pre> 1111 * setFieldsOn() may override the value of any field in the class based 1112 * on internal properties that are fixed at boot time. 1113 * <p> 1114 * These properties are only set during platform debugging, and are not 1115 * meant to be used as a general-purpose properties store. 1116 * 1117 * {@hide} 1118 * 1119 * @param cl The class to (possibly) modify 1120 * @param partial If false, sets all static fields, otherwise, only set 1121 * fields with the {@link android.os.Debug.DebugProperty} 1122 * annotation 1123 * @throws IllegalArgumentException if any fields are final or non-static, 1124 * or if the type of the field does not match the type of 1125 * the internal debugging property value. 1126 */ 1127 public static void setFieldsOn(Class<?> cl, boolean partial) { 1128 if (Config.DEBUG) { 1129 if (debugProperties != null) { 1130 /* Only look for fields declared directly by the class, 1131 * so we don't mysteriously change static fields in superclasses. 1132 */ 1133 for (Field field : cl.getDeclaredFields()) { 1134 if (!partial || field.getAnnotation(DebugProperty.class) != null) { 1135 final String propertyName = cl.getName() + "." + field.getName(); 1136 boolean isStatic = Modifier.isStatic(field.getModifiers()); 1137 boolean isFinal = Modifier.isFinal(field.getModifiers()); 1138 1139 if (!isStatic || isFinal) { 1140 throw new IllegalArgumentException(propertyName + 1141 " must be static and non-final"); 1142 } 1143 modifyFieldIfSet(field, debugProperties, propertyName); 1144 } 1145 } 1146 } 1147 } else { 1148 Log.wtf(TAG, 1149 "setFieldsOn(" + (cl == null ? "null" : cl.getName()) + 1150 ") called in non-DEBUG build"); 1151 } 1152 } 1153 1154 /** 1155 * Annotation to put on fields you want to set with 1156 * {@link Debug#setFieldsOn(Class, boolean)}. 1157 * 1158 * @hide 1159 */ 1160 @Target({ ElementType.FIELD }) 1161 @Retention(RetentionPolicy.RUNTIME) 1162 public @interface DebugProperty { 1163 } 1164 1165 /** 1166 * Get a debugging dump of a system service by name. 1167 * 1168 * <p>Most services require the caller to hold android.permission.DUMP. 1169 * 1170 * @param name of the service to dump 1171 * @param fd to write dump output to (usually an output log file) 1172 * @param args to pass to the service's dump method, may be null 1173 * @return true if the service was dumped successfully, false if 1174 * the service could not be found or had an error while dumping 1175 */ 1176 public static boolean dumpService(String name, FileDescriptor fd, String[] args) { 1177 IBinder service = ServiceManager.getService(name); 1178 if (service == null) { 1179 Log.e(TAG, "Can't find service to dump: " + name); 1180 return false; 1181 } 1182 1183 try { 1184 service.dump(fd, args); 1185 return true; 1186 } catch (RemoteException e) { 1187 Log.e(TAG, "Can't dump service: " + name, e); 1188 return false; 1189 } 1190 } 1191} 1192