Debug.java revision 8e69257a9c7e9c1781e1f53d8856358ada38921d
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.FastPrintWriter; 20import com.android.internal.util.TypedProperties; 21 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 methods 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.getLegacyExternalStorageDirectory().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 heap. (Doesn't include other Dalvik overhead.) */ 113 public int dalvikPss; 114 /** The proportional set size that is swappable for dalvik heap. */ 115 /** @hide We may want to expose this, eventually. */ 116 public int dalvikSwappablePss; 117 /** The private dirty pages used by dalvik heap. */ 118 public int dalvikPrivateDirty; 119 /** The shared dirty pages used by dalvik heap. */ 120 public int dalvikSharedDirty; 121 /** The private clean pages used by dalvik heap. */ 122 /** @hide We may want to expose this, eventually. */ 123 public int dalvikPrivateClean; 124 /** The shared clean pages used by dalvik heap. */ 125 /** @hide We may want to expose this, eventually. */ 126 public int dalvikSharedClean; 127 128 /** The proportional set size for the native heap. */ 129 public int nativePss; 130 /** The proportional set size that is swappable for the native heap. */ 131 /** @hide We may want to expose this, eventually. */ 132 public int nativeSwappablePss; 133 /** The private dirty pages used by the native heap. */ 134 public int nativePrivateDirty; 135 /** The shared dirty pages used by the native heap. */ 136 public int nativeSharedDirty; 137 /** The private clean pages used by the native heap. */ 138 /** @hide We may want to expose this, eventually. */ 139 public int nativePrivateClean; 140 /** The shared clean pages used by the native heap. */ 141 /** @hide We may want to expose this, eventually. */ 142 public int nativeSharedClean; 143 144 /** The proportional set size for everything else. */ 145 public int otherPss; 146 /** The proportional set size that is swappable for everything else. */ 147 /** @hide We may want to expose this, eventually. */ 148 public int otherSwappablePss; 149 /** The private dirty pages used by everything else. */ 150 public int otherPrivateDirty; 151 /** The shared dirty pages used by everything else. */ 152 public int otherSharedDirty; 153 /** The private clean pages used by everything else. */ 154 /** @hide We may want to expose this, eventually. */ 155 public int otherPrivateClean; 156 /** The shared clean pages used by everything else. */ 157 /** @hide We may want to expose this, eventually. */ 158 public int otherSharedClean; 159 160 /** @hide */ 161 public static final int NUM_OTHER_STATS = 14; 162 163 /** @hide */ 164 public static final int NUM_DVK_STATS = 5; 165 166 /** @hide */ 167 public static final int NUM_CATEGORIES = 6; 168 169 /** @hide */ 170 public static final int offsetPss = 0; 171 /** @hide */ 172 public static final int offsetSwappablePss = 1; 173 /** @hide */ 174 public static final int offsetPrivateDirty = 2; 175 /** @hide */ 176 public static final int offsetSharedDirty = 3; 177 /** @hide */ 178 public static final int offsetPrivateClean = 4; 179 /** @hide */ 180 public static final int offsetSharedClean = 5; 181 182 183 private int[] otherStats = new int[(NUM_OTHER_STATS+NUM_DVK_STATS)*NUM_CATEGORIES]; 184 185 public MemoryInfo() { 186 } 187 188 /** 189 * Return total PSS memory usage in kB. 190 */ 191 public int getTotalPss() { 192 return dalvikPss + nativePss + otherPss; 193 } 194 195 /** 196 * @hide Return total PSS memory usage in kB. 197 */ 198 public int getTotalUss() { 199 return dalvikPrivateClean + dalvikPrivateDirty 200 + nativePrivateClean + nativePrivateDirty 201 + otherPrivateClean + otherPrivateDirty; 202 } 203 204 /** 205 * Return total PSS memory usage in kB. 206 */ 207 public int getTotalSwappablePss() { 208 return dalvikSwappablePss + nativeSwappablePss + otherSwappablePss; 209 } 210 211 /** 212 * Return total private dirty memory usage in kB. 213 */ 214 public int getTotalPrivateDirty() { 215 return dalvikPrivateDirty + nativePrivateDirty + otherPrivateDirty; 216 } 217 218 /** 219 * Return total shared dirty memory usage in kB. 220 */ 221 public int getTotalSharedDirty() { 222 return dalvikSharedDirty + nativeSharedDirty + otherSharedDirty; 223 } 224 225 /** 226 * Return total shared clean memory usage in kB. 227 */ 228 public int getTotalPrivateClean() { 229 return dalvikPrivateClean + nativePrivateClean + otherPrivateClean; 230 } 231 232 /** 233 * Return total shared clean memory usage in kB. 234 */ 235 public int getTotalSharedClean() { 236 return dalvikSharedClean + nativeSharedClean + otherSharedClean; 237 } 238 239 /* @hide */ 240 public int getOtherPss(int which) { 241 return otherStats[which*NUM_CATEGORIES + offsetPss]; 242 } 243 244 245 /* @hide */ 246 public int getOtherSwappablePss(int which) { 247 return otherStats[which*NUM_CATEGORIES + offsetSwappablePss]; 248 } 249 250 251 /* @hide */ 252 public int getOtherPrivateDirty(int which) { 253 return otherStats[which*NUM_CATEGORIES + offsetPrivateDirty]; 254 } 255 256 /* @hide */ 257 public int getOtherSharedDirty(int which) { 258 return otherStats[which*NUM_CATEGORIES + offsetSharedDirty]; 259 } 260 261 /* @hide */ 262 public int getOtherPrivateClean(int which) { 263 return otherStats[which*NUM_CATEGORIES + offsetPrivateClean]; 264 } 265 266 267 /* @hide */ 268 public int getOtherSharedClean(int which) { 269 return otherStats[which*NUM_CATEGORIES + offsetSharedClean]; 270 } 271 272 /* @hide */ 273 public static String getOtherLabel(int which) { 274 switch (which) { 275 case 0: return "Dalvik Other"; 276 case 1: return "Stack"; 277 case 2: return "Cursor"; 278 case 3: return "Ashmem"; 279 case 4: return "Other dev"; 280 case 5: return ".so mmap"; 281 case 6: return ".jar mmap"; 282 case 7: return ".apk mmap"; 283 case 8: return ".ttf mmap"; 284 case 9: return ".dex mmap"; 285 case 10: return "code mmap"; 286 case 11: return "image mmap"; 287 case 12: return "Other mmap"; 288 case 13: return "GPU"; 289 case 14: return ".Heap"; 290 case 15: return ".LOS"; 291 case 16: return ".LinearAlloc"; 292 case 17: return ".GC"; 293 case 18: return ".JITCache"; 294 default: return "????"; 295 } 296 } 297 298 public int describeContents() { 299 return 0; 300 } 301 302 public void writeToParcel(Parcel dest, int flags) { 303 dest.writeInt(dalvikPss); 304 dest.writeInt(dalvikSwappablePss); 305 dest.writeInt(dalvikPrivateDirty); 306 dest.writeInt(dalvikSharedDirty); 307 dest.writeInt(dalvikPrivateClean); 308 dest.writeInt(dalvikSharedClean); 309 dest.writeInt(nativePss); 310 dest.writeInt(nativeSwappablePss); 311 dest.writeInt(nativePrivateDirty); 312 dest.writeInt(nativeSharedDirty); 313 dest.writeInt(nativePrivateClean); 314 dest.writeInt(nativeSharedClean); 315 dest.writeInt(otherPss); 316 dest.writeInt(otherSwappablePss); 317 dest.writeInt(otherPrivateDirty); 318 dest.writeInt(otherSharedDirty); 319 dest.writeInt(otherPrivateClean); 320 dest.writeInt(otherSharedClean); 321 dest.writeIntArray(otherStats); 322 } 323 324 public void readFromParcel(Parcel source) { 325 dalvikPss = source.readInt(); 326 dalvikSwappablePss = source.readInt(); 327 dalvikPrivateDirty = source.readInt(); 328 dalvikSharedDirty = source.readInt(); 329 dalvikPrivateClean = source.readInt(); 330 dalvikSharedClean = source.readInt(); 331 nativePss = source.readInt(); 332 nativeSwappablePss = source.readInt(); 333 nativePrivateDirty = source.readInt(); 334 nativeSharedDirty = source.readInt(); 335 nativePrivateClean = source.readInt(); 336 nativeSharedClean = source.readInt(); 337 otherPss = source.readInt(); 338 otherSwappablePss = source.readInt(); 339 otherPrivateDirty = source.readInt(); 340 otherSharedDirty = source.readInt(); 341 otherPrivateClean = source.readInt(); 342 otherSharedClean = source.readInt(); 343 otherStats = source.createIntArray(); 344 } 345 346 public static final Creator<MemoryInfo> CREATOR = new Creator<MemoryInfo>() { 347 public MemoryInfo createFromParcel(Parcel source) { 348 return new MemoryInfo(source); 349 } 350 public MemoryInfo[] newArray(int size) { 351 return new MemoryInfo[size]; 352 } 353 }; 354 355 private MemoryInfo(Parcel source) { 356 readFromParcel(source); 357 } 358 } 359 360 361 /** 362 * Wait until a debugger attaches. As soon as the debugger attaches, 363 * this returns, so you will need to place a breakpoint after the 364 * waitForDebugger() call if you want to start tracing immediately. 365 */ 366 public static void waitForDebugger() { 367 if (!VMDebug.isDebuggingEnabled()) { 368 //System.out.println("debugging not enabled, not waiting"); 369 return; 370 } 371 if (isDebuggerConnected()) 372 return; 373 374 // if DDMS is listening, inform them of our plight 375 System.out.println("Sending WAIT chunk"); 376 byte[] data = new byte[] { 0 }; // 0 == "waiting for debugger" 377 Chunk waitChunk = new Chunk(ChunkHandler.type("WAIT"), data, 0, 1); 378 DdmServer.sendChunk(waitChunk); 379 380 mWaiting = true; 381 while (!isDebuggerConnected()) { 382 try { Thread.sleep(SPIN_DELAY); } 383 catch (InterruptedException ie) {} 384 } 385 mWaiting = false; 386 387 System.out.println("Debugger has connected"); 388 389 /* 390 * There is no "ready to go" signal from the debugger, and we're 391 * not allowed to suspend ourselves -- the debugger expects us to 392 * be running happily, and gets confused if we aren't. We need to 393 * allow the debugger a chance to set breakpoints before we start 394 * running again. 395 * 396 * Sit and spin until the debugger has been idle for a short while. 397 */ 398 while (true) { 399 long delta = VMDebug.lastDebuggerActivity(); 400 if (delta < 0) { 401 System.out.println("debugger detached?"); 402 break; 403 } 404 405 if (delta < MIN_DEBUGGER_IDLE) { 406 System.out.println("waiting for debugger to settle..."); 407 try { Thread.sleep(SPIN_DELAY); } 408 catch (InterruptedException ie) {} 409 } else { 410 System.out.println("debugger has settled (" + delta + ")"); 411 break; 412 } 413 } 414 } 415 416 /** 417 * Returns "true" if one or more threads is waiting for a debugger 418 * to attach. 419 */ 420 public static boolean waitingForDebugger() { 421 return mWaiting; 422 } 423 424 /** 425 * Determine if a debugger is currently attached. 426 */ 427 public static boolean isDebuggerConnected() { 428 return VMDebug.isDebuggerConnected(); 429 } 430 431 /** 432 * Returns an array of strings that identify VM features. This is 433 * used by DDMS to determine what sorts of operations the VM can 434 * perform. 435 * 436 * @hide 437 */ 438 public static String[] getVmFeatureList() { 439 return VMDebug.getVmFeatureList(); 440 } 441 442 /** 443 * Change the JDWP port. 444 * 445 * @deprecated no longer needed or useful 446 */ 447 @Deprecated 448 public static void changeDebugPort(int port) {} 449 450 /** 451 * This is the pathname to the sysfs file that enables and disables 452 * tracing on the qemu emulator. 453 */ 454 private static final String SYSFS_QEMU_TRACE_STATE = "/sys/qemu_trace/state"; 455 456 /** 457 * Enable qemu tracing. For this to work requires running everything inside 458 * the qemu emulator; otherwise, this method will have no effect. The trace 459 * file is specified on the command line when the emulator is started. For 460 * example, the following command line <br /> 461 * <code>emulator -trace foo</code><br /> 462 * will start running the emulator and create a trace file named "foo". This 463 * method simply enables writing the trace records to the trace file. 464 * 465 * <p> 466 * The main differences between this and {@link #startMethodTracing()} are 467 * that tracing in the qemu emulator traces every cpu instruction of every 468 * process, including kernel code, so we have more complete information, 469 * including all context switches. We can also get more detailed information 470 * such as cache misses. The sequence of calls is determined by 471 * post-processing the instruction trace. The qemu tracing is also done 472 * without modifying the application or perturbing the timing of calls 473 * because no instrumentation is added to the application being traced. 474 * </p> 475 * 476 * <p> 477 * One limitation of using this method compared to using 478 * {@link #startMethodTracing()} on the real device is that the emulator 479 * does not model all of the real hardware effects such as memory and 480 * bus contention. The emulator also has a simple cache model and cannot 481 * capture all the complexities of a real cache. 482 * </p> 483 */ 484 public static void startNativeTracing() { 485 // Open the sysfs file for writing and write "1" to it. 486 PrintWriter outStream = null; 487 try { 488 FileOutputStream fos = new FileOutputStream(SYSFS_QEMU_TRACE_STATE); 489 outStream = new FastPrintWriter(fos); 490 outStream.println("1"); 491 } catch (Exception e) { 492 } finally { 493 if (outStream != null) 494 outStream.close(); 495 } 496 497 VMDebug.startEmulatorTracing(); 498 } 499 500 /** 501 * Stop qemu tracing. See {@link #startNativeTracing()} to start tracing. 502 * 503 * <p>Tracing can be started and stopped as many times as desired. When 504 * the qemu emulator itself is stopped then the buffered trace records 505 * are flushed and written to the trace file. In fact, it is not necessary 506 * to call this method at all; simply killing qemu is sufficient. But 507 * starting and stopping a trace is useful for examining a specific 508 * region of code.</p> 509 */ 510 public static void stopNativeTracing() { 511 VMDebug.stopEmulatorTracing(); 512 513 // Open the sysfs file for writing and write "0" to it. 514 PrintWriter outStream = null; 515 try { 516 FileOutputStream fos = new FileOutputStream(SYSFS_QEMU_TRACE_STATE); 517 outStream = new FastPrintWriter(fos); 518 outStream.println("0"); 519 } catch (Exception e) { 520 // We could print an error message here but we probably want 521 // to quietly ignore errors if we are not running in the emulator. 522 } finally { 523 if (outStream != null) 524 outStream.close(); 525 } 526 } 527 528 /** 529 * Enable "emulator traces", in which information about the current 530 * method is made available to the "emulator -trace" feature. There 531 * is no corresponding "disable" call -- this is intended for use by 532 * the framework when tracing should be turned on and left that way, so 533 * that traces captured with F9/F10 will include the necessary data. 534 * 535 * This puts the VM into "profile" mode, which has performance 536 * consequences. 537 * 538 * To temporarily enable tracing, use {@link #startNativeTracing()}. 539 */ 540 public static void enableEmulatorTraceOutput() { 541 VMDebug.startEmulatorTracing(); 542 } 543 544 /** 545 * Start method tracing with default log name and buffer size. See <a 546href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 547 * information about reading these files. Call stopMethodTracing() to stop 548 * tracing. 549 */ 550 public static void startMethodTracing() { 551 VMDebug.startMethodTracing(DEFAULT_TRACE_FILE_PATH, 0, 0); 552 } 553 554 /** 555 * Start method tracing, specifying the trace log file name. The trace 556 * file will be put under "/sdcard" unless an absolute path is given. 557 * See <a 558 href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 559 * information about reading trace files. 560 * 561 * @param traceName Name for the trace log file to create. 562 * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". 563 * If the files already exist, they will be truncated. 564 * If the trace file given does not end in ".trace", it will be appended for you. 565 */ 566 public static void startMethodTracing(String traceName) { 567 startMethodTracing(traceName, 0, 0); 568 } 569 570 /** 571 * Start method tracing, specifying the trace log file name and the 572 * buffer size. The trace files will be put under "/sdcard" unless an 573 * absolute path is given. See <a 574 href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 575 * information about reading trace files. 576 * @param traceName Name for the trace log file to create. 577 * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". 578 * If the files already exist, they will be truncated. 579 * If the trace file given does not end in ".trace", it will be appended for you. 580 * 581 * @param bufferSize The maximum amount of trace data we gather. If not given, it defaults to 8MB. 582 */ 583 public static void startMethodTracing(String traceName, int bufferSize) { 584 startMethodTracing(traceName, bufferSize, 0); 585 } 586 587 /** 588 * Start method tracing, specifying the trace log file name and the 589 * buffer size. The trace files will be put under "/sdcard" unless an 590 * absolute path is given. See <a 591 href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for 592 * information about reading trace files. 593 * 594 * <p> 595 * When method tracing is enabled, the VM will run more slowly than 596 * usual, so the timings from the trace files should only be considered 597 * in relative terms (e.g. was run #1 faster than run #2). The times 598 * for native methods will not change, so don't try to use this to 599 * compare the performance of interpreted and native implementations of the 600 * same method. As an alternative, consider using "native" tracing 601 * in the emulator via {@link #startNativeTracing()}. 602 * </p> 603 * 604 * @param traceName Name for the trace log file to create. 605 * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". 606 * If the files already exist, they will be truncated. 607 * If the trace file given does not end in ".trace", it will be appended for you. 608 * @param bufferSize The maximum amount of trace data we gather. If not given, it defaults to 8MB. 609 */ 610 public static void startMethodTracing(String traceName, int bufferSize, 611 int flags) { 612 613 String pathName = traceName; 614 if (pathName.charAt(0) != '/') 615 pathName = DEFAULT_TRACE_PATH_PREFIX + pathName; 616 if (!pathName.endsWith(DEFAULT_TRACE_EXTENSION)) 617 pathName = pathName + DEFAULT_TRACE_EXTENSION; 618 619 VMDebug.startMethodTracing(pathName, bufferSize, flags); 620 } 621 622 /** 623 * Like startMethodTracing(String, int, int), but taking an already-opened 624 * FileDescriptor in which the trace is written. The file name is also 625 * supplied simply for logging. Makes a dup of the file descriptor. 626 * 627 * Not exposed in the SDK unless we are really comfortable with supporting 628 * this and find it would be useful. 629 * @hide 630 */ 631 public static void startMethodTracing(String traceName, FileDescriptor fd, 632 int bufferSize, int flags) { 633 VMDebug.startMethodTracing(traceName, fd, bufferSize, flags); 634 } 635 636 /** 637 * Starts method tracing without a backing file. When stopMethodTracing 638 * is called, the result is sent directly to DDMS. (If DDMS is not 639 * attached when tracing ends, the profiling data will be discarded.) 640 * 641 * @hide 642 */ 643 public static void startMethodTracingDdms(int bufferSize, int flags, 644 boolean samplingEnabled, int intervalUs) { 645 VMDebug.startMethodTracingDdms(bufferSize, flags, samplingEnabled, intervalUs); 646 } 647 648 /** 649 * Determine whether method tracing is currently active and what type is 650 * active. 651 * 652 * @hide 653 */ 654 public static int getMethodTracingMode() { 655 return VMDebug.getMethodTracingMode(); 656 } 657 658 /** 659 * Stop method tracing. 660 */ 661 public static void stopMethodTracing() { 662 VMDebug.stopMethodTracing(); 663 } 664 665 /** 666 * Get an indication of thread CPU usage. The value returned 667 * indicates the amount of time that the current thread has spent 668 * executing code or waiting for certain types of I/O. 669 * 670 * The time is expressed in nanoseconds, and is only meaningful 671 * when compared to the result from an earlier call. Note that 672 * nanosecond resolution does not imply nanosecond accuracy. 673 * 674 * On system which don't support this operation, the call returns -1. 675 */ 676 public static long threadCpuTimeNanos() { 677 return VMDebug.threadCpuTimeNanos(); 678 } 679 680 /** 681 * Start counting the number and aggregate size of memory allocations. 682 * 683 * <p>The {@link #startAllocCounting() start} method resets the counts and enables counting. 684 * The {@link #stopAllocCounting() stop} method disables the counting so that the analysis 685 * code doesn't cause additional allocations. The various <code>get</code> methods return 686 * the specified value. And the various <code>reset</code> methods reset the specified 687 * count.</p> 688 * 689 * <p>Counts are kept for the system as a whole (global) and for each thread. 690 * The per-thread counts for threads other than the current thread 691 * are not cleared by the "reset" or "start" calls.</p> 692 * 693 * @deprecated Accurate counting is a burden on the runtime and may be removed. 694 */ 695 @Deprecated 696 public static void startAllocCounting() { 697 VMDebug.startAllocCounting(); 698 } 699 700 /** 701 * Stop counting the number and aggregate size of memory allocations. 702 * 703 * @see #startAllocCounting() 704 */ 705 @Deprecated 706 public static void stopAllocCounting() { 707 VMDebug.stopAllocCounting(); 708 } 709 710 /** 711 * Returns the global count of objects allocated by the runtime between a 712 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 713 */ 714 public static int getGlobalAllocCount() { 715 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_OBJECTS); 716 } 717 718 /** 719 * Clears the global count of objects allocated. 720 * @see #getGlobalAllocCount() 721 */ 722 public static void resetGlobalAllocCount() { 723 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_OBJECTS); 724 } 725 726 /** 727 * Returns the global size, in bytes, of objects allocated by the runtime between a 728 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 729 */ 730 public static int getGlobalAllocSize() { 731 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_BYTES); 732 } 733 734 /** 735 * Clears the global size of objects allocated. 736 * @see #getGlobalAllocCountSize() 737 */ 738 public static void resetGlobalAllocSize() { 739 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_BYTES); 740 } 741 742 /** 743 * Returns the global count of objects freed by the runtime between a 744 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 745 */ 746 public static int getGlobalFreedCount() { 747 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_FREED_OBJECTS); 748 } 749 750 /** 751 * Clears the global count of objects freed. 752 * @see #getGlobalFreedCount() 753 */ 754 public static void resetGlobalFreedCount() { 755 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_FREED_OBJECTS); 756 } 757 758 /** 759 * Returns the global size, in bytes, of objects freed by the runtime between a 760 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 761 */ 762 public static int getGlobalFreedSize() { 763 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_FREED_BYTES); 764 } 765 766 /** 767 * Clears the global size of objects freed. 768 * @see #getGlobalFreedSize() 769 */ 770 public static void resetGlobalFreedSize() { 771 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_FREED_BYTES); 772 } 773 774 /** 775 * Returns the number of non-concurrent GC invocations between a 776 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 777 */ 778 public static int getGlobalGcInvocationCount() { 779 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_GC_INVOCATIONS); 780 } 781 782 /** 783 * Clears the count of non-concurrent GC invocations. 784 * @see #getGlobalGcInvocationCount() 785 */ 786 public static void resetGlobalGcInvocationCount() { 787 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_GC_INVOCATIONS); 788 } 789 790 /** 791 * Returns the number of classes successfully initialized (ie those that executed without 792 * throwing an exception) between a {@link #startAllocCounting() start} and 793 * {@link #stopAllocCounting() stop}. 794 */ 795 public static int getGlobalClassInitCount() { 796 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_COUNT); 797 } 798 799 /** 800 * Clears the count of classes initialized. 801 * @see #getGlobalClassInitCount() 802 */ 803 public static void resetGlobalClassInitCount() { 804 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_COUNT); 805 } 806 807 /** 808 * Returns the time spent successfully initializing classes between a 809 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 810 */ 811 public static int getGlobalClassInitTime() { 812 /* cumulative elapsed time for class initialization, in usec */ 813 return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_TIME); 814 } 815 816 /** 817 * Clears the count of time spent initializing classes. 818 * @see #getGlobalClassInitTime() 819 */ 820 public static void resetGlobalClassInitTime() { 821 VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_TIME); 822 } 823 824 /** 825 * This method exists for compatibility and always returns 0. 826 * @deprecated This method is now obsolete. 827 */ 828 @Deprecated 829 public static int getGlobalExternalAllocCount() { 830 return 0; 831 } 832 833 /** 834 * This method exists for compatibility and has no effect. 835 * @deprecated This method is now obsolete. 836 */ 837 @Deprecated 838 public static void resetGlobalExternalAllocSize() {} 839 840 /** 841 * This method exists for compatibility and has no effect. 842 * @deprecated This method is now obsolete. 843 */ 844 @Deprecated 845 public static void resetGlobalExternalAllocCount() {} 846 847 /** 848 * This method exists for compatibility and always returns 0. 849 * @deprecated This method is now obsolete. 850 */ 851 @Deprecated 852 public static int getGlobalExternalAllocSize() { 853 return 0; 854 } 855 856 /** 857 * This method exists for compatibility and always returns 0. 858 * @deprecated This method is now obsolete. 859 */ 860 @Deprecated 861 public static int getGlobalExternalFreedCount() { 862 return 0; 863 } 864 865 /** 866 * This method exists for compatibility and has no effect. 867 * @deprecated This method is now obsolete. 868 */ 869 @Deprecated 870 public static void resetGlobalExternalFreedCount() {} 871 872 /** 873 * This method exists for compatibility and has no effect. 874 * @deprecated This method is now obsolete. 875 */ 876 @Deprecated 877 public static int getGlobalExternalFreedSize() { 878 return 0; 879 } 880 881 /** 882 * This method exists for compatibility and has no effect. 883 * @deprecated This method is now obsolete. 884 */ 885 @Deprecated 886 public static void resetGlobalExternalFreedSize() {} 887 888 /** 889 * Returns the thread-local count of objects allocated by the runtime between a 890 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 891 */ 892 public static int getThreadAllocCount() { 893 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_ALLOCATED_OBJECTS); 894 } 895 896 /** 897 * Clears the thread-local count of objects allocated. 898 * @see #getThreadAllocCount() 899 */ 900 public static void resetThreadAllocCount() { 901 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_ALLOCATED_OBJECTS); 902 } 903 904 /** 905 * Returns the thread-local size of objects allocated by the runtime between a 906 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 907 * @return The allocated size in bytes. 908 */ 909 public static int getThreadAllocSize() { 910 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_ALLOCATED_BYTES); 911 } 912 913 /** 914 * Clears the thread-local count of objects allocated. 915 * @see #getThreadAllocSize() 916 */ 917 public static void resetThreadAllocSize() { 918 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_ALLOCATED_BYTES); 919 } 920 921 /** 922 * This method exists for compatibility and has no effect. 923 * @deprecated This method is now obsolete. 924 */ 925 @Deprecated 926 public static int getThreadExternalAllocCount() { 927 return 0; 928 } 929 930 /** 931 * This method exists for compatibility and has no effect. 932 * @deprecated This method is now obsolete. 933 */ 934 @Deprecated 935 public static void resetThreadExternalAllocCount() {} 936 937 /** 938 * This method exists for compatibility and has no effect. 939 * @deprecated This method is now obsolete. 940 */ 941 @Deprecated 942 public static int getThreadExternalAllocSize() { 943 return 0; 944 } 945 946 /** 947 * This method exists for compatibility and has no effect. 948 * @deprecated This method is now obsolete. 949 */ 950 @Deprecated 951 public static void resetThreadExternalAllocSize() {} 952 953 /** 954 * Returns the number of thread-local non-concurrent GC invocations between a 955 * {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}. 956 */ 957 public static int getThreadGcInvocationCount() { 958 return VMDebug.getAllocCount(VMDebug.KIND_THREAD_GC_INVOCATIONS); 959 } 960 961 /** 962 * Clears the thread-local count of non-concurrent GC invocations. 963 * @see #getThreadGcInvocationCount() 964 */ 965 public static void resetThreadGcInvocationCount() { 966 VMDebug.resetAllocCount(VMDebug.KIND_THREAD_GC_INVOCATIONS); 967 } 968 969 /** 970 * Clears all the global and thread-local memory allocation counters. 971 * @see #startAllocCounting() 972 */ 973 public static void resetAllCounts() { 974 VMDebug.resetAllocCount(VMDebug.KIND_ALL_COUNTS); 975 } 976 977 /** 978 * Returns the size of the native heap. 979 * @return The size of the native heap in bytes. 980 */ 981 public static native long getNativeHeapSize(); 982 983 /** 984 * Returns the amount of allocated memory in the native heap. 985 * @return The allocated size in bytes. 986 */ 987 public static native long getNativeHeapAllocatedSize(); 988 989 /** 990 * Returns the amount of free memory in the native heap. 991 * @return The freed size in bytes. 992 */ 993 public static native long getNativeHeapFreeSize(); 994 995 /** 996 * Retrieves information about this processes memory usages. This information is broken down by 997 * how much is in use by dalivk, the native heap, and everything else. 998 */ 999 public static native void getMemoryInfo(MemoryInfo memoryInfo); 1000 1001 /** 1002 * Note: currently only works when the requested pid has the same UID 1003 * as the caller. 1004 * @hide 1005 */ 1006 public static native void getMemoryInfo(int pid, MemoryInfo memoryInfo); 1007 1008 /** 1009 * Retrieves the PSS memory used by the process as given by the 1010 * smaps. 1011 */ 1012 public static native long getPss(); 1013 1014 /** 1015 * Retrieves the PSS memory used by the process as given by the 1016 * smaps. Optionally supply a long array of 1 entry to also 1017 * receive the uss of the process. @hide 1018 */ 1019 public static native long getPss(int pid, long[] outUss); 1020 1021 /** @hide */ 1022 public static final int MEMINFO_TOTAL = 0; 1023 /** @hide */ 1024 public static final int MEMINFO_FREE = 1; 1025 /** @hide */ 1026 public static final int MEMINFO_BUFFERS = 2; 1027 /** @hide */ 1028 public static final int MEMINFO_CACHED = 3; 1029 /** @hide */ 1030 public static final int MEMINFO_SHMEM = 4; 1031 /** @hide */ 1032 public static final int MEMINFO_SLAB = 5; 1033 /** @hide */ 1034 public static final int MEMINFO_COUNT = 6; 1035 1036 /** 1037 * Retrieves /proc/meminfo. outSizes is filled with fields 1038 * as defined by MEMINFO_* offsets. 1039 * @hide 1040 */ 1041 public static native void getMemInfo(long[] outSizes); 1042 1043 /** 1044 * Establish an object allocation limit in the current thread. 1045 * This feature was never enabled in release builds. The 1046 * allocation limits feature was removed in Honeycomb. This 1047 * method exists for compatibility and always returns -1 and has 1048 * no effect. 1049 * 1050 * @deprecated This method is now obsolete. 1051 */ 1052 @Deprecated 1053 public static int setAllocationLimit(int limit) { 1054 return -1; 1055 } 1056 1057 /** 1058 * Establish a global object allocation limit. This feature was 1059 * never enabled in release builds. The allocation limits feature 1060 * was removed in Honeycomb. This method exists for compatibility 1061 * and always returns -1 and has no effect. 1062 * 1063 * @deprecated This method is now obsolete. 1064 */ 1065 @Deprecated 1066 public static int setGlobalAllocationLimit(int limit) { 1067 return -1; 1068 } 1069 1070 /** 1071 * Dump a list of all currently loaded class to the log file. 1072 * 1073 * @param flags See constants above. 1074 */ 1075 public static void printLoadedClasses(int flags) { 1076 VMDebug.printLoadedClasses(flags); 1077 } 1078 1079 /** 1080 * Get the number of loaded classes. 1081 * @return the number of loaded classes. 1082 */ 1083 public static int getLoadedClassCount() { 1084 return VMDebug.getLoadedClassCount(); 1085 } 1086 1087 /** 1088 * Dump "hprof" data to the specified file. This may cause a GC. 1089 * 1090 * @param fileName Full pathname of output file (e.g. "/sdcard/dump.hprof"). 1091 * @throws UnsupportedOperationException if the VM was built without 1092 * HPROF support. 1093 * @throws IOException if an error occurs while opening or writing files. 1094 */ 1095 public static void dumpHprofData(String fileName) throws IOException { 1096 VMDebug.dumpHprofData(fileName); 1097 } 1098 1099 /** 1100 * Like dumpHprofData(String), but takes an already-opened 1101 * FileDescriptor to which the trace is written. The file name is also 1102 * supplied simply for logging. Makes a dup of the file descriptor. 1103 * 1104 * Primarily for use by the "am" shell command. 1105 * 1106 * @hide 1107 */ 1108 public static void dumpHprofData(String fileName, FileDescriptor fd) 1109 throws IOException { 1110 VMDebug.dumpHprofData(fileName, fd); 1111 } 1112 1113 /** 1114 * Collect "hprof" and send it to DDMS. This may cause a GC. 1115 * 1116 * @throws UnsupportedOperationException if the VM was built without 1117 * HPROF support. 1118 * @hide 1119 */ 1120 public static void dumpHprofDataDdms() { 1121 VMDebug.dumpHprofDataDdms(); 1122 } 1123 1124 /** 1125 * Writes native heap data to the specified file descriptor. 1126 * 1127 * @hide 1128 */ 1129 public static native void dumpNativeHeap(FileDescriptor fd); 1130 1131 /** 1132 * Returns a count of the extant instances of a class. 1133 * 1134 * @hide 1135 */ 1136 public static long countInstancesOfClass(Class cls) { 1137 return VMDebug.countInstancesOfClass(cls, true); 1138 } 1139 1140 /** 1141 * Returns the number of sent transactions from this process. 1142 * @return The number of sent transactions or -1 if it could not read t. 1143 */ 1144 public static native int getBinderSentTransactions(); 1145 1146 /** 1147 * Returns the number of received transactions from the binder driver. 1148 * @return The number of received transactions or -1 if it could not read the stats. 1149 */ 1150 public static native int getBinderReceivedTransactions(); 1151 1152 /** 1153 * Returns the number of active local Binder objects that exist in the 1154 * current process. 1155 */ 1156 public static final native int getBinderLocalObjectCount(); 1157 1158 /** 1159 * Returns the number of references to remote proxy Binder objects that 1160 * exist in the current process. 1161 */ 1162 public static final native int getBinderProxyObjectCount(); 1163 1164 /** 1165 * Returns the number of death notification links to Binder objects that 1166 * exist in the current process. 1167 */ 1168 public static final native int getBinderDeathObjectCount(); 1169 1170 /** 1171 * Primes the register map cache. 1172 * 1173 * Only works for classes in the bootstrap class loader. Does not 1174 * cause classes to be loaded if they're not already present. 1175 * 1176 * The classAndMethodDesc argument is a concatentation of the VM-internal 1177 * class descriptor, method name, and method descriptor. Examples: 1178 * Landroid/os/Looper;.loop:()V 1179 * Landroid/app/ActivityThread;.main:([Ljava/lang/String;)V 1180 * 1181 * @param classAndMethodDesc the method to prepare 1182 * 1183 * @hide 1184 */ 1185 public static final boolean cacheRegisterMap(String classAndMethodDesc) { 1186 return VMDebug.cacheRegisterMap(classAndMethodDesc); 1187 } 1188 1189 /** 1190 * Dumps the contents of VM reference tables (e.g. JNI locals and 1191 * globals) to the log file. 1192 * 1193 * @hide 1194 */ 1195 public static final void dumpReferenceTables() { 1196 VMDebug.dumpReferenceTables(); 1197 } 1198 1199 /** 1200 * API for gathering and querying instruction counts. 1201 * 1202 * Example usage: 1203 * <pre> 1204 * Debug.InstructionCount icount = new Debug.InstructionCount(); 1205 * icount.resetAndStart(); 1206 * [... do lots of stuff ...] 1207 * if (icount.collect()) { 1208 * System.out.println("Total instructions executed: " 1209 * + icount.globalTotal()); 1210 * System.out.println("Method invocations: " 1211 * + icount.globalMethodInvocations()); 1212 * } 1213 * </pre> 1214 */ 1215 public static class InstructionCount { 1216 private static final int NUM_INSTR = 1217 OpcodeInfo.MAXIMUM_PACKED_VALUE + 1; 1218 1219 private int[] mCounts; 1220 1221 public InstructionCount() { 1222 mCounts = new int[NUM_INSTR]; 1223 } 1224 1225 /** 1226 * Reset counters and ensure counts are running. Counts may 1227 * have already been running. 1228 * 1229 * @return true if counting was started 1230 */ 1231 public boolean resetAndStart() { 1232 try { 1233 VMDebug.startInstructionCounting(); 1234 VMDebug.resetInstructionCount(); 1235 } catch (UnsupportedOperationException uoe) { 1236 return false; 1237 } 1238 return true; 1239 } 1240 1241 /** 1242 * Collect instruction counts. May or may not stop the 1243 * counting process. 1244 */ 1245 public boolean collect() { 1246 try { 1247 VMDebug.stopInstructionCounting(); 1248 VMDebug.getInstructionCount(mCounts); 1249 } catch (UnsupportedOperationException uoe) { 1250 return false; 1251 } 1252 return true; 1253 } 1254 1255 /** 1256 * Return the total number of instructions executed globally (i.e. in 1257 * all threads). 1258 */ 1259 public int globalTotal() { 1260 int count = 0; 1261 1262 for (int i = 0; i < NUM_INSTR; i++) { 1263 count += mCounts[i]; 1264 } 1265 1266 return count; 1267 } 1268 1269 /** 1270 * Return the total number of method-invocation instructions 1271 * executed globally. 1272 */ 1273 public int globalMethodInvocations() { 1274 int count = 0; 1275 1276 for (int i = 0; i < NUM_INSTR; i++) { 1277 if (OpcodeInfo.isInvoke(i)) { 1278 count += mCounts[i]; 1279 } 1280 } 1281 1282 return count; 1283 } 1284 } 1285 1286 /** 1287 * A Map of typed debug properties. 1288 */ 1289 private static final TypedProperties debugProperties; 1290 1291 /* 1292 * Load the debug properties from the standard files into debugProperties. 1293 */ 1294 static { 1295 if (false) { 1296 final String TAG = "DebugProperties"; 1297 final String[] files = { "/system/debug.prop", "/debug.prop", "/data/debug.prop" }; 1298 final TypedProperties tp = new TypedProperties(); 1299 1300 // Read the properties from each of the files, if present. 1301 for (String file : files) { 1302 Reader r; 1303 try { 1304 r = new FileReader(file); 1305 } catch (FileNotFoundException ex) { 1306 // It's ok if a file is missing. 1307 continue; 1308 } 1309 1310 try { 1311 tp.load(r); 1312 } catch (Exception ex) { 1313 throw new RuntimeException("Problem loading " + file, ex); 1314 } finally { 1315 try { 1316 r.close(); 1317 } catch (IOException ex) { 1318 // Ignore this error. 1319 } 1320 } 1321 } 1322 1323 debugProperties = tp.isEmpty() ? null : tp; 1324 } else { 1325 debugProperties = null; 1326 } 1327 } 1328 1329 1330 /** 1331 * Returns true if the type of the field matches the specified class. 1332 * Handles the case where the class is, e.g., java.lang.Boolean, but 1333 * the field is of the primitive "boolean" type. Also handles all of 1334 * the java.lang.Number subclasses. 1335 */ 1336 private static boolean fieldTypeMatches(Field field, Class<?> cl) { 1337 Class<?> fieldClass = field.getType(); 1338 if (fieldClass == cl) { 1339 return true; 1340 } 1341 Field primitiveTypeField; 1342 try { 1343 /* All of the classes we care about (Boolean, Integer, etc.) 1344 * have a Class field called "TYPE" that points to the corresponding 1345 * primitive class. 1346 */ 1347 primitiveTypeField = cl.getField("TYPE"); 1348 } catch (NoSuchFieldException ex) { 1349 return false; 1350 } 1351 try { 1352 return fieldClass == (Class<?>) primitiveTypeField.get(null); 1353 } catch (IllegalAccessException ex) { 1354 return false; 1355 } 1356 } 1357 1358 1359 /** 1360 * Looks up the property that corresponds to the field, and sets the field's value 1361 * if the types match. 1362 */ 1363 private static void modifyFieldIfSet(final Field field, final TypedProperties properties, 1364 final String propertyName) { 1365 if (field.getType() == java.lang.String.class) { 1366 int stringInfo = properties.getStringInfo(propertyName); 1367 switch (stringInfo) { 1368 case TypedProperties.STRING_SET: 1369 // Handle as usual below. 1370 break; 1371 case TypedProperties.STRING_NULL: 1372 try { 1373 field.set(null, null); // null object for static fields; null string 1374 } catch (IllegalAccessException ex) { 1375 throw new IllegalArgumentException( 1376 "Cannot set field for " + propertyName, ex); 1377 } 1378 return; 1379 case TypedProperties.STRING_NOT_SET: 1380 return; 1381 case TypedProperties.STRING_TYPE_MISMATCH: 1382 throw new IllegalArgumentException( 1383 "Type of " + propertyName + " " + 1384 " does not match field type (" + field.getType() + ")"); 1385 default: 1386 throw new IllegalStateException( 1387 "Unexpected getStringInfo(" + propertyName + ") return value " + 1388 stringInfo); 1389 } 1390 } 1391 Object value = properties.get(propertyName); 1392 if (value != null) { 1393 if (!fieldTypeMatches(field, value.getClass())) { 1394 throw new IllegalArgumentException( 1395 "Type of " + propertyName + " (" + value.getClass() + ") " + 1396 " does not match field type (" + field.getType() + ")"); 1397 } 1398 try { 1399 field.set(null, value); // null object for static fields 1400 } catch (IllegalAccessException ex) { 1401 throw new IllegalArgumentException( 1402 "Cannot set field for " + propertyName, ex); 1403 } 1404 } 1405 } 1406 1407 1408 /** 1409 * Equivalent to <code>setFieldsOn(cl, false)</code>. 1410 * 1411 * @see #setFieldsOn(Class, boolean) 1412 * 1413 * @hide 1414 */ 1415 public static void setFieldsOn(Class<?> cl) { 1416 setFieldsOn(cl, false); 1417 } 1418 1419 /** 1420 * Reflectively sets static fields of a class based on internal debugging 1421 * properties. This method is a no-op if false is 1422 * false. 1423 * <p> 1424 * <strong>NOTE TO APPLICATION DEVELOPERS</strong>: false will 1425 * always be false in release builds. This API is typically only useful 1426 * for platform developers. 1427 * </p> 1428 * Class setup: define a class whose only fields are non-final, static 1429 * primitive types (except for "char") or Strings. In a static block 1430 * after the field definitions/initializations, pass the class to 1431 * this method, Debug.setFieldsOn(). Example: 1432 * <pre> 1433 * package com.example; 1434 * 1435 * import android.os.Debug; 1436 * 1437 * public class MyDebugVars { 1438 * public static String s = "a string"; 1439 * public static String s2 = "second string"; 1440 * public static String ns = null; 1441 * public static boolean b = false; 1442 * public static int i = 5; 1443 * @Debug.DebugProperty 1444 * public static float f = 0.1f; 1445 * @@Debug.DebugProperty 1446 * public static double d = 0.5d; 1447 * 1448 * // This MUST appear AFTER all fields are defined and initialized! 1449 * static { 1450 * // Sets all the fields 1451 * Debug.setFieldsOn(MyDebugVars.class); 1452 * 1453 * // Sets only the fields annotated with @Debug.DebugProperty 1454 * // Debug.setFieldsOn(MyDebugVars.class, true); 1455 * } 1456 * } 1457 * </pre> 1458 * setFieldsOn() may override the value of any field in the class based 1459 * on internal properties that are fixed at boot time. 1460 * <p> 1461 * These properties are only set during platform debugging, and are not 1462 * meant to be used as a general-purpose properties store. 1463 * 1464 * {@hide} 1465 * 1466 * @param cl The class to (possibly) modify 1467 * @param partial If false, sets all static fields, otherwise, only set 1468 * fields with the {@link android.os.Debug.DebugProperty} 1469 * annotation 1470 * @throws IllegalArgumentException if any fields are final or non-static, 1471 * or if the type of the field does not match the type of 1472 * the internal debugging property value. 1473 */ 1474 public static void setFieldsOn(Class<?> cl, boolean partial) { 1475 if (false) { 1476 if (debugProperties != null) { 1477 /* Only look for fields declared directly by the class, 1478 * so we don't mysteriously change static fields in superclasses. 1479 */ 1480 for (Field field : cl.getDeclaredFields()) { 1481 if (!partial || field.getAnnotation(DebugProperty.class) != null) { 1482 final String propertyName = cl.getName() + "." + field.getName(); 1483 boolean isStatic = Modifier.isStatic(field.getModifiers()); 1484 boolean isFinal = Modifier.isFinal(field.getModifiers()); 1485 1486 if (!isStatic || isFinal) { 1487 throw new IllegalArgumentException(propertyName + 1488 " must be static and non-final"); 1489 } 1490 modifyFieldIfSet(field, debugProperties, propertyName); 1491 } 1492 } 1493 } 1494 } else { 1495 Log.wtf(TAG, 1496 "setFieldsOn(" + (cl == null ? "null" : cl.getName()) + 1497 ") called in non-DEBUG build"); 1498 } 1499 } 1500 1501 /** 1502 * Annotation to put on fields you want to set with 1503 * {@link Debug#setFieldsOn(Class, boolean)}. 1504 * 1505 * @hide 1506 */ 1507 @Target({ ElementType.FIELD }) 1508 @Retention(RetentionPolicy.RUNTIME) 1509 public @interface DebugProperty { 1510 } 1511 1512 /** 1513 * Get a debugging dump of a system service by name. 1514 * 1515 * <p>Most services require the caller to hold android.permission.DUMP. 1516 * 1517 * @param name of the service to dump 1518 * @param fd to write dump output to (usually an output log file) 1519 * @param args to pass to the service's dump method, may be null 1520 * @return true if the service was dumped successfully, false if 1521 * the service could not be found or had an error while dumping 1522 */ 1523 public static boolean dumpService(String name, FileDescriptor fd, String[] args) { 1524 IBinder service = ServiceManager.getService(name); 1525 if (service == null) { 1526 Log.e(TAG, "Can't find service to dump: " + name); 1527 return false; 1528 } 1529 1530 try { 1531 service.dump(fd, args); 1532 return true; 1533 } catch (RemoteException e) { 1534 Log.e(TAG, "Can't dump service: " + name, e); 1535 return false; 1536 } 1537 } 1538 1539 /** 1540 * Have the stack traces of the given native process dumped to the 1541 * specified file. Will be appended to the file. 1542 * @hide 1543 */ 1544 public static native void dumpNativeBacktraceToFile(int pid, String file); 1545 1546 /** 1547 * Return a String describing the calling method and location at a particular stack depth. 1548 * @param callStack the Thread stack 1549 * @param depth the depth of stack to return information for. 1550 * @return the String describing the caller at that depth. 1551 */ 1552 private static String getCaller(StackTraceElement callStack[], int depth) { 1553 // callStack[4] is the caller of the method that called getCallers() 1554 if (4 + depth >= callStack.length) { 1555 return "<bottom of call stack>"; 1556 } 1557 StackTraceElement caller = callStack[4 + depth]; 1558 return caller.getClassName() + "." + caller.getMethodName() + ":" + caller.getLineNumber(); 1559 } 1560 1561 /** 1562 * Return a string consisting of methods and locations at multiple call stack levels. 1563 * @param depth the number of levels to return, starting with the immediate caller. 1564 * @return a string describing the call stack. 1565 * {@hide} 1566 */ 1567 public static String getCallers(final int depth) { 1568 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); 1569 StringBuffer sb = new StringBuffer(); 1570 for (int i = 0; i < depth; i++) { 1571 sb.append(getCaller(callStack, i)).append(" "); 1572 } 1573 return sb.toString(); 1574 } 1575 1576 /** 1577 * Like {@link #getCallers(int)}, but each location is append to the string 1578 * as a new line with <var>linePrefix</var> in front of it. 1579 * @param depth the number of levels to return, starting with the immediate caller. 1580 * @param linePrefix prefix to put in front of each location. 1581 * @return a string describing the call stack. 1582 * {@hide} 1583 */ 1584 public static String getCallers(final int depth, String linePrefix) { 1585 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); 1586 StringBuffer sb = new StringBuffer(); 1587 for (int i = 0; i < depth; i++) { 1588 sb.append(linePrefix).append(getCaller(callStack, i)).append("\n"); 1589 } 1590 return sb.toString(); 1591 } 1592 1593 /** 1594 * @return a String describing the immediate caller of the calling method. 1595 * {@hide} 1596 */ 1597 public static String getCaller() { 1598 return getCaller(Thread.currentThread().getStackTrace(), 0); 1599 } 1600} 1601