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