1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.app.AppGlobals;
import android.content.Context;
import android.util.Log;
import com.android.internal.util.FastPrintWriter;
import com.android.internal.util.Preconditions;
import com.android.internal.util.TypedProperties;
import dalvik.system.VMDebug;
import org.apache.harmony.dalvik.ddmc.Chunk;
import org.apache.harmony.dalvik.ddmc.ChunkHandler;
import org.apache.harmony.dalvik.ddmc.DdmServer;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
* Provides various debugging methods for Android applications, including
* tracing and allocation counts.
* <p><strong>Logging Trace Files</strong></p>
* <p>Debug can create log files that give details about an application, such as
* a call stack and start/stop times for any running methods. See <a
* href="{@docRoot}studio/profile/traceview.html">Inspect Trace Logs with
* Traceview</a> for information about reading trace files. To start logging
* trace files, call one of the startMethodTracing() methods. To stop tracing,
* call {@link #stopMethodTracing()}.
*/
public final class Debug
{
private static final String TAG = "Debug";
/**
* Flags for startMethodTracing(). These can be ORed together.
*
* TRACE_COUNT_ALLOCS adds the results from startAllocCounting to the
* trace key file.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static final int TRACE_COUNT_ALLOCS = VMDebug.TRACE_COUNT_ALLOCS;
/**
* Flags for printLoadedClasses(). Default behavior is to only show
* the class name.
*/
public static final int SHOW_FULL_DETAIL = 1;
public static final int SHOW_CLASSLOADER = (1 << 1);
public static final int SHOW_INITIALIZED = (1 << 2);
// set/cleared by waitForDebugger()
private static volatile boolean mWaiting = false;
@UnsupportedAppUsage
private Debug() {}
/*
* How long to wait for the debugger to finish sending requests. I've
* seen this hit 800msec on the device while waiting for a response
* to travel over USB and get processed, so we take that and add
* half a second.
*/
private static final int MIN_DEBUGGER_IDLE = 1300; // msec
/* how long to sleep when polling for activity */
private static final int SPIN_DELAY = 200; // msec
/**
* Default trace file path and file
*/
private static final String DEFAULT_TRACE_BODY = "dmtrace";
private static final String DEFAULT_TRACE_EXTENSION = ".trace";
/**
* This class is used to retrieved various statistics about the memory mappings for this
* process. The returned info is broken down by dalvik, native, and other. All results are in kB.
*/
public static class MemoryInfo implements Parcelable {
/** The proportional set size for dalvik heap. (Doesn't include other Dalvik overhead.) */
public int dalvikPss;
/** The proportional set size that is swappable for dalvik heap. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int dalvikSwappablePss;
/** @hide The resident set size for dalvik heap. (Without other Dalvik overhead.) */
@UnsupportedAppUsage
public int dalvikRss;
/** The private dirty pages used by dalvik heap. */
public int dalvikPrivateDirty;
/** The shared dirty pages used by dalvik heap. */
public int dalvikSharedDirty;
/** The private clean pages used by dalvik heap. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int dalvikPrivateClean;
/** The shared clean pages used by dalvik heap. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int dalvikSharedClean;
/** The dirty dalvik pages that have been swapped out. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int dalvikSwappedOut;
/** The dirty dalvik pages that have been swapped out, proportional. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int dalvikSwappedOutPss;
/** The proportional set size for the native heap. */
public int nativePss;
/** The proportional set size that is swappable for the native heap. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int nativeSwappablePss;
/** @hide The resident set size for the native heap. */
@UnsupportedAppUsage
public int nativeRss;
/** The private dirty pages used by the native heap. */
public int nativePrivateDirty;
/** The shared dirty pages used by the native heap. */
public int nativeSharedDirty;
/** The private clean pages used by the native heap. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int nativePrivateClean;
/** The shared clean pages used by the native heap. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int nativeSharedClean;
/** The dirty native pages that have been swapped out. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int nativeSwappedOut;
/** The dirty native pages that have been swapped out, proportional. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int nativeSwappedOutPss;
/** The proportional set size for everything else. */
public int otherPss;
/** The proportional set size that is swappable for everything else. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int otherSwappablePss;
/** @hide The resident set size for everything else. */
@UnsupportedAppUsage
public int otherRss;
/** The private dirty pages used by everything else. */
public int otherPrivateDirty;
/** The shared dirty pages used by everything else. */
public int otherSharedDirty;
/** The private clean pages used by everything else. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int otherPrivateClean;
/** The shared clean pages used by everything else. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int otherSharedClean;
/** The dirty pages used by anyting else that have been swapped out. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int otherSwappedOut;
/** The dirty pages used by anyting else that have been swapped out, proportional. */
/** @hide We may want to expose this, eventually. */
@UnsupportedAppUsage
public int otherSwappedOutPss;
/** Whether the kernel reports proportional swap usage */
/** @hide */
@UnsupportedAppUsage
public boolean hasSwappedOutPss;
/** @hide */
public static final int HEAP_UNKNOWN = 0;
/** @hide */
public static final int HEAP_DALVIK = 1;
/** @hide */
public static final int HEAP_NATIVE = 2;
/** @hide */
public static final int OTHER_DALVIK_OTHER = 0;
/** @hide */
public static final int OTHER_STACK = 1;
/** @hide */
public static final int OTHER_CURSOR = 2;
/** @hide */
public static final int OTHER_ASHMEM = 3;
/** @hide */
public static final int OTHER_GL_DEV = 4;
/** @hide */
public static final int OTHER_UNKNOWN_DEV = 5;
/** @hide */
public static final int OTHER_SO = 6;
/** @hide */
public static final int OTHER_JAR = 7;
/** @hide */
public static final int OTHER_APK = 8;
/** @hide */
public static final int OTHER_TTF = 9;
/** @hide */
public static final int OTHER_DEX = 10;
/** @hide */
public static final int OTHER_OAT = 11;
/** @hide */
public static final int OTHER_ART = 12;
/** @hide */
public static final int OTHER_UNKNOWN_MAP = 13;
/** @hide */
public static final int OTHER_GRAPHICS = 14;
/** @hide */
public static final int OTHER_GL = 15;
/** @hide */
public static final int OTHER_OTHER_MEMTRACK = 16;
// Needs to be declared here for the DVK_STAT ranges below.
/** @hide */
@UnsupportedAppUsage
public static final int NUM_OTHER_STATS = 17;
// Dalvik subsections.
/** @hide */
public static final int OTHER_DALVIK_NORMAL = 17;
/** @hide */
public static final int OTHER_DALVIK_LARGE = 18;
/** @hide */
public static final int OTHER_DALVIK_ZYGOTE = 19;
/** @hide */
public static final int OTHER_DALVIK_NON_MOVING = 20;
// Section begins and ends for dumpsys, relative to the DALVIK categories.
/** @hide */
public static final int OTHER_DVK_STAT_DALVIK_START =
OTHER_DALVIK_NORMAL - NUM_OTHER_STATS;
/** @hide */
public static final int OTHER_DVK_STAT_DALVIK_END =
OTHER_DALVIK_NON_MOVING - NUM_OTHER_STATS;
// Dalvik Other subsections.
/** @hide */
public static final int OTHER_DALVIK_OTHER_LINEARALLOC = 21;
/** @hide */
public static final int OTHER_DALVIK_OTHER_ACCOUNTING = 22;
/** @hide */
public static final int OTHER_DALVIK_OTHER_CODE_CACHE = 23;
/** @hide */
public static final int OTHER_DALVIK_OTHER_COMPILER_METADATA = 24;
/** @hide */
public static final int OTHER_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE = 25;
/** @hide */
public static final int OTHER_DVK_STAT_DALVIK_OTHER_START =
OTHER_DALVIK_OTHER_LINEARALLOC - NUM_OTHER_STATS;
/** @hide */
public static final int OTHER_DVK_STAT_DALVIK_OTHER_END =
OTHER_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE - NUM_OTHER_STATS;
// Dex subsections (Boot vdex, App dex, and App vdex).
/** @hide */
public static final int OTHER_DEX_BOOT_VDEX = 26;
/** @hide */
public static final int OTHER_DEX_APP_DEX = 27;
/** @hide */
public static final int OTHER_DEX_APP_VDEX = 28;
/** @hide */
public static final int OTHER_DVK_STAT_DEX_START = OTHER_DEX_BOOT_VDEX - NUM_OTHER_STATS;
/** @hide */
public static final int OTHER_DVK_STAT_DEX_END = OTHER_DEX_APP_VDEX - NUM_OTHER_STATS;
// Art subsections (App image, boot image).
/** @hide */
public static final int OTHER_ART_APP = 29;
/** @hide */
public static final int OTHER_ART_BOOT = 30;
/** @hide */
public static final int OTHER_DVK_STAT_ART_START = OTHER_ART_APP - NUM_OTHER_STATS;
/** @hide */
public static final int OTHER_DVK_STAT_ART_END = OTHER_ART_BOOT - NUM_OTHER_STATS;
/** @hide */
@UnsupportedAppUsage
public static final int NUM_DVK_STATS = 14;
/** @hide */
public static final int NUM_CATEGORIES = 9;
/** @hide */
public static final int OFFSET_PSS = 0;
/** @hide */
public static final int OFFSET_SWAPPABLE_PSS = 1;
/** @hide */
public static final int OFFSET_RSS = 2;
/** @hide */
public static final int OFFSET_PRIVATE_DIRTY = 3;
/** @hide */
public static final int OFFSET_SHARED_DIRTY = 4;
/** @hide */
public static final int OFFSET_PRIVATE_CLEAN = 5;
/** @hide */
public static final int OFFSET_SHARED_CLEAN = 6;
/** @hide */
public static final int OFFSET_SWAPPED_OUT = 7;
/** @hide */
public static final int OFFSET_SWAPPED_OUT_PSS = 8;
@UnsupportedAppUsage
private int[] otherStats = new int[(NUM_OTHER_STATS+NUM_DVK_STATS)*NUM_CATEGORIES];
public MemoryInfo() {
}
/**
* @hide Copy contents from another object.
*/
public void set(MemoryInfo other) {
dalvikPss = other.dalvikPss;
dalvikSwappablePss = other.dalvikSwappablePss;
dalvikRss = other.dalvikRss;
dalvikPrivateDirty = other.dalvikPrivateDirty;
dalvikSharedDirty = other.dalvikSharedDirty;
dalvikPrivateClean = other.dalvikPrivateClean;
dalvikSharedClean = other.dalvikSharedClean;
dalvikSwappedOut = other.dalvikSwappedOut;
dalvikSwappedOutPss = other.dalvikSwappedOutPss;
nativePss = other.nativePss;
nativeSwappablePss = other.nativeSwappablePss;
nativeRss = other.nativeRss;
nativePrivateDirty = other.nativePrivateDirty;
nativeSharedDirty = other.nativeSharedDirty;
nativePrivateClean = other.nativePrivateClean;
nativeSharedClean = other.nativeSharedClean;
nativeSwappedOut = other.nativeSwappedOut;
nativeSwappedOutPss = other.nativeSwappedOutPss;
otherPss = other.otherPss;
otherSwappablePss = other.otherSwappablePss;
otherRss = other.otherRss;
otherPrivateDirty = other.otherPrivateDirty;
otherSharedDirty = other.otherSharedDirty;
otherPrivateClean = other.otherPrivateClean;
otherSharedClean = other.otherSharedClean;
otherSwappedOut = other.otherSwappedOut;
otherSwappedOutPss = other.otherSwappedOutPss;
hasSwappedOutPss = other.hasSwappedOutPss;
System.arraycopy(other.otherStats, 0, otherStats, 0, otherStats.length);
}
/**
* Return total PSS memory usage in kB.
*/
public int getTotalPss() {
return dalvikPss + nativePss + otherPss + getTotalSwappedOutPss();
}
/**
* @hide Return total PSS memory usage in kB.
*/
@UnsupportedAppUsage
public int getTotalUss() {
return dalvikPrivateClean + dalvikPrivateDirty
+ nativePrivateClean + nativePrivateDirty
+ otherPrivateClean + otherPrivateDirty;
}
/**
* Return total PSS memory usage in kB mapping a file of one of the following extension:
* .so, .jar, .apk, .ttf, .dex, .odex, .oat, .art .
*/
public int getTotalSwappablePss() {
return dalvikSwappablePss + nativeSwappablePss + otherSwappablePss;
}
/**
* @hide Return total RSS memory usage in kB.
*/
public int getTotalRss() {
return dalvikRss + nativeRss + otherRss;
}
/**
* Return total private dirty memory usage in kB.
*/
public int getTotalPrivateDirty() {
return dalvikPrivateDirty + nativePrivateDirty + otherPrivateDirty;
}
/**
* Return total shared dirty memory usage in kB.
*/
public int getTotalSharedDirty() {
return dalvikSharedDirty + nativeSharedDirty + otherSharedDirty;
}
/**
* Return total shared clean memory usage in kB.
*/
public int getTotalPrivateClean() {
return dalvikPrivateClean + nativePrivateClean + otherPrivateClean;
}
/**
* Return total shared clean memory usage in kB.
*/
public int getTotalSharedClean() {
return dalvikSharedClean + nativeSharedClean + otherSharedClean;
}
/**
* Return total swapped out memory in kB.
* @hide
*/
public int getTotalSwappedOut() {
return dalvikSwappedOut + nativeSwappedOut + otherSwappedOut;
}
/**
* Return total swapped out memory in kB, proportional.
* @hide
*/
public int getTotalSwappedOutPss() {
return dalvikSwappedOutPss + nativeSwappedOutPss + otherSwappedOutPss;
}
/** @hide */
@UnsupportedAppUsage
public int getOtherPss(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_PSS];
}
/** @hide */
public int getOtherSwappablePss(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_SWAPPABLE_PSS];
}
/** @hide */
public int getOtherRss(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_RSS];
}
/** @hide */
@UnsupportedAppUsage
public int getOtherPrivateDirty(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_PRIVATE_DIRTY];
}
/** @hide */
@UnsupportedAppUsage
public int getOtherSharedDirty(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_SHARED_DIRTY];
}
/** @hide */
public int getOtherPrivateClean(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_PRIVATE_CLEAN];
}
/** @hide */
@UnsupportedAppUsage
public int getOtherPrivate(int which) {
return getOtherPrivateClean(which) + getOtherPrivateDirty(which);
}
/** @hide */
public int getOtherSharedClean(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_SHARED_CLEAN];
}
/** @hide */
public int getOtherSwappedOut(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_SWAPPED_OUT];
}
/** @hide */
public int getOtherSwappedOutPss(int which) {
return otherStats[which * NUM_CATEGORIES + OFFSET_SWAPPED_OUT_PSS];
}
/** @hide */
@UnsupportedAppUsage
public static String getOtherLabel(int which) {
switch (which) {
case OTHER_DALVIK_OTHER: return "Dalvik Other";
case OTHER_STACK: return "Stack";
case OTHER_CURSOR: return "Cursor";
case OTHER_ASHMEM: return "Ashmem";
case OTHER_GL_DEV: return "Gfx dev";
case OTHER_UNKNOWN_DEV: return "Other dev";
case OTHER_SO: return ".so mmap";
case OTHER_JAR: return ".jar mmap";
case OTHER_APK: return ".apk mmap";
case OTHER_TTF: return ".ttf mmap";
case OTHER_DEX: return ".dex mmap";
case OTHER_OAT: return ".oat mmap";
case OTHER_ART: return ".art mmap";
case OTHER_UNKNOWN_MAP: return "Other mmap";
case OTHER_GRAPHICS: return "EGL mtrack";
case OTHER_GL: return "GL mtrack";
case OTHER_OTHER_MEMTRACK: return "Other mtrack";
case OTHER_DALVIK_NORMAL: return ".Heap";
case OTHER_DALVIK_LARGE: return ".LOS";
case OTHER_DALVIK_ZYGOTE: return ".Zygote";
case OTHER_DALVIK_NON_MOVING: return ".NonMoving";
case OTHER_DALVIK_OTHER_LINEARALLOC: return ".LinearAlloc";
case OTHER_DALVIK_OTHER_ACCOUNTING: return ".GC";
case OTHER_DALVIK_OTHER_CODE_CACHE: return ".JITCache";
case OTHER_DALVIK_OTHER_COMPILER_METADATA: return ".CompilerMetadata";
case OTHER_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE: return ".IndirectRef";
case OTHER_DEX_BOOT_VDEX: return ".Boot vdex";
case OTHER_DEX_APP_DEX: return ".App dex";
case OTHER_DEX_APP_VDEX: return ".App vdex";
case OTHER_ART_APP: return ".App art";
case OTHER_ART_BOOT: return ".Boot art";
default: return "????";
}
}
/**
* Returns the value of a particular memory statistic or {@code null} if no
* such memory statistic exists.
*
* <p>The following table lists the memory statistics that are supported.
* Note that memory statistics may be added or removed in a future API level.</p>
*
* <table>
* <thead>
* <tr>
* <th>Memory statistic name</th>
* <th>Meaning</th>
* <th>Example</th>
* <th>Supported (API Levels)</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>summary.java-heap</td>
* <td>The private Java Heap usage in kB. This corresponds to the Java Heap field
* in the App Summary section output by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.native-heap</td>
* <td>The private Native Heap usage in kB. This corresponds to the Native Heap
* field in the App Summary section output by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.code</td>
* <td>The memory usage for static code and resources in kB. This corresponds to
* the Code field in the App Summary section output by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.stack</td>
* <td>The stack usage in kB. This corresponds to the Stack field in the
* App Summary section output by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.graphics</td>
* <td>The graphics usage in kB. This corresponds to the Graphics field in the
* App Summary section output by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.private-other</td>
* <td>Other private memory usage in kB. This corresponds to the Private Other
* field output in the App Summary section by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.system</td>
* <td>Shared and system memory usage in kB. This corresponds to the System
* field output in the App Summary section by dumpsys meminfo.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.total-pss</td>
* <td>Total PPS memory usage in kB.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>summary.total-swap</td>
* <td>Total swap usage in kB.</td>
* <td>{@code 1442}</td>
* <td>23</td>
* </tr>
* </tbody>
* </table>
*/
public String getMemoryStat(String statName) {
switch(statName) {
case "summary.java-heap":
return Integer.toString(getSummaryJavaHeap());
case "summary.native-heap":
return Integer.toString(getSummaryNativeHeap());
case "summary.code":
return Integer.toString(getSummaryCode());
case "summary.stack":
return Integer.toString(getSummaryStack());
case "summary.graphics":
return Integer.toString(getSummaryGraphics());
case "summary.private-other":
return Integer.toString(getSummaryPrivateOther());
case "summary.system":
return Integer.toString(getSummarySystem());
case "summary.total-pss":
return Integer.toString(getSummaryTotalPss());
case "summary.total-swap":
return Integer.toString(getSummaryTotalSwap());
default:
return null;
}
}
/**
* Returns a map of the names/values of the memory statistics
* that {@link #getMemoryStat(String)} supports.
*
* @return a map of the names/values of the supported memory statistics.
*/
public Map<String, String> getMemoryStats() {
Map<String, String> stats = new HashMap<String, String>();
stats.put("summary.java-heap", Integer.toString(getSummaryJavaHeap()));
stats.put("summary.native-heap", Integer.toString(getSummaryNativeHeap()));
stats.put("summary.code", Integer.toString(getSummaryCode()));
stats.put("summary.stack", Integer.toString(getSummaryStack()));
stats.put("summary.graphics", Integer.toString(getSummaryGraphics()));
stats.put("summary.private-other", Integer.toString(getSummaryPrivateOther()));
stats.put("summary.system", Integer.toString(getSummarySystem()));
stats.put("summary.total-pss", Integer.toString(getSummaryTotalPss()));
stats.put("summary.total-swap", Integer.toString(getSummaryTotalSwap()));
return stats;
}
/**
* Pss of Java Heap bytes in KB due to the application.
* Notes:
* * OTHER_ART is the boot image. Anything private here is blamed on
* the application, not the system.
* * dalvikPrivateDirty includes private zygote, which means the
* application dirtied something allocated by the zygote. We blame
* the application for that memory, not the system.
* * Does not include OTHER_DALVIK_OTHER, which is considered VM
* Overhead and lumped into Private Other.
* * We don't include dalvikPrivateClean, because there should be no
* such thing as private clean for the Java Heap.
* @hide
*/
@UnsupportedAppUsage
public int getSummaryJavaHeap() {
return dalvikPrivateDirty + getOtherPrivate(OTHER_ART);
}
/**
* Pss of Native Heap bytes in KB due to the application.
* Notes:
* * Includes private dirty malloc space.
* * We don't include nativePrivateClean, because there should be no
* such thing as private clean for the Native Heap.
* @hide
*/
@UnsupportedAppUsage
public int getSummaryNativeHeap() {
return nativePrivateDirty;
}
/**
* Pss of code and other static resource bytes in KB due to
* the application.
* @hide
*/
@UnsupportedAppUsage
public int getSummaryCode() {
return getOtherPrivate(OTHER_SO)
+ getOtherPrivate(OTHER_JAR)
+ getOtherPrivate(OTHER_APK)
+ getOtherPrivate(OTHER_TTF)
+ getOtherPrivate(OTHER_DEX)
+ getOtherPrivate(OTHER_OAT);
}
/**
* Pss in KB of the stack due to the application.
* Notes:
* * Includes private dirty stack, which includes both Java and Native
* stack.
* * Does not include private clean stack, because there should be no
* such thing as private clean for the stack.
* @hide
*/
@UnsupportedAppUsage
public int getSummaryStack() {
return getOtherPrivateDirty(OTHER_STACK);
}
/**
* Pss in KB of graphics due to the application.
* Notes:
* * Includes private Gfx, EGL, and GL.
* * Warning: These numbers can be misreported by the graphics drivers.
* * We don't include shared graphics. It may make sense to, because
* shared graphics are likely buffers due to the application
* anyway, but it's simpler to implement to just group all shared
* memory into the System category.
* @hide
*/
@UnsupportedAppUsage
public int getSummaryGraphics() {
return getOtherPrivate(OTHER_GL_DEV)
+ getOtherPrivate(OTHER_GRAPHICS)
+ getOtherPrivate(OTHER_GL);
}
/**
* Pss in KB due to the application that haven't otherwise been
* accounted for.
* @hide
*/
@UnsupportedAppUsage
public int getSummaryPrivateOther() {
return getTotalPrivateClean()
+ getTotalPrivateDirty()
- getSummaryJavaHeap()
- getSummaryNativeHeap()
- getSummaryCode()
- getSummaryStack()
- getSummaryGraphics();
}
/**
* Pss in KB due to the system.
* Notes:
* * Includes all shared memory.
* @hide
*/
@UnsupportedAppUsage
public int getSummarySystem() {
return getTotalPss()
- getTotalPrivateClean()
- getTotalPrivateDirty();
}
/**
* Total Pss in KB.
* @hide
*/
public int getSummaryTotalPss() {
return getTotalPss();
}
/**
* Total Swap in KB.
* Notes:
* * Some of this memory belongs in other categories, but we don't
* know if the Swap memory is shared or private, so we don't know
* what to blame on the application and what on the system.
* For now, just lump all the Swap in one place.
* For kernels reporting SwapPss {@link #getSummaryTotalSwapPss()}
* will report the application proportional Swap.
* @hide
*/
public int getSummaryTotalSwap() {
return getTotalSwappedOut();
}
/**
* Total proportional Swap in KB.
* Notes:
* * Always 0 if {@link #hasSwappedOutPss} is false.
* @hide
*/
public int getSummaryTotalSwapPss() {
return getTotalSwappedOutPss();
}
/**
* Return true if the kernel is reporting pss swapped out... that is, if
* {@link #getSummaryTotalSwapPss()} will return non-0 values.
* @hide
*/
public boolean hasSwappedOutPss() {
return hasSwappedOutPss;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(dalvikPss);
dest.writeInt(dalvikSwappablePss);
dest.writeInt(dalvikRss);
dest.writeInt(dalvikPrivateDirty);
dest.writeInt(dalvikSharedDirty);
dest.writeInt(dalvikPrivateClean);
dest.writeInt(dalvikSharedClean);
dest.writeInt(dalvikSwappedOut);
dest.writeInt(dalvikSwappedOutPss);
dest.writeInt(nativePss);
dest.writeInt(nativeSwappablePss);
dest.writeInt(nativeRss);
dest.writeInt(nativePrivateDirty);
dest.writeInt(nativeSharedDirty);
dest.writeInt(nativePrivateClean);
dest.writeInt(nativeSharedClean);
dest.writeInt(nativeSwappedOut);
dest.writeInt(nativeSwappedOutPss);
dest.writeInt(otherPss);
dest.writeInt(otherSwappablePss);
dest.writeInt(otherRss);
dest.writeInt(otherPrivateDirty);
dest.writeInt(otherSharedDirty);
dest.writeInt(otherPrivateClean);
dest.writeInt(otherSharedClean);
dest.writeInt(otherSwappedOut);
dest.writeInt(hasSwappedOutPss ? 1 : 0);
dest.writeInt(otherSwappedOutPss);
dest.writeIntArray(otherStats);
}
public void readFromParcel(Parcel source) {
dalvikPss = source.readInt();
dalvikSwappablePss = source.readInt();
dalvikRss = source.readInt();
dalvikPrivateDirty = source.readInt();
dalvikSharedDirty = source.readInt();
dalvikPrivateClean = source.readInt();
dalvikSharedClean = source.readInt();
dalvikSwappedOut = source.readInt();
dalvikSwappedOutPss = source.readInt();
nativePss = source.readInt();
nativeSwappablePss = source.readInt();
nativeRss = source.readInt();
nativePrivateDirty = source.readInt();
nativeSharedDirty = source.readInt();
nativePrivateClean = source.readInt();
nativeSharedClean = source.readInt();
nativeSwappedOut = source.readInt();
nativeSwappedOutPss = source.readInt();
otherPss = source.readInt();
otherSwappablePss = source.readInt();
otherRss = source.readInt();
otherPrivateDirty = source.readInt();
otherSharedDirty = source.readInt();
otherPrivateClean = source.readInt();
otherSharedClean = source.readInt();
otherSwappedOut = source.readInt();
hasSwappedOutPss = source.readInt() != 0;
otherSwappedOutPss = source.readInt();
otherStats = source.createIntArray();
}
public static final @android.annotation.NonNull Creator<MemoryInfo> CREATOR = new Creator<MemoryInfo>() {
public MemoryInfo createFromParcel(Parcel source) {
return new MemoryInfo(source);
}
public MemoryInfo[] newArray(int size) {
return new MemoryInfo[size];
}
};
private MemoryInfo(Parcel source) {
readFromParcel(source);
}
}
/**
* Wait until a debugger attaches. As soon as the debugger attaches,
* this returns, so you will need to place a breakpoint after the
* waitForDebugger() call if you want to start tracing immediately.
*/
public static void waitForDebugger() {
if (!VMDebug.isDebuggingEnabled()) {
//System.out.println("debugging not enabled, not waiting");
return;
}
if (isDebuggerConnected())
return;
// if DDMS is listening, inform them of our plight
System.out.println("Sending WAIT chunk");
byte[] data = new byte[] { 0 }; // 0 == "waiting for debugger"
Chunk waitChunk = new Chunk(ChunkHandler.type("WAIT"), data, 0, 1);
DdmServer.sendChunk(waitChunk);
mWaiting = true;
while (!isDebuggerConnected()) {
try { Thread.sleep(SPIN_DELAY); }
catch (InterruptedException ie) {}
}
mWaiting = false;
System.out.println("Debugger has connected");
/*
* There is no "ready to go" signal from the debugger, and we're
* not allowed to suspend ourselves -- the debugger expects us to
* be running happily, and gets confused if we aren't. We need to
* allow the debugger a chance to set breakpoints before we start
* running again.
*
* Sit and spin until the debugger has been idle for a short while.
*/
while (true) {
long delta = VMDebug.lastDebuggerActivity();
if (delta < 0) {
System.out.println("debugger detached?");
break;
}
if (delta < MIN_DEBUGGER_IDLE) {
System.out.println("waiting for debugger to settle...");
try { Thread.sleep(SPIN_DELAY); }
catch (InterruptedException ie) {}
} else {
System.out.println("debugger has settled (" + delta + ")");
break;
}
}
}
/**
* Returns "true" if one or more threads is waiting for a debugger
* to attach.
*/
public static boolean waitingForDebugger() {
return mWaiting;
}
/**
* Determine if a debugger is currently attached.
*/
public static boolean isDebuggerConnected() {
return VMDebug.isDebuggerConnected();
}
/**
* Returns an array of strings that identify VM features. This is
* used by DDMS to determine what sorts of operations the VM can
* perform.
*
* @hide
*/
public static String[] getVmFeatureList() {
return VMDebug.getVmFeatureList();
}
/**
* Change the JDWP port.
*
* @deprecated no longer needed or useful
*/
@Deprecated
public static void changeDebugPort(int port) {}
/**
* This is the pathname to the sysfs file that enables and disables
* tracing on the qemu emulator.
*/
private static final String SYSFS_QEMU_TRACE_STATE = "/sys/qemu_trace/state";
/**
* Enable qemu tracing. For this to work requires running everything inside
* the qemu emulator; otherwise, this method will have no effect. The trace
* file is specified on the command line when the emulator is started. For
* example, the following command line <br />
* <code>emulator -trace foo</code><br />
* will start running the emulator and create a trace file named "foo". This
* method simply enables writing the trace records to the trace file.
*
* <p>
* The main differences between this and {@link #startMethodTracing()} are
* that tracing in the qemu emulator traces every cpu instruction of every
* process, including kernel code, so we have more complete information,
* including all context switches. We can also get more detailed information
* such as cache misses. The sequence of calls is determined by
* post-processing the instruction trace. The qemu tracing is also done
* without modifying the application or perturbing the timing of calls
* because no instrumentation is added to the application being traced.
* </p>
*
* <p>
* One limitation of using this method compared to using
* {@link #startMethodTracing()} on the real device is that the emulator
* does not model all of the real hardware effects such as memory and
* bus contention. The emulator also has a simple cache model and cannot
* capture all the complexities of a real cache.
* </p>
*/
public static void startNativeTracing() {
// Open the sysfs file for writing and write "1" to it.
PrintWriter outStream = null;
try {
FileOutputStream fos = new FileOutputStream(SYSFS_QEMU_TRACE_STATE);
outStream = new FastPrintWriter(fos);
outStream.println("1");
} catch (Exception e) {
} finally {
if (outStream != null)
outStream.close();
}
VMDebug.startEmulatorTracing();
}
/**
* Stop qemu tracing. See {@link #startNativeTracing()} to start tracing.
*
* <p>Tracing can be started and stopped as many times as desired. When
* the qemu emulator itself is stopped then the buffered trace records
* are flushed and written to the trace file. In fact, it is not necessary
* to call this method at all; simply killing qemu is sufficient. But
* starting and stopping a trace is useful for examining a specific
* region of code.</p>
*/
public static void stopNativeTracing() {
VMDebug.stopEmulatorTracing();
// Open the sysfs file for writing and write "0" to it.
PrintWriter outStream = null;
try {
FileOutputStream fos = new FileOutputStream(SYSFS_QEMU_TRACE_STATE);
outStream = new FastPrintWriter(fos);
outStream.println("0");
} catch (Exception e) {
// We could print an error message here but we probably want
// to quietly ignore errors if we are not running in the emulator.
} finally {
if (outStream != null)
outStream.close();
}
}
/**
* Enable "emulator traces", in which information about the current
* method is made available to the "emulator -trace" feature. There
* is no corresponding "disable" call -- this is intended for use by
* the framework when tracing should be turned on and left that way, so
* that traces captured with F9/F10 will include the necessary data.
*
* This puts the VM into "profile" mode, which has performance
* consequences.
*
* To temporarily enable tracing, use {@link #startNativeTracing()}.
*/
public static void enableEmulatorTraceOutput() {
VMDebug.startEmulatorTracing();
}
/**
* Start method tracing with default log name and buffer size.
* <p>
* By default, the trace file is called "dmtrace.trace" and it's placed
* under your package-specific directory on primary shared/external storage,
* as returned by {@link Context#getExternalFilesDir(String)}.
* <p>
* See <a href="{@docRoot}studio/profile/traceview.html">Inspect Trace Logs
* with Traceview</a> for information about reading trace files.
* <p class="note">
* When method tracing is enabled, the VM will run more slowly than usual,
* so the timings from the trace files should only be considered in relative
* terms (e.g. was run #1 faster than run #2). The times for native methods
* will not change, so don't try to use this to compare the performance of
* interpreted and native implementations of the same method. As an
* alternative, consider using sampling-based method tracing via
* {@link #startMethodTracingSampling(String, int, int)} or "native" tracing
* in the emulator via {@link #startNativeTracing()}.
* </p>
*/
public static void startMethodTracing() {
VMDebug.startMethodTracing(fixTracePath(null), 0, 0, false, 0);
}
/**
* Start method tracing, specifying the trace log file path.
* <p>
* When a relative file path is given, the trace file will be placed under
* your package-specific directory on primary shared/external storage, as
* returned by {@link Context#getExternalFilesDir(String)}.
* <p>
* See <a href="{@docRoot}studio/profile/traceview.html">Inspect Trace Logs
* with Traceview</a> for information about reading trace files.
* <p class="note">
* When method tracing is enabled, the VM will run more slowly than usual,
* so the timings from the trace files should only be considered in relative
* terms (e.g. was run #1 faster than run #2). The times for native methods
* will not change, so don't try to use this to compare the performance of
* interpreted and native implementations of the same method. As an
* alternative, consider using sampling-based method tracing via
* {@link #startMethodTracingSampling(String, int, int)} or "native" tracing
* in the emulator via {@link #startNativeTracing()}.
* </p>
*
* @param tracePath Path to the trace log file to create. If {@code null},
* this will default to "dmtrace.trace". If the file already
* exists, it will be truncated. If the path given does not end
* in ".trace", it will be appended for you.
*/
public static void startMethodTracing(String tracePath) {
startMethodTracing(tracePath, 0, 0);
}
/**
* Start method tracing, specifying the trace log file name and the buffer
* size.
* <p>
* When a relative file path is given, the trace file will be placed under
* your package-specific directory on primary shared/external storage, as
* returned by {@link Context#getExternalFilesDir(String)}.
* <p>
* See <a href="{@docRoot}studio/profile/traceview.html">Inspect Trace Logs
* with Traceview</a> for information about reading trace files.
* <p class="note">
* When method tracing is enabled, the VM will run more slowly than usual,
* so the timings from the trace files should only be considered in relative
* terms (e.g. was run #1 faster than run #2). The times for native methods
* will not change, so don't try to use this to compare the performance of
* interpreted and native implementations of the same method. As an
* alternative, consider using sampling-based method tracing via
* {@link #startMethodTracingSampling(String, int, int)} or "native" tracing
* in the emulator via {@link #startNativeTracing()}.
* </p>
*
* @param tracePath Path to the trace log file to create. If {@code null},
* this will default to "dmtrace.trace". If the file already
* exists, it will be truncated. If the path given does not end
* in ".trace", it will be appended for you.
* @param bufferSize The maximum amount of trace data we gather. If not
* given, it defaults to 8MB.
*/
public static void startMethodTracing(String tracePath, int bufferSize) {
startMethodTracing(tracePath, bufferSize, 0);
}
/**
* Start method tracing, specifying the trace log file name, the buffer
* size, and flags.
* <p>
* When a relative file path is given, the trace file will be placed under
* your package-specific directory on primary shared/external storage, as
* returned by {@link Context#getExternalFilesDir(String)}.
* <p>
* See <a href="{@docRoot}studio/profile/traceview.html">Inspect Trace Logs
* with Traceview</a> for information about reading trace files.
* <p class="note">
* When method tracing is enabled, the VM will run more slowly than usual,
* so the timings from the trace files should only be considered in relative
* terms (e.g. was run #1 faster than run #2). The times for native methods
* will not change, so don't try to use this to compare the performance of
* interpreted and native implementations of the same method. As an
* alternative, consider using sampling-based method tracing via
* {@link #startMethodTracingSampling(String, int, int)} or "native" tracing
* in the emulator via {@link #startNativeTracing()}.
* </p>
*
* @param tracePath Path to the trace log file to create. If {@code null},
* this will default to "dmtrace.trace". If the file already
* exists, it will be truncated. If the path given does not end
* in ".trace", it will be appended for you.
* @param bufferSize The maximum amount of trace data we gather. If not
* given, it defaults to 8MB.
* @param flags Flags to control method tracing. The only one that is
* currently defined is {@link #TRACE_COUNT_ALLOCS}.
*/
public static void startMethodTracing(String tracePath, int bufferSize, int flags) {
VMDebug.startMethodTracing(fixTracePath(tracePath), bufferSize, flags, false, 0);
}
/**
* Start sampling-based method tracing, specifying the trace log file name,
* the buffer size, and the sampling interval.
* <p>
* When a relative file path is given, the trace file will be placed under
* your package-specific directory on primary shared/external storage, as
* returned by {@link Context#getExternalFilesDir(String)}.
* <p>
* See <a href="{@docRoot}studio/profile/traceview.html">Inspect Trace Logs
* with Traceview</a> for information about reading trace files.
*
* @param tracePath Path to the trace log file to create. If {@code null},
* this will default to "dmtrace.trace". If the file already
* exists, it will be truncated. If the path given does not end
* in ".trace", it will be appended for you.
* @param bufferSize The maximum amount of trace data we gather. If not
* given, it defaults to 8MB.
* @param intervalUs The amount of time between each sample in microseconds.
*/
public static void startMethodTracingSampling(String tracePath, int bufferSize,
int intervalUs) {
VMDebug.startMethodTracing(fixTracePath(tracePath), bufferSize, 0, true, intervalUs);
}
/**
* Formats name of trace log file for method tracing.
*/
private static String fixTracePath(String tracePath) {
if (tracePath == null || tracePath.charAt(0) != '/') {
final Context context = AppGlobals.getInitialApplication();
final File dir;
if (context != null) {
dir = context.getExternalFilesDir(null);
} else {
dir = Environment.getExternalStorageDirectory();
}
if (tracePath == null) {
tracePath = new File(dir, DEFAULT_TRACE_BODY).getAbsolutePath();
} else {
tracePath = new File(dir, tracePath).getAbsolutePath();
}
}
if (!tracePath.endsWith(DEFAULT_TRACE_EXTENSION)) {
tracePath += DEFAULT_TRACE_EXTENSION;
}
return tracePath;
}
/**
* Like startMethodTracing(String, int, int), but taking an already-opened
* FileDescriptor in which the trace is written. The file name is also
* supplied simply for logging. Makes a dup of the file descriptor.
*
* Not exposed in the SDK unless we are really comfortable with supporting
* this and find it would be useful.
* @hide
*/
public static void startMethodTracing(String traceName, FileDescriptor fd,
int bufferSize, int flags, boolean streamOutput) {
VMDebug.startMethodTracing(traceName, fd, bufferSize, flags, false, 0, streamOutput);
}
/**
* Starts method tracing without a backing file. When stopMethodTracing
* is called, the result is sent directly to DDMS. (If DDMS is not
* attached when tracing ends, the profiling data will be discarded.)
*
* @hide
*/
public static void startMethodTracingDdms(int bufferSize, int flags,
boolean samplingEnabled, int intervalUs) {
VMDebug.startMethodTracingDdms(bufferSize, flags, samplingEnabled, intervalUs);
}
/**
* Determine whether method tracing is currently active and what type is
* active.
*
* @hide
*/
public static int getMethodTracingMode() {
return VMDebug.getMethodTracingMode();
}
/**
* Stop method tracing.
*/
public static void stopMethodTracing() {
VMDebug.stopMethodTracing();
}
/**
* Get an indication of thread CPU usage. The value returned
* indicates the amount of time that the current thread has spent
* executing code or waiting for certain types of I/O.
*
* The time is expressed in nanoseconds, and is only meaningful
* when compared to the result from an earlier call. Note that
* nanosecond resolution does not imply nanosecond accuracy.
*
* On system which don't support this operation, the call returns -1.
*/
public static long threadCpuTimeNanos() {
return VMDebug.threadCpuTimeNanos();
}
/**
* Start counting the number and aggregate size of memory allocations.
*
* <p>The {@link #startAllocCounting() start} method resets the counts and enables counting.
* The {@link #stopAllocCounting() stop} method disables the counting so that the analysis
* code doesn't cause additional allocations. The various <code>get</code> methods return
* the specified value. And the various <code>reset</code> methods reset the specified
* count.</p>
*
* <p>Counts are kept for the system as a whole (global) and for each thread.
* The per-thread counts for threads other than the current thread
* are not cleared by the "reset" or "start" calls.</p>
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void startAllocCounting() {
VMDebug.startAllocCounting();
}
/**
* Stop counting the number and aggregate size of memory allocations.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void stopAllocCounting() {
VMDebug.stopAllocCounting();
}
/**
* Returns the global count of objects allocated by the runtime between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalAllocCount() {
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_OBJECTS);
}
/**
* Clears the global count of objects allocated.
* @see #getGlobalAllocCount()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalAllocCount() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_OBJECTS);
}
/**
* Returns the global size, in bytes, of objects allocated by the runtime between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalAllocSize() {
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_BYTES);
}
/**
* Clears the global size of objects allocated.
* @see #getGlobalAllocSize()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalAllocSize() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_ALLOCATED_BYTES);
}
/**
* Returns the global count of objects freed by the runtime between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalFreedCount() {
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_FREED_OBJECTS);
}
/**
* Clears the global count of objects freed.
* @see #getGlobalFreedCount()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalFreedCount() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_FREED_OBJECTS);
}
/**
* Returns the global size, in bytes, of objects freed by the runtime between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalFreedSize() {
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_FREED_BYTES);
}
/**
* Clears the global size of objects freed.
* @see #getGlobalFreedSize()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalFreedSize() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_FREED_BYTES);
}
/**
* Returns the number of non-concurrent GC invocations between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalGcInvocationCount() {
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_GC_INVOCATIONS);
}
/**
* Clears the count of non-concurrent GC invocations.
* @see #getGlobalGcInvocationCount()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalGcInvocationCount() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_GC_INVOCATIONS);
}
/**
* Returns the number of classes successfully initialized (ie those that executed without
* throwing an exception) between a {@link #startAllocCounting() start} and
* {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalClassInitCount() {
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_COUNT);
}
/**
* Clears the count of classes initialized.
* @see #getGlobalClassInitCount()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalClassInitCount() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_COUNT);
}
/**
* Returns the time spent successfully initializing classes between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getGlobalClassInitTime() {
/* cumulative elapsed time for class initialization, in usec */
return VMDebug.getAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_TIME);
}
/**
* Clears the count of time spent initializing classes.
* @see #getGlobalClassInitTime()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetGlobalClassInitTime() {
VMDebug.resetAllocCount(VMDebug.KIND_GLOBAL_CLASS_INIT_TIME);
}
/**
* This method exists for compatibility and always returns 0.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int getGlobalExternalAllocCount() {
return 0;
}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static void resetGlobalExternalAllocSize() {}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static void resetGlobalExternalAllocCount() {}
/**
* This method exists for compatibility and always returns 0.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int getGlobalExternalAllocSize() {
return 0;
}
/**
* This method exists for compatibility and always returns 0.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int getGlobalExternalFreedCount() {
return 0;
}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static void resetGlobalExternalFreedCount() {}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int getGlobalExternalFreedSize() {
return 0;
}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static void resetGlobalExternalFreedSize() {}
/**
* Returns the thread-local count of objects allocated by the runtime between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getThreadAllocCount() {
return VMDebug.getAllocCount(VMDebug.KIND_THREAD_ALLOCATED_OBJECTS);
}
/**
* Clears the thread-local count of objects allocated.
* @see #getThreadAllocCount()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetThreadAllocCount() {
VMDebug.resetAllocCount(VMDebug.KIND_THREAD_ALLOCATED_OBJECTS);
}
/**
* Returns the thread-local size of objects allocated by the runtime between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
* @return The allocated size in bytes.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getThreadAllocSize() {
return VMDebug.getAllocCount(VMDebug.KIND_THREAD_ALLOCATED_BYTES);
}
/**
* Clears the thread-local count of objects allocated.
* @see #getThreadAllocSize()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetThreadAllocSize() {
VMDebug.resetAllocCount(VMDebug.KIND_THREAD_ALLOCATED_BYTES);
}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int getThreadExternalAllocCount() {
return 0;
}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static void resetThreadExternalAllocCount() {}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int getThreadExternalAllocSize() {
return 0;
}
/**
* This method exists for compatibility and has no effect.
* @deprecated This method is now obsolete.
*/
@Deprecated
public static void resetThreadExternalAllocSize() {}
/**
* Returns the number of thread-local non-concurrent GC invocations between a
* {@link #startAllocCounting() start} and {@link #stopAllocCounting() stop}.
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static int getThreadGcInvocationCount() {
return VMDebug.getAllocCount(VMDebug.KIND_THREAD_GC_INVOCATIONS);
}
/**
* Clears the thread-local count of non-concurrent GC invocations.
* @see #getThreadGcInvocationCount()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetThreadGcInvocationCount() {
VMDebug.resetAllocCount(VMDebug.KIND_THREAD_GC_INVOCATIONS);
}
/**
* Clears all the global and thread-local memory allocation counters.
* @see #startAllocCounting()
*
* @deprecated Accurate counting is a burden on the runtime and may be removed.
*/
@Deprecated
public static void resetAllCounts() {
VMDebug.resetAllocCount(VMDebug.KIND_ALL_COUNTS);
}
/**
* Returns the value of a particular runtime statistic or {@code null} if no
* such runtime statistic exists.
*
* <p>The following table lists the runtime statistics that the runtime supports.
* Note runtime statistics may be added or removed in a future API level.</p>
*
* <table>
* <thead>
* <tr>
* <th>Runtime statistic name</th>
* <th>Meaning</th>
* <th>Example</th>
* <th>Supported (API Levels)</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>art.gc.gc-count</td>
* <td>The number of garbage collection runs.</td>
* <td>{@code 164}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.gc-time</td>
* <td>The total duration of garbage collection runs in ms.</td>
* <td>{@code 62364}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.bytes-allocated</td>
* <td>The total number of bytes that the application allocated.</td>
* <td>{@code 1463948408}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.bytes-freed</td>
* <td>The total number of bytes that garbage collection reclaimed.</td>
* <td>{@code 1313493084}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.blocking-gc-count</td>
* <td>The number of blocking garbage collection runs.</td>
* <td>{@code 2}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.blocking-gc-time</td>
* <td>The total duration of blocking garbage collection runs in ms.</td>
* <td>{@code 804}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.gc-count-rate-histogram</td>
* <td>Every 10 seconds, the gc-count-rate is computed as the number of garbage
* collection runs that have occurred over the last 10
* seconds. art.gc.gc-count-rate-histogram is a histogram of the gc-count-rate
* samples taken since the process began. The histogram can be used to identify
* instances of high rates of garbage collection runs. For example, a histogram
* of "0:34503,1:45350,2:11281,3:8088,4:43,5:8" shows that most of the time
* there are between 0 and 2 garbage collection runs every 10 seconds, but there
* were 8 distinct 10-second intervals in which 5 garbage collection runs
* occurred.</td>
* <td>{@code 0:34503,1:45350,2:11281,3:8088,4:43,5:8}</td>
* <td>23</td>
* </tr>
* <tr>
* <td>art.gc.blocking-gc-count-rate-histogram</td>
* <td>Every 10 seconds, the blocking-gc-count-rate is computed as the number of
* blocking garbage collection runs that have occurred over the last 10
* seconds. art.gc.blocking-gc-count-rate-histogram is a histogram of the
* blocking-gc-count-rate samples taken since the process began. The histogram
* can be used to identify instances of high rates of blocking garbage
* collection runs. For example, a histogram of "0:99269,1:1,2:1" shows that
* most of the time there are zero blocking garbage collection runs every 10
* seconds, but there was one 10-second interval in which one blocking garbage
* collection run occurred, and there was one interval in which two blocking
* garbage collection runs occurred.</td>
* <td>{@code 0:99269,1:1,2:1}</td>
* <td>23</td>
* </tr>
* </tbody>
* </table>
*
* @param statName
* the name of the runtime statistic to look up.
* @return the value of the specified runtime statistic or {@code null} if the
* runtime statistic doesn't exist.
*/
public static String getRuntimeStat(String statName) {
return VMDebug.getRuntimeStat(statName);
}
/**
* Returns a map of the names/values of the runtime statistics
* that {@link #getRuntimeStat(String)} supports.
*
* @return a map of the names/values of the supported runtime statistics.
*/
public static Map<String, String> getRuntimeStats() {
return VMDebug.getRuntimeStats();
}
/**
* Returns the size of the native heap.
* @return The size of the native heap in bytes.
*/
public static native long getNativeHeapSize();
/**
* Returns the amount of allocated memory in the native heap.
* @return The allocated size in bytes.
*/
public static native long getNativeHeapAllocatedSize();
/**
* Returns the amount of free memory in the native heap.
* @return The freed size in bytes.
*/
public static native long getNativeHeapFreeSize();
/**
* Retrieves information about this processes memory usages. This information is broken down by
* how much is in use by dalvik, the native heap, and everything else.
*
* <p><b>Note:</b> this method directly retrieves memory information for the given process
* from low-level data available to it. It may not be able to retrieve information about
* some protected allocations, such as graphics. If you want to be sure you can see
* all information about allocations by the process, use
* {@link android.app.ActivityManager#getProcessMemoryInfo(int[])} instead.</p>
*/
public static native void getMemoryInfo(MemoryInfo memoryInfo);
/**
* Note: currently only works when the requested pid has the same UID
* as the caller.
* @hide
*/
@UnsupportedAppUsage
public static native void getMemoryInfo(int pid, MemoryInfo memoryInfo);
/**
* Retrieves the PSS memory used by the process as given by the
* smaps.
*/
public static native long getPss();
/**
* Retrieves the PSS memory used by the process as given by the smaps. Optionally supply a long
* array of up to 3 entries to also receive (up to 3 values in order): the Uss and SwapPss and
* Rss (only filled in as of {@link android.os.Build.VERSION_CODES#P}) of the process, and
* another array to also retrieve the separate memtrack size.
* @hide
*/
public static native long getPss(int pid, long[] outUssSwapPssRss, long[] outMemtrack);
/** @hide */
public static final int MEMINFO_TOTAL = 0;
/** @hide */
public static final int MEMINFO_FREE = 1;
/** @hide */
public static final int MEMINFO_BUFFERS = 2;
/** @hide */
public static final int MEMINFO_CACHED = 3;
/** @hide */
public static final int MEMINFO_SHMEM = 4;
/** @hide */
public static final int MEMINFO_SLAB = 5;
/** @hide */
public static final int MEMINFO_SLAB_RECLAIMABLE = 6;
/** @hide */
public static final int MEMINFO_SLAB_UNRECLAIMABLE = 7;
/** @hide */
public static final int MEMINFO_SWAP_TOTAL = 8;
/** @hide */
public static final int MEMINFO_SWAP_FREE = 9;
/** @hide */
public static final int MEMINFO_ZRAM_TOTAL = 10;
/** @hide */
public static final int MEMINFO_MAPPED = 11;
/** @hide */
public static final int MEMINFO_VM_ALLOC_USED = 12;
/** @hide */
public static final int MEMINFO_PAGE_TABLES = 13;
/** @hide */
public static final int MEMINFO_KERNEL_STACK = 14;
/** @hide */
public static final int MEMINFO_COUNT = 15;
/**
* Retrieves /proc/meminfo. outSizes is filled with fields
* as defined by MEMINFO_* offsets.
* @hide
*/
@UnsupportedAppUsage
public static native void getMemInfo(long[] outSizes);
/**
* Establish an object allocation limit in the current thread.
* This feature was never enabled in release builds. The
* allocation limits feature was removed in Honeycomb. This
* method exists for compatibility and always returns -1 and has
* no effect.
*
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int setAllocationLimit(int limit) {
return -1;
}
/**
* Establish a global object allocation limit. This feature was
* never enabled in release builds. The allocation limits feature
* was removed in Honeycomb. This method exists for compatibility
* and always returns -1 and has no effect.
*
* @deprecated This method is now obsolete.
*/
@Deprecated
public static int setGlobalAllocationLimit(int limit) {
return -1;
}
/**
* Dump a list of all currently loaded class to the log file.
*
* @param flags See constants above.
*/
public static void printLoadedClasses(int flags) {
VMDebug.printLoadedClasses(flags);
}
/**
* Get the number of loaded classes.
* @return the number of loaded classes.
*/
public static int getLoadedClassCount() {
return VMDebug.getLoadedClassCount();
}
/**
* Dump "hprof" data to the specified file. This may cause a GC.
*
* @param fileName Full pathname of output file (e.g. "/sdcard/dump.hprof").
* @throws UnsupportedOperationException if the VM was built without
* HPROF support.
* @throws IOException if an error occurs while opening or writing files.
*/
public static void dumpHprofData(String fileName) throws IOException {
VMDebug.dumpHprofData(fileName);
}
/**
* Like dumpHprofData(String), but takes an already-opened
* FileDescriptor to which the trace is written. The file name is also
* supplied simply for logging. Makes a dup of the file descriptor.
*
* Primarily for use by the "am" shell command.
*
* @hide
*/
public static void dumpHprofData(String fileName, FileDescriptor fd)
throws IOException {
VMDebug.dumpHprofData(fileName, fd);
}
/**
* Collect "hprof" and send it to DDMS. This may cause a GC.
*
* @throws UnsupportedOperationException if the VM was built without
* HPROF support.
* @hide
*/
public static void dumpHprofDataDdms() {
VMDebug.dumpHprofDataDdms();
}
/**
* Writes native heap data to the specified file descriptor.
*
* @hide
*/
@UnsupportedAppUsage
public static native void dumpNativeHeap(FileDescriptor fd);
/**
* Writes malloc info data to the specified file descriptor.
*
* @hide
*/
public static native void dumpNativeMallocInfo(FileDescriptor fd);
/**
* Returns a count of the extant instances of a class.
*
* @hide
*/
@UnsupportedAppUsage
public static long countInstancesOfClass(Class cls) {
return VMDebug.countInstancesOfClass(cls, true);
}
/**
* Returns the number of sent transactions from this process.
* @return The number of sent transactions or -1 if it could not read t.
*/
public static native int getBinderSentTransactions();
/**
* Returns the number of received transactions from the binder driver.
* @return The number of received transactions or -1 if it could not read the stats.
*/
public static native int getBinderReceivedTransactions();
/**
* Returns the number of active local Binder objects that exist in the
* current process.
*/
public static final native int getBinderLocalObjectCount();
/**
* Returns the number of references to remote proxy Binder objects that
* exist in the current process.
*/
public static final native int getBinderProxyObjectCount();
/**
* Returns the number of death notification links to Binder objects that
* exist in the current process.
*/
public static final native int getBinderDeathObjectCount();
/**
* Primes the register map cache.
*
* Only works for classes in the bootstrap class loader. Does not
* cause classes to be loaded if they're not already present.
*
* The classAndMethodDesc argument is a concatentation of the VM-internal
* class descriptor, method name, and method descriptor. Examples:
* Landroid/os/Looper;.loop:()V
* Landroid/app/ActivityThread;.main:([Ljava/lang/String;)V
*
* @param classAndMethodDesc the method to prepare
*
* @hide
*/
public static final boolean cacheRegisterMap(String classAndMethodDesc) {
return VMDebug.cacheRegisterMap(classAndMethodDesc);
}
/**
* Dumps the contents of VM reference tables (e.g. JNI locals and
* globals) to the log file.
*
* @hide
*/
@UnsupportedAppUsage
public static final void dumpReferenceTables() {
VMDebug.dumpReferenceTables();
}
/**
* API for gathering and querying instruction counts.
*
* Example usage:
* <pre>
* Debug.InstructionCount icount = new Debug.InstructionCount();
* icount.resetAndStart();
* [... do lots of stuff ...]
* if (icount.collect()) {
* System.out.println("Total instructions executed: "
* + icount.globalTotal());
* System.out.println("Method invocations: "
* + icount.globalMethodInvocations());
* }
* </pre>
*
* @deprecated Instruction counting is no longer supported.
*/
@Deprecated
public static class InstructionCount {
public InstructionCount() {
}
/**
* Reset counters and ensure counts are running. Counts may
* have already been running.
*
* @return true if counting was started
*/
public boolean resetAndStart() {
return false;
}
/**
* Collect instruction counts. May or may not stop the
* counting process.
*/
public boolean collect() {
return false;
}
/**
* Return the total number of instructions executed globally (i.e. in
* all threads).
*/
public int globalTotal() {
return 0;
}
/**
* Return the total number of method-invocation instructions
* executed globally.
*/
public int globalMethodInvocations() {
return 0;
}
}
/**
* A Map of typed debug properties.
*/
private static final TypedProperties debugProperties;
/*
* Load the debug properties from the standard files into debugProperties.
*/
static {
if (false) {
final String TAG = "DebugProperties";
final String[] files = { "/system/debug.prop", "/debug.prop", "/data/debug.prop" };
final TypedProperties tp = new TypedProperties();
// Read the properties from each of the files, if present.
for (String file : files) {
Reader r;
try {
r = new FileReader(file);
} catch (FileNotFoundException ex) {
// It's ok if a file is missing.
continue;
}
try {
tp.load(r);
} catch (Exception ex) {
throw new RuntimeException("Problem loading " + file, ex);
} finally {
try {
r.close();
} catch (IOException ex) {
// Ignore this error.
}
}
}
debugProperties = tp.isEmpty() ? null : tp;
} else {
debugProperties = null;
}
}
/**
* Returns true if the type of the field matches the specified class.
* Handles the case where the class is, e.g., java.lang.Boolean, but
* the field is of the primitive "boolean" type. Also handles all of
* the java.lang.Number subclasses.
*/
private static boolean fieldTypeMatches(Field field, Class<?> cl) {
Class<?> fieldClass = field.getType();
if (fieldClass == cl) {
return true;
}
Field primitiveTypeField;
try {
/* All of the classes we care about (Boolean, Integer, etc.)
* have a Class field called "TYPE" that points to the corresponding
* primitive class.
*/
primitiveTypeField = cl.getField("TYPE");
} catch (NoSuchFieldException ex) {
return false;
}
try {
return fieldClass == (Class<?>) primitiveTypeField.get(null);
} catch (IllegalAccessException ex) {
return false;
}
}
/**
* Looks up the property that corresponds to the field, and sets the field's value
* if the types match.
*/
private static void modifyFieldIfSet(final Field field, final TypedProperties properties,
final String propertyName) {
if (field.getType() == java.lang.String.class) {
int stringInfo = properties.getStringInfo(propertyName);
switch (stringInfo) {
case TypedProperties.STRING_SET:
// Handle as usual below.
break;
case TypedProperties.STRING_NULL:
try {
field.set(null, null); // null object for static fields; null string
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Cannot set field for " + propertyName, ex);
}
return;
case TypedProperties.STRING_NOT_SET:
return;
case TypedProperties.STRING_TYPE_MISMATCH:
throw new IllegalArgumentException(
"Type of " + propertyName + " " +
" does not match field type (" + field.getType() + ")");
default:
throw new IllegalStateException(
"Unexpected getStringInfo(" + propertyName + ") return value " +
stringInfo);
}
}
Object value = properties.get(propertyName);
if (value != null) {
if (!fieldTypeMatches(field, value.getClass())) {
throw new IllegalArgumentException(
"Type of " + propertyName + " (" + value.getClass() + ") " +
" does not match field type (" + field.getType() + ")");
}
try {
field.set(null, value); // null object for static fields
} catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Cannot set field for " + propertyName, ex);
}
}
}
/**
* Equivalent to <code>setFieldsOn(cl, false)</code>.
*
* @see #setFieldsOn(Class, boolean)
*
* @hide
*/
public static void setFieldsOn(Class<?> cl) {
setFieldsOn(cl, false);
}
/**
* Reflectively sets static fields of a class based on internal debugging
* properties. This method is a no-op if false is
* false.
* <p>
* <strong>NOTE TO APPLICATION DEVELOPERS</strong>: false will
* always be false in release builds. This API is typically only useful
* for platform developers.
* </p>
* Class setup: define a class whose only fields are non-final, static
* primitive types (except for "char") or Strings. In a static block
* after the field definitions/initializations, pass the class to
* this method, Debug.setFieldsOn(). Example:
* <pre>
* package com.example;
*
* import android.os.Debug;
*
* public class MyDebugVars {
* public static String s = "a string";
* public static String s2 = "second string";
* public static String ns = null;
* public static boolean b = false;
* public static int i = 5;
* @Debug.DebugProperty
* public static float f = 0.1f;
* @@Debug.DebugProperty
* public static double d = 0.5d;
*
* // This MUST appear AFTER all fields are defined and initialized!
* static {
* // Sets all the fields
* Debug.setFieldsOn(MyDebugVars.class);
*
* // Sets only the fields annotated with @Debug.DebugProperty
* // Debug.setFieldsOn(MyDebugVars.class, true);
* }
* }
* </pre>
* setFieldsOn() may override the value of any field in the class based
* on internal properties that are fixed at boot time.
* <p>
* These properties are only set during platform debugging, and are not
* meant to be used as a general-purpose properties store.
*
* {@hide}
*
* @param cl The class to (possibly) modify
* @param partial If false, sets all static fields, otherwise, only set
* fields with the {@link android.os.Debug.DebugProperty}
* annotation
* @throws IllegalArgumentException if any fields are final or non-static,
* or if the type of the field does not match the type of
* the internal debugging property value.
*/
public static void setFieldsOn(Class<?> cl, boolean partial) {
if (false) {
if (debugProperties != null) {
/* Only look for fields declared directly by the class,
* so we don't mysteriously change static fields in superclasses.
*/
for (Field field : cl.getDeclaredFields()) {
if (!partial || field.getAnnotation(DebugProperty.class) != null) {
final String propertyName = cl.getName() + "." + field.getName();
boolean isStatic = Modifier.isStatic(field.getModifiers());
boolean isFinal = Modifier.isFinal(field.getModifiers());
if (!isStatic || isFinal) {
throw new IllegalArgumentException(propertyName +
" must be static and non-final");
}
modifyFieldIfSet(field, debugProperties, propertyName);
}
}
}
} else {
Log.wtf(TAG,
"setFieldsOn(" + (cl == null ? "null" : cl.getName()) +
") called in non-DEBUG build");
}
}
/**
* Annotation to put on fields you want to set with
* {@link Debug#setFieldsOn(Class, boolean)}.
*
* @hide
*/
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DebugProperty {
}
/**
* Get a debugging dump of a system service by name.
*
* <p>Most services require the caller to hold android.permission.DUMP.
*
* @param name of the service to dump
* @param fd to write dump output to (usually an output log file)
* @param args to pass to the service's dump method, may be null
* @return true if the service was dumped successfully, false if
* the service could not be found or had an error while dumping
*/
public static boolean dumpService(String name, FileDescriptor fd, String[] args) {
IBinder service = ServiceManager.getService(name);
if (service == null) {
Log.e(TAG, "Can't find service to dump: " + name);
return false;
}
try {
service.dump(fd, args);
return true;
} catch (RemoteException e) {
Log.e(TAG, "Can't dump service: " + name, e);
return false;
}
}
/**
* Append the Java stack traces of a given native process to a specified file.
*
* @param pid pid to dump.
* @param file path of file to append dump to.
* @param timeoutSecs time to wait in seconds, or 0 to wait forever.
* @hide
*/
public static native boolean dumpJavaBacktraceToFileTimeout(int pid, String file,
int timeoutSecs);
/**
* Append the native stack traces of a given process to a specified file.
*
* @param pid pid to dump.
* @param file path of file to append dump to.
* @param timeoutSecs time to wait in seconds, or 0 to wait forever.
* @hide
*/
public static native boolean dumpNativeBacktraceToFileTimeout(int pid, String file,
int timeoutSecs);
/**
* Get description of unreachable native memory.
* @param limit the number of leaks to provide info on, 0 to only get a summary.
* @param contents true to include a hex dump of the contents of unreachable memory.
* @return the String containing a description of unreachable memory.
* @hide */
public static native String getUnreachableMemory(int limit, boolean contents);
/**
* Return a String describing the calling method and location at a particular stack depth.
* @param callStack the Thread stack
* @param depth the depth of stack to return information for.
* @return the String describing the caller at that depth.
*/
private static String getCaller(StackTraceElement callStack[], int depth) {
// callStack[4] is the caller of the method that called getCallers()
if (4 + depth >= callStack.length) {
return "<bottom of call stack>";
}
StackTraceElement caller = callStack[4 + depth];
return caller.getClassName() + "." + caller.getMethodName() + ":" + caller.getLineNumber();
}
/**
* Return a string consisting of methods and locations at multiple call stack levels.
* @param depth the number of levels to return, starting with the immediate caller.
* @return a string describing the call stack.
* {@hide}
*/
@UnsupportedAppUsage
public static String getCallers(final int depth) {
final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < depth; i++) {
sb.append(getCaller(callStack, i)).append(" ");
}
return sb.toString();
}
/**
* Return a string consisting of methods and locations at multiple call stack levels.
* @param depth the number of levels to return, starting with the immediate caller.
* @return a string describing the call stack.
* {@hide}
*/
public static String getCallers(final int start, int depth) {
final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
StringBuffer sb = new StringBuffer();
depth += start;
for (int i = start; i < depth; i++) {
sb.append(getCaller(callStack, i)).append(" ");
}
return sb.toString();
}
/**
* Like {@link #getCallers(int)}, but each location is append to the string
* as a new line with <var>linePrefix</var> in front of it.
* @param depth the number of levels to return, starting with the immediate caller.
* @param linePrefix prefix to put in front of each location.
* @return a string describing the call stack.
* {@hide}
*/
public static String getCallers(final int depth, String linePrefix) {
final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < depth; i++) {
sb.append(linePrefix).append(getCaller(callStack, i)).append("\n");
}
return sb.toString();
}
/**
* @return a String describing the immediate caller of the calling method.
* {@hide}
*/
@UnsupportedAppUsage
public static String getCaller() {
return getCaller(Thread.currentThread().getStackTrace(), 0);
}
/**
* Attach a library as a jvmti agent to the current runtime, with the given classloader
* determining the library search path.
* <p>
* Note: agents may only be attached to debuggable apps. Otherwise, this function will
* throw a SecurityException.
*
* @param library the library containing the agent.
* @param options the options passed to the agent.
* @param classLoader the classloader determining the library search path.
*
* @throws IOException if the agent could not be attached.
* @throws SecurityException if the app is not debuggable.
*/
public static void attachJvmtiAgent(@NonNull String library, @Nullable String options,
@Nullable ClassLoader classLoader) throws IOException {
Preconditions.checkNotNull(library);
Preconditions.checkArgument(!library.contains("="));
if (options == null) {
VMDebug.attachAgent(library, classLoader);
} else {
VMDebug.attachAgent(library + "=" + options, classLoader);
}
}
/**
* Return the current free ZRAM usage in kilobytes.
*
* @hide
*/
public static native long getZramFreeKb();
}
|