DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (1aeaa33a64f9)

VCS Links

Line Code
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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

from __future__ import absolute_import

import os
import posixpath
import re
import shutil
import subprocess
import tempfile
import time
import traceback

from abc import ABCMeta, abstractmethod
from distutils import dir_util


class ADBProcess(object):
    """ADBProcess encapsulates the data related to executing the adb process."""

    def __init__(self, args):
        #: command argument argument list.
        self.args = args
        #: Temporary file handle to be used for stdout.
        self.stdout_file = tempfile.TemporaryFile()
        #: boolean indicating if the command timed out.
        self.timedout = None
        #: exitcode of the process.
        self.exitcode = None
        #: subprocess Process object used to execute the command.
        self.proc = subprocess.Popen(args,
                                     stdout=self.stdout_file,
                                     stderr=subprocess.STDOUT)

    @property
    def stdout(self):
        """Return the contents of stdout."""
        if not self.stdout_file or self.stdout_file.closed:
            content = ""
        else:
            self.stdout_file.seek(0, os.SEEK_SET)
            content = self.stdout_file.read().rstrip()
        return content

    def __str__(self):
        return ('args: %s, exitcode: %s, stdout: %s' % (
            ' '.join(self.args), self.exitcode, self.stdout))

# ADBError, ADBRootError, and ADBTimeoutError are treated
# differently in order that unhandled ADBRootErrors and
# ADBTimeoutErrors can be handled distinctly from ADBErrors.


class ADBError(Exception):
    """ADBError is raised in situations where a command executed on a
    device either exited with a non-zero exitcode or when an
    unexpected error condition has occurred. Generally, ADBErrors can
    be handled and the device can continue to be used.
    """
    pass


class ADBListDevicesError(ADBError):
    """ADBListDevicesError is raised when errors are found listing the
    devices, typically not any permissions.

    The devices information is stocked with the *devices* member.
    """

    def __init__(self, msg, devices):
        ADBError.__init__(self, msg)
        self.devices = devices


class ADBRootError(Exception):
    """ADBRootError is raised when a shell command is to be executed as
    root but the device does not support it. This error is fatal since
    there is no recovery possible by the script. You must either root
    your device or change your scripts to not require running as root.
    """
    pass


class ADBTimeoutError(Exception):
    """ADBTimeoutError is raised when either a host command or shell
    command takes longer than the specified timeout to execute. The
    timeout value is set in the ADBCommand constructor and is 300 seconds by
    default. This error is typically fatal since the host is having
    problems communicating with the device. You may be able to recover
    by rebooting, but this is not guaranteed.

    Recovery options are:

    * Killing and restarting the adb server via
      ::

          adb kill-server; adb start-server

    * Rebooting the device manually.
    * Rebooting the host.
    """
    pass


class ADBCommand(object):
    """ADBCommand provides a basic interface to adb commands
    which is used to provide the 'command' methods for the
    classes ADBHost and ADBDevice.

    ADBCommand should only be used as the base class for other
    classes and should not be instantiated directly. To enforce this
    restriction calling ADBCommand's constructor will raise a
    NonImplementedError exception.

    ::

       from mozdevice import ADBCommand

       try:
           adbcommand = ADBCommand()
       except NotImplementedError:
           print "ADBCommand can not be instantiated."
    """

    def __init__(self,
                 adb='adb',
                 adb_host=None,
                 adb_port=None,
                 logger_name='adb',
                 timeout=300,
                 verbose=False):
        """Initializes the ADBCommand object.

        :param str adb: path to adb executable. Defaults to 'adb'.
        :param adb_host: host of the adb server.
        :type adb_host: str or None
        :param adb_port: port of the adb server.
        :type adb_port: integer or None
        :param str logger_name: logging logger name. Defaults to 'adb'.

        :raises: * ADBError
                 * ADBTimeoutError
        """
        if self.__class__ == ADBCommand:
            raise NotImplementedError

        self._logger = self._get_logger(logger_name)
        self._verbose = verbose
        self._adb_path = adb
        self._adb_host = adb_host
        self._adb_port = adb_port
        self._timeout = timeout
        self._polling_interval = 0.1
        self._adb_version = ''

        self._logger.debug("%s: %s" % (self.__class__.__name__,
                                       self.__dict__))

        # catch early a missing or non executable adb command
        # and get the adb version while we are at it.
        try:
            output = subprocess.Popen([adb, 'version'],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE).communicate()
            re_version = re.compile(r'Android Debug Bridge version (.*)')
            self._adb_version = re_version.match(output[0]).group(1)
        except Exception as exc:
            raise ADBError('%s: %s is not executable.' % (exc, adb))

    def _get_logger(self, logger_name):
        logger = None
        try:
            import mozlog
            logger = mozlog.get_default_logger(logger_name)
        except ImportError:
            pass

        if logger is None:
            import logging
            logger = logging.getLogger(logger_name)
        return logger

    # Host Command methods

    def command(self, cmds, device_serial=None, timeout=None):
        """Executes an adb command on the host.

        :param list cmds: The command and its arguments to be
            executed.
        :param device_serial: The device's
            serial number if the adb command is to be executed against
            a specific device.
        :type device_serial: str or None
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBCommand constructor is used.
        :type timeout: integer or None
        :returns: :class:`mozdevice.ADBProcess`

        command() provides a low level interface for executing
        commands on the host via adb.

        command() executes on the host in such a fashion that stdout
        of the adb process is a file handle on the host and
        the exit code is available as the exit code of the adb
        process.

        The caller provides a list containing commands, as well as a
        timeout period in seconds.

        A subprocess is spawned to execute adb with stdout and stderr
        directed to a temporary file. If the process takes longer than
        the specified timeout, the process is terminated.

        It is the caller's responsibilty to clean up by closing
        the stdout temporary file.
        """
        args = [self._adb_path]
        if self._adb_host:
            args.extend(['-H', self._adb_host])
        if self._adb_port:
            args.extend(['-P', str(self._adb_port)])
        if device_serial:
            args.extend(['-s', device_serial, 'wait-for-device'])
        args.extend(cmds)

        adb_process = ADBProcess(args)

        if timeout is None:
            timeout = self._timeout

        start_time = time.time()
        adb_process.exitcode = adb_process.proc.poll()
        while ((time.time() - start_time) <= timeout and
               adb_process.exitcode is None):
            time.sleep(self._polling_interval)
            adb_process.exitcode = adb_process.proc.poll()
        if adb_process.exitcode is None:
            adb_process.proc.kill()
            adb_process.timedout = True
            adb_process.exitcode = adb_process.proc.poll()

        adb_process.stdout_file.seek(0, os.SEEK_SET)

        return adb_process

    def command_output(self, cmds, device_serial=None, timeout=None):
        """Executes an adb command on the host returning stdout.

        :param list cmds: The command and its arguments to be
            executed.
        :param device_serial: The device's
            serial number if the adb command is to be executed against
            a specific device.
        :type device_serial: str or None
        :param timeout: The maximum time in seconds
            for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBCommand constructor is used.
        :type timeout: integer or None
        :returns: string - content of stdout.

        :raises: * ADBTimeoutError
                 * ADBError
        """
        adb_process = None
        try:
            # Need to force the use of the ADBCommand class's command
            # since ADBDevice will redefine command and call its
            # own version otherwise.
            adb_process = ADBCommand.command(self, cmds,
                                             device_serial=device_serial,
                                             timeout=timeout)
            if adb_process.timedout:
                raise ADBTimeoutError("%s" % adb_process)
            elif adb_process.exitcode:
                raise ADBError("%s" % adb_process)
            output = adb_process.stdout_file.read().rstrip()
            if self._verbose:
                self._logger.debug('command_output: %s, '
                                   'timeout: %s, '
                                   'timedout: %s, '
                                   'exitcode: %s, output: %s' %
                                   (' '.join(adb_process.args),
                                    timeout,
                                    adb_process.timedout,
                                    adb_process.exitcode,
                                    output))

            return output
        finally:
            if adb_process and isinstance(adb_process.stdout_file, file):
                adb_process.stdout_file.close()


class ADBHost(ADBCommand):
    """ADBHost provides a basic interface to adb host commands
    which do not target a specific device.

    ::

       from mozdevice import ADBHost

       adbhost = ADBHost()
       adbhost.start_server()
    """

    def __init__(self,
                 adb='adb',
                 adb_host=None,
                 adb_port=None,
                 logger_name='adb',
                 timeout=300,
                 verbose=False):
        """Initializes the ADBHost object.

        :param str adb: path to adb executable. Defaults to 'adb'.
        :param adb_host: host of the adb server.
        :type adb_host: str or None
        :param adb_port: port of the adb server.
        :type adb_port: integer or None
        :param str logger_name: logging logger name. Defaults to 'adb'.

        :raises: * ADBError
                 * ADBTimeoutError
        """
        ADBCommand.__init__(self, adb=adb, adb_host=adb_host,
                            adb_port=adb_port, logger_name=logger_name,
                            timeout=timeout, verbose=verbose)

    def command(self, cmds, timeout=None):
        """Executes an adb command on the host.

        :param list cmds: The command and its arguments to be
            executed.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBHost constructor is used.
        :type timeout: integer or None
        :returns: :class:`mozdevice.ADBProcess`

        command() provides a low level interface for executing
        commands on the host via adb.

        command() executes on the host in such a fashion that stdout
        of the adb process is a file handle on the host and
        the exit code is available as the exit code of the adb
        process.

        The caller provides a list containing commands, as well as a
        timeout period in seconds.

        A subprocess is spawned to execute adb with stdout and stderr
        directed to a temporary file. If the process takes longer than
        the specified timeout, the process is terminated.

        It is the caller's responsibilty to clean up by closing
        the stdout temporary file.
        """
        return ADBCommand.command(self, cmds, timeout=timeout)

    def command_output(self, cmds, timeout=None):
        """Executes an adb command on the host returning stdout.

        :param list cmds: The command and its arguments to be
            executed.
        :param timeout: The maximum time in seconds
            for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBHost constructor is used.
        :type timeout: integer or None
        :returns: string - content of stdout.

        :raises: * ADBTimeoutError
                 * ADBError
        """
        return ADBCommand.command_output(self, cmds, timeout=timeout)

    def start_server(self, timeout=None):
        """Starts the adb server.

        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBHost constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError

        Attempting to use start_server with any adb_host value other than None
        will fail with an ADBError exception.

        You will need to start the server on the remote host via the command:

        .. code-block:: shell

            adb -a fork-server server

        If you wish the remote adb server to restart automatically, you can
        enclose the command in a loop as in:

        .. code-block:: shell

            while true; do
              adb -a fork-server server
            done
        """
        self.command_output(["start-server"], timeout=timeout)

    def kill_server(self, timeout=None):
        """Kills the adb server.

        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBHost constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError
        """
        self.command_output(["kill-server"], timeout=timeout)

    def devices(self, timeout=None):
        """Executes adb devices -l and returns a list of objects describing attached devices.

        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBHost constructor is used.
        :type timeout: integer or None
        :returns: an object contain
        :raises: * ADBTimeoutError
                 * ADBListDevicesError
                 * ADBError

        The output of adb devices -l ::

            $ adb devices -l
            List of devices attached
            b313b945               device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw

        is parsed and placed into an object as in

        [{'device_serial': 'b313b945', 'state': 'device', 'product': 'd2vzw',
          'usb': '1-7', 'device': 'd2vzw', 'model': 'SCH_I535' }]
        """
        # b313b945               device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw
        # from Android system/core/adb/transport.c statename()
        re_device_info = re.compile(
            r"([^\s]+)\s+(offline|bootloader|device|host|recovery|sideload|"
            "no permissions|unauthorized|unknown)")
        devices = []
        lines = self.command_output(["devices", "-l"], timeout=timeout).splitlines()
        for line in lines:
            if line == 'List of devices attached ':
                continue
            match = re_device_info.match(line)
            if match:
                device = {
                    'device_serial': match.group(1),
                    'state': match.group(2)
                }
                remainder = line[match.end(2):].strip()
                if remainder:
                    try:
                        device.update(dict([j.split(':')
                                            for j in remainder.split(' ')]))
                    except ValueError:
                        self._logger.warning('devices: Unable to parse '
                                             'remainder for device %s' % line)
                devices.append(device)
        for device in devices:
            if device['state'] == 'no permissions':
                raise ADBListDevicesError(
                    "No permissions to detect devices. You should restart the"
                    " adb server as root:\n"
                    "\n# adb kill-server\n# adb start-server\n"
                    "\nor maybe configure your udev rules.",
                    devices)
        return devices


class ADBDevice(ADBCommand):
    """ADBDevice is an abstract base class which provides methods which
    can be used to interact with the associated Android or B2G based
    device. It must be used via one of the concrete implementations in
    :class:`ADBAndroid` or :class:`ADBB2G`.
    """
    __metaclass__ = ABCMeta

    def __init__(self,
                 device=None,
                 adb='adb',
                 adb_host=None,
                 adb_port=None,
                 test_root='',
                 logger_name='adb',
                 timeout=300,
                 verbose=False,
                 device_ready_retry_wait=20,
                 device_ready_retry_attempts=3):
        """Initializes the ADBDevice object.

        :param device: When a string is passed, it is interpreted as the
            device serial number. This form is not compatible with
            devices containing a ":" in the serial; in this case
            ValueError will be raised.
            When a dictionary is passed it must have one or both of
            the keys "device_serial" and "usb". This is compatible
            with the dictionaries in the list returned by
            ADBHost.devices(). If the value of device_serial is a
            valid serial not containing a ":" it will be used to
            identify the device, otherwise the value of the usb key,
            prefixed with "usb:" is used.
            If None is passed and there is exactly one device attached
            to the host, that device is used. If there is more than one
            device attached, ValueError is raised. If no device is
            attached the constructor will block until a device is
            attached or the timeout is reached.
        :type device: dict, str or None
        :param adb_host: host of the adb server to connect to.
        :type adb_host: str or None
        :param adb_port: port of the adb server to connect to.
        :type adb_port: integer or None
        :param str logger_name: logging logger name. Defaults to 'adb'.
        :param integer device_ready_retry_wait: number of seconds to wait
            between attempts to check if the device is ready after a
            reboot.
        :param integer device_ready_retry_attempts: number of attempts when
            checking if a device is ready.

        :raises: * ADBError
                 * ADBTimeoutError
                 * ValueError
        """
        ADBCommand.__init__(self, adb=adb, adb_host=adb_host,
                            adb_port=adb_port, logger_name=logger_name,
                            timeout=timeout, verbose=verbose)
        self._device_serial = self._get_device_serial(device)
        self._initial_test_root = test_root
        self._test_root = None
        self._device_ready_retry_wait = device_ready_retry_wait
        self._device_ready_retry_attempts = device_ready_retry_attempts
        self._have_root_shell = False
        self._have_su = False
        self._have_android_su = False

        # Catch exceptions due to the potential for segfaults
        # calling su when using an improperly rooted device.

        # Note this check to see if adbd is running is performed on
        # the device in the state it exists in when the ADBDevice is
        # initialized. It may be the case that it has been manipulated
        # since its last boot and that its current state does not
        # match the state the device will have immediately after a
        # reboot. For example, if adb root was called manually prior
        # to ADBDevice being initialized, then self._have_root_shell
        # will not reflect the state of the device after it has been
        # rebooted again. Therefore this check will need to be
        # performed again after a reboot.

        self._check_adb_root(timeout=timeout)

        uid = 'uid=0'
        # Do we have a 'Superuser' sh like su?
        try:
            if self.shell_output("su -c id", timeout=timeout).find(uid) != -1:
                self._have_su = True
                self._logger.info("su -c supported")
        except ADBError:
            self._logger.debug("Check for su -c failed")

        # Do we have Android's su?
        try:
            if self.shell_output("su 0 id", timeout=timeout).find(uid) != -1:
                self._have_android_su = True
                self._logger.info("su 0 supported")
        except ADBError:
            self._logger.debug("Check for su 0 failed")

        self._mkdir_p = None
        # Force the use of /system/bin/ls or /system/xbin/ls in case
        # there is /sbin/ls which embeds ansi escape codes to colorize
        # the output.  Detect if we are using busybox ls. We want each
        # entry on a single line and we don't want . or ..
        if self.shell_bool("/system/bin/ls /data/local/tmp", timeout=timeout):
            self._ls = "/system/bin/ls"
        elif self.shell_bool("/system/xbin/ls /data/local/tmp", timeout=timeout):
            self._ls = "/system/xbin/ls"
        else:
            raise ADBError("ADBDevice.__init__: ls not found")
        try:
            self.shell_output("%s -1A /data/local/tmp" % self._ls, timeout=timeout)
            self._ls += " -1A"
        except ADBError:
            self._ls += " -a"

        self._logger.info("%s supported" % self._ls)

        # Do we have cp?
        self._have_cp = self.shell_bool("type cp", timeout=timeout)
        self._logger.info("Native cp support: %s" % self._have_cp)

        # Do we have chmod -R?
        try:
            self._chmod_R = False
            re_recurse = re.compile(r'[-]R')
            chmod_output = self.shell_output("chmod --help", timeout=timeout)
            match = re_recurse.search(chmod_output)
            if match:
                self._chmod_R = True
        except (ADBError, ADBTimeoutError) as e:
            self._logger.debug('Check chmod -R: %s' % e)
            match = re_recurse.search(e.message)
            if match:
                self._chmod_R = True
        self._logger.info("Native chmod -R support: %s" % self._chmod_R)

        self._logger.debug("ADBDevice: %s" % self.__dict__)

    def _get_device_serial(self, device):
        if device is None:
            devices = ADBHost(adb=self._adb_path, adb_host=self._adb_host,
                              adb_port=self._adb_port).devices()
            if len(devices) > 1:
                raise ValueError("ADBDevice called with multiple devices "
                                 "attached and no device specified")
            elif len(devices) == 0:
                # We could error here, but this way we'll wait-for-device before we next
                # run a command, which seems more friendly
                return
            device = devices[0]

        def is_valid_serial(serial):
            return ":" not in serial or serial.startswith("usb:")

        if isinstance(device, (str, unicode)):
            # Treat this as a device serial
            if not is_valid_serial(device):
                raise ValueError("Device serials containing ':' characters are "
                                 "invalid. Pass the output from "
                                 "ADBHost.devices() for the device instead")
            return device

        serial = device.get("device_serial")
        if serial is not None and is_valid_serial(serial):
            return serial
        usb = device.get("usb")
        if usb is not None:
            return "usb:%s" % usb

        raise ValueError("Unable to get device serial")

    def _check_adb_root(self, timeout=None):
        self._have_root_shell = False
        uid = 'uid=0'
        # Is shell already running as root?
        try:
            if self.shell_output("id", timeout=timeout).find(uid) != -1:
                self._have_root_shell = True
                self._logger.info("adbd running as root")
        except ADBError:
            self._logger.debug("Check for root shell failed")

        # Do we need to run adb root to get a root shell?
        try:
            if (not self._have_root_shell and self.command_output(
                    ["root"],
                    timeout=timeout).find("cannot run as root") == -1):
                self._have_root_shell = True
                self._logger.info("adbd restarted as root")
        except ADBError:
            self._logger.debug("Check for root adbd failed")

    @staticmethod
    def _escape_command_line(cmd):
        """Utility function to return escaped and quoted version of command
        line.
        """
        quoted_cmd = []

        for arg in cmd:
            arg.replace('&', r'\&')

            needs_quoting = False
            for char in [' ', '(', ')', '"', '&']:
                if arg.find(char) >= 0:
                    needs_quoting = True
                    break
            if needs_quoting:
                arg = "'%s'" % arg

            quoted_cmd.append(arg)

        return " ".join(quoted_cmd)

    @staticmethod
    def _get_exitcode(file_obj):
        """Get the exitcode from the last line of the file_obj for shell
        commands.
        """
        file_obj.seek(0, os.SEEK_END)

        line = ''
        length = file_obj.tell()
        offset = 1
        while length - offset >= 0:
            file_obj.seek(-offset, os.SEEK_END)
            char = file_obj.read(1)
            if not char:
                break
            if char != '\r' and char != '\n':
                line = char + line
            elif line:
                # we have collected everything up to the beginning of the line
                break
            offset += 1

        match = re.match(r'rc=([0-9]+)', line)
        if match:
            exitcode = int(match.group(1))
            file_obj.seek(-1, os.SEEK_CUR)
            file_obj.truncate()
        else:
            exitcode = None

        return exitcode

    @property
    def test_root(self):
        """
        The test_root property returns the directory on the device where
        temporary test files are stored.

        The first time test_root it is called it determines and caches a value
        for the test root on the device. It determines the appropriate test
        root by attempting to create a 'dummy' directory on each of a list of
        directories and returning the first successful directory as the
        test_root value.

        The default list of directories checked by test_root are:

        - /storage/sdcard0/tests
        - /storage/sdcard1/tests
        - /sdcard/tests
        - /mnt/sdcard/tests
        - /data/local/tests

        You may override the default list by providing a test_root argument to
        the :class:`ADBDevice` constructor which will then be used when
        attempting to create the 'dummy' directory.

        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        if self._test_root is not None:
            return self._test_root

        if self._initial_test_root:
            paths = [self._initial_test_root]
        else:
            paths = ['/storage/sdcard0/tests',
                     '/storage/sdcard1/tests',
                     '/sdcard/tests',
                     '/mnt/sdcard/tests',
                     '/data/local/tests']

        max_attempts = 3
        for attempt in range(1, max_attempts + 1):
            for test_root in paths:
                self._logger.debug("Setting test root to %s attempt %d of %d" %
                                   (test_root, attempt, max_attempts))

                if self._try_test_root(test_root):
                    self._test_root = test_root
                    return self._test_root

                self._logger.debug('_setup_test_root: '
                                   'Attempt %d of %d failed to set test_root to %s' %
                                   (attempt, max_attempts, test_root))

            if attempt != max_attempts:
                time.sleep(20)

        raise ADBError("Unable to set up test root using paths: [%s]"
                       % ", ".join(paths))

    def _try_test_root(self, test_root):
        base_path, sub_path = posixpath.split(test_root)
        if not self.is_dir(base_path):
            return False

        try:
            dummy_dir = posixpath.join(test_root, 'dummy')
            if self.is_dir(dummy_dir):
                self.rm(dummy_dir, recursive=True)
            self.mkdir(dummy_dir, parents=True)
        except ADBError:
            self._logger.debug("%s is not writable" % test_root)
            return False

        return True

    # Host Command methods

    def command(self, cmds, timeout=None):
        """Executes an adb command on the host against the device.

        :param list cmds: The command and its arguments to be
            executed.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: :class:`mozdevice.ADBProcess`

        command() provides a low level interface for executing
        commands for a specific device on the host via adb.

        command() executes on the host in such a fashion that stdout
        of the adb process are file handles on the host and
        the exit code is available as the exit code of the adb
        process.

        For executing shell commands on the device, use
        ADBDevice.shell().  The caller provides a list containing
        commands, as well as a timeout period in seconds.

        A subprocess is spawned to execute adb for the device with
        stdout and stderr directed to a temporary file. If the process
        takes longer than the specified timeout, the process is
        terminated.

        It is the caller's responsibilty to clean up by closing
        the stdout temporary file.
        """

        return ADBCommand.command(self, cmds,
                                  device_serial=self._device_serial,
                                  timeout=timeout)

    def command_output(self, cmds, timeout=None):
        """Executes an adb command on the host against the device returning
        stdout.

        :param list cmds: The command and its arguments to be executed.
        :param timeout: The maximum time in seconds
            for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: string - content of stdout.

        :raises: * ADBTimeoutError
                 * ADBError
        """
        return ADBCommand.command_output(self, cmds,
                                         device_serial=self._device_serial,
                                         timeout=timeout)

    # Port forwarding methods

    def _validate_port(self, port, is_local=True):
        """Validate a port forwarding specifier. Raises ValueError on failure.

        :param str port: The port specifier to validate
        :param bool is_local: Flag indicating whether the port represents a local port.
        """
        prefixes = ["tcp", "localabstract", "localreserved", "localfilesystem", "dev"]

        if not is_local:
            prefixes += ["jdwp"]

        parts = port.split(":", 1)
        if len(parts) != 2 or parts[0] not in prefixes:
            raise ValueError("Invalid forward specifier %s" % port)

    def forward(self, local, remote, allow_rebind=True, timeout=None):
        """Forward a local port to a specific port on the device.

        Ports are specified in the form:
            tcp:<port>
            localabstract:<unix domain socket name>
            localreserved:<unix domain socket name>
            localfilesystem:<unix domain socket name>
            dev:<character device name>
            jdwp:<process pid> (remote only)

        :param str local: Local port to forward
        :param str remote: Remote port to which to forward
        :param bool allow_rebind: Don't error if the local port is already forwarded
        :param timeout: The maximum time in seconds
            for any spawned adb process to complete before throwing
            an ADBTimeoutError. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ValueError
                 * ADBTimeoutError
                 * ADBError
        """

        for port, is_local in [(local, True), (remote, False)]:
            self._validate_port(port, is_local=is_local)

        cmd = ["forward", local, remote]
        if not allow_rebind:
            cmd.insert(1, "--no-rebind")
        self.command_output(cmd, timeout=timeout)

    def list_forwards(self, timeout=None):
        """Return a list of tuples specifying active forwards

        Return values are of the form (device, local, remote).

        :param timeout: The maximum time in seconds
            for any spawned adb process to complete before throwing
            an ADBTimeoutError. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError
        """
        forwards = self.command_output(["forward", "--list"], timeout=timeout)
        return [tuple(line.split(" ")) for line in forwards.splitlines() if line.strip()]

    def remove_forwards(self, local=None, timeout=None):
        """Remove existing port forwards.

        :param local: local port specifier as for ADBDevice.forward. If local
            is not specified removes all forwards.
        :type local: str or None
        :param timeout: The maximum time in seconds
            for any spawned adb process to complete before throwing
            an ADBTimeoutError. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ValueError
                 * ADBTimeoutError
                 * ADBError
        """
        cmd = ["forward"]
        if local is None:
            cmd.extend(["--remove-all"])
        else:
            self._validate_port(local, is_local=True)
            cmd.extend(["--remove", local])

        self.command_output(cmd, timeout=timeout)

    # Device Shell methods

    def shell(self, cmd, env=None, cwd=None, timeout=None, root=False):
        """Executes a shell command on the device.

        :param str cmd: The command to be executed.
        :param env: Contains the environment variables and
            their values.
        :type env: dict or None
        :param cwd: The directory from which to execute.
        :type cwd: str or None
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per adb call. The
            total time spent may exceed this value. If it is not
            specified, the value set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :returns: :class:`mozdevice.ADBProcess`
        :raises: ADBRootError

        shell() provides a low level interface for executing commands
        on the device via adb shell.

        shell() executes on the host in such as fashion that stdout
        contains the stdout and stderr of the host abd process
        combined with the stdout and stderr of the shell command
        on the device. The exit code of shell() is the exit code of
        the adb command if it was non-zero or the extracted exit code
        from the output of the shell command executed on the
        device.

        The caller provides a flag indicating if the command is to be
        executed as root, a string for any requested working
        directory, a hash defining the environment, a string
        containing shell commands, as well as a timeout period in
        seconds.

        The command line to be executed is created to set the current
        directory, set the required environment variables, optionally
        execute the command using su and to output the return code of
        the command to stdout. The command list is created as a
        command sequence separated by && which will terminate the
        command sequence on the first command which returns a non-zero
        exit code.

        A subprocess is spawned to execute adb shell for the device
        with stdout and stderr directed to a temporary file. If the
        process takes longer than the specified timeout, the process
        is terminated. The return code is extracted from the stdout
        and is then removed from the file.

        It is the caller's responsibilty to clean up by closing
        the stdout temporary files.

        """
        if root and not self._have_root_shell:
            # If root was requested and we do not already have a root
            # shell, then use the appropriate version of su to invoke
            # the shell cmd. Prefer Android's su version since it may
            # falsely report support for su -c.
            if self._have_android_su:
                cmd = "su 0 %s" % cmd
            elif self._have_su:
                cmd = "su -c \"%s\"" % cmd
            else:
                raise ADBRootError('Can not run command %s as root!' % cmd)

        # prepend cwd and env to command if necessary
        if cwd:
            cmd = "cd %s && %s" % (cwd, cmd)
        if env:
            envstr = '&& '.join(map(lambda x: 'export %s=%s' %
                                    (x[0], x[1]), env.iteritems()))
            cmd = envstr + "&& " + cmd
        cmd += "; echo rc=$?"

        args = [self._adb_path]
        if self._adb_host:
            args.extend(['-H', self._adb_host])
        if self._adb_port:
            args.extend(['-P', str(self._adb_port)])
        if self._device_serial:
            args.extend(['-s', self._device_serial])
        args.extend(["wait-for-device", "shell", cmd])
        adb_process = ADBProcess(args)

        if timeout is None:
            timeout = self._timeout

        start_time = time.time()
        exitcode = adb_process.proc.poll()
        while ((time.time() - start_time) <= timeout) and exitcode is None:
            time.sleep(self._polling_interval)
            exitcode = adb_process.proc.poll()
        if exitcode is None:
            adb_process.proc.kill()
            adb_process.timedout = True
            adb_process.exitcode = adb_process.proc.poll()
        elif exitcode == 0:
            adb_process.exitcode = self._get_exitcode(adb_process.stdout_file)
        else:
            adb_process.exitcode = exitcode

        adb_process.stdout_file.seek(0, os.SEEK_SET)

        return adb_process

    def shell_bool(self, cmd, env=None, cwd=None, timeout=None, root=False):
        """Executes a shell command on the device returning True on success
        and False on failure.

        :param str cmd: The command to be executed.
        :param env: Contains the environment variables and
            their values.
        :type env: dict or None
        :param cwd: The directory from which to execute.
        :type cwd: str or None
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :returns: boolean

        :raises: * ADBTimeoutError
                 * ADBRootError
        """
        adb_process = None
        try:
            adb_process = self.shell(cmd, env=env, cwd=cwd,
                                     timeout=timeout, root=root)
            if adb_process.timedout:
                raise ADBTimeoutError("%s" % adb_process)
            return adb_process.exitcode == 0
        finally:
            if adb_process:
                adb_process.stdout_file.close()

    def shell_output(self, cmd, env=None, cwd=None, timeout=None, root=False):
        """Executes an adb shell on the device returning stdout.

        :param str cmd: The command to be executed.
        :param env: Contains the environment variables and their values.
        :type env: dict or None
        :param cwd: The directory from which to execute.
        :type cwd: str or None
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per
            adb call. The total time spent may exceed this
            value. If it is not specified, the value set
            in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command
            should be executed as root.
        :returns: string - content of stdout.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        adb_process = None
        try:
            adb_process = self.shell(cmd, env=env, cwd=cwd,
                                     timeout=timeout, root=root)
            if adb_process.timedout:
                raise ADBTimeoutError("%s" % adb_process)
            elif adb_process.exitcode:
                raise ADBError("%s" % adb_process)
            output = adb_process.stdout_file.read().rstrip()
            if self._verbose:
                self._logger.debug('shell_output: %s, '
                                   'timeout: %s, '
                                   'root: %s, '
                                   'timedout: %s, '
                                   'exitcode: %s, '
                                   'output: %s' %
                                   (' '.join(adb_process.args),
                                    timeout,
                                    root,
                                    adb_process.timedout,
                                    adb_process.exitcode,
                                    output))

            return output
        finally:
            if adb_process and isinstance(adb_process.stdout_file, file):
                adb_process.stdout_file.close()

    # Informational methods

    def _get_logcat_buffer_args(self, buffers):
        valid_buffers = set(['radio', 'main', 'events'])
        invalid_buffers = set(buffers).difference(valid_buffers)
        if invalid_buffers:
            raise ADBError('Invalid logcat buffers %s not in %s ' % (
                list(invalid_buffers), list(valid_buffers)))
        args = []
        for b in buffers:
            args.extend(['-b', b])
        return args

    def clear_logcat(self, timeout=None, buffers=[]):
        """Clears logcat via adb logcat -c.

        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.  This timeout is per
            adb call. The total time spent may exceed this
            value. If it is not specified, the value set
            in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param list buffers: Log buffers to clear. Valid buffers are
            "radio", "events", and "main". Defaults to "main".
        :raises: * ADBTimeoutError
                 * ADBError
        """
        buffers = self._get_logcat_buffer_args(buffers)
        cmds = ["logcat", "-c"] + buffers
        self.command_output(cmds, timeout=timeout)
        self.shell_output("log logcat cleared", timeout=timeout)

    def get_logcat(self,
                   filter_specs=[
                       "dalvikvm:I",
                       "ConnectivityService:S",
                       "WifiMonitor:S",
                       "WifiStateTracker:S",
                       "wpa_supplicant:S",
                       "NetworkStateTracker:S"],
                   format="time",
                   filter_out_regexps=[],
                   timeout=None,
                   buffers=[]):
        """Returns the contents of the logcat file as a list of strings.

        :param list filter_specs: Optional logcat messages to
            be included.
        :param str format: Optional logcat format.
        :param list filterOutRexps: Optional logcat messages to be
            excluded.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param list buffers: Log buffers to retrieve. Valid buffers are
            "radio", "events", and "main". Defaults to "main".
        :returns: list of lines logcat output.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        buffers = self._get_logcat_buffer_args(buffers)
        cmds = ["logcat", "-v", format, "-d"] + buffers + filter_specs
        lines = self.command_output(cmds, timeout=timeout).splitlines()

        for regex in filter_out_regexps:
            lines = [line for line in lines if not re.search(regex, line)]

        return lines

    def get_prop(self, prop, timeout=None):
        """Gets value of a property from the device via adb shell getprop.

        :param str prop: The propery name.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: string value of property.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        output = self.shell_output('getprop %s' % prop, timeout=timeout)
        return output

    def get_state(self, timeout=None):
        """Returns the device's state via adb get-state.

        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: string value of adb get-state.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        output = self.command_output(["get-state"], timeout=timeout).strip()
        return output

    def get_ip_address(self, interfaces=None, timeout=None):
        """Returns the device's ip address, or None if it doesn't have one

        :param interfaces: Interfaces to allow, or None to allow any
            non-loopback interface.
        :type interfaces: list or None
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: string ip address of the device or None if it could not
            be found.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        if not interfaces:
            interfaces = ["wlan0", "eth0"]
            wifi_interface = self.shell_output('getprop wifi.interface', timeout=timeout)
            self._logger.debug('get_ip_address: wifi_interface: %s' % wifi_interface)
            if wifi_interface and wifi_interface not in interfaces:
                interfaces = interfaces.append(wifi_interface)

        # ifconfig interface
        # can return two different formats:
        # eth0: ip 192.168.1.139 mask 255.255.255.0 flags [up broadcast running multicast]
        # or
        # wlan0     Link encap:Ethernet  HWaddr 00:9A:CD:B8:39:65
        # inet addr:192.168.1.38  Bcast:192.168.1.255  Mask:255.255.255.0
        # inet6 addr: fe80::29a:cdff:feb8:3965/64 Scope: Link
        # UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
        # RX packets:180 errors:0 dropped:0 overruns:0 frame:0
        # TX packets:218 errors:0 dropped:0 overruns:0 carrier:0
        # collisions:0 txqueuelen:1000
        # RX bytes:84577 TX bytes:31202

        re1_ip = re.compile(r'(\w+): ip ([0-9.]+) mask.*')
        # re1_ip will match output of the first format
        # with group 1 returning the interface and group 2 returing the ip address.

        # re2_interface will match the interface line in the second format
        # while re2_ip will match the inet addr line of the second format.
        re2_interface = re.compile(r'(\w+)\s+Link')
        re2_ip = re.compile(r'\s+inet addr:([0-9.]+)')

        matched_interface = None
        matched_ip = None
        re_bad_addr = re.compile(r'127.0.0.1|0.0.0.0')

        self._logger.debug('get_ip_address: ifconfig')
        for interface in interfaces:
            try:
                output = self.shell_output('ifconfig %s' % interface,
                                           timeout=timeout)
            except ADBError:
                output = ''

            for line in output.splitlines():
                if not matched_interface:
                    match = re1_ip.match(line)
                    if match:
                        matched_interface, matched_ip = match.groups()
                    else:
                        match = re2_interface.match(line)
                        if match:
                            matched_interface = match.group(1)
                else:
                    match = re2_ip.match(line)
                    if match:
                        matched_ip = match.group(1)

                if matched_ip:
                    if not re_bad_addr.match(matched_ip):
                        self._logger.debug('get_ip_address: found: %s %s' %
                                           (matched_interface, matched_ip))
                        return matched_ip
                    matched_interface = None
                    matched_ip = None

        self._logger.debug('get_ip_address: netcfg')
        # Fall back on netcfg if ifconfig does not work.
        # $ adb shell netcfg
        # lo       UP   127.0.0.1/8       0x00000049 00:00:00:00:00:00
        # dummy0   DOWN   0.0.0.0/0       0x00000082 8e:cd:67:48:b7:c2
        # rmnet0   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet1   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet2   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet3   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet4   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet5   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet6   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # rmnet7   DOWN   0.0.0.0/0       0x00000000 00:00:00:00:00:00
        # sit0     DOWN   0.0.0.0/0       0x00000080 00:00:00:00:00:00
        # vip0     DOWN   0.0.0.0/0       0x00001012 00:01:00:00:00:01
        # wlan0    UP   192.168.1.157/24  0x00001043 38:aa:3c:1c:f6:94

        re3_netcfg = re.compile(r'(\w+)\s+UP\s+([1-9]\d{0,2}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
        try:
            output = self.shell_output('netcfg', timeout=timeout)
        except ADBError:
            output = ''
        for line in output.splitlines():
            match = re3_netcfg.search(line)
            if match:
                matched_interface, matched_ip = match.groups()
                if matched_interface == "lo" or re_bad_addr.match(matched_ip):
                    matched_interface = None
                    matched_ip = None
                elif matched_ip and matched_interface in interfaces:
                    self._logger.debug('get_ip_address: found: %s %s' %
                                       (matched_interface, matched_ip))
                    return matched_ip
        self._logger.debug('get_ip_address: not found')
        return matched_ip

    # File management methods

    def remount(self, timeout=None):
        """Remount /system/ in read/write mode

        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError"""

        rv = self.command_output(["remount"], timeout=timeout)
        if not rv.startswith("remount succeeded"):
            raise ADBError("Unable to remount device")

    def chmod(self, path, recursive=False, mask="777", timeout=None, root=False):
        """Recursively changes the permissions of a directory on the
        device.

        :param str path: The directory name on the device.
        :param bool recursive: Flag specifying if the command should be
            executed recursively.
        :param str mask: The octal permissions.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before throwing
            an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        # Note that on some tests such as webappstartup, an error
        # occurs during recursive calls to chmod where a "No such file
        # or directory" error will occur for the
        # /data/data/org.mozilla.fennec/files/mozilla/*.webapp0/lock
        # which is a symbolic link to a socket: lock ->
        # 127.0.0.1:+<port>.  On Linux, chmod -R ignores symbolic
        # links but it appear Android's version does not. We ignore
        # this type of error, but pass on any other errors that are
        # detected.
        path = posixpath.normpath(path.strip())
        self._logger.debug('chmod: path=%s, recursive=%s, mask=%s, root=%s' %
                           (path, recursive, mask, root))
        if not recursive:
            self.shell_output("chmod %s %s" % (mask, path),
                              timeout=timeout, root=root)
            return

        if self._chmod_R:
            try:
                self.shell_output("chmod -R %s %s" % (mask, path),
                                  timeout=timeout, root=root)
            except ADBError as e:
                if e.message.find('No such file or directory') == -1:
                    raise
                self._logger.warning('chmod -R %s %s: Ignoring Error: %s' %
                                     (mask, path, e.message))
            return
        # Obtain a list of the directories and files which match path
        # and construct a shell script which explictly calls chmod on
        # each of them.
        entries = self.ls(path, recursive=recursive, timeout=timeout,
                          root=root)
        tmpf = None
        chmodsh = None
        try:
            tmpf = tempfile.NamedTemporaryFile(delete=False)
            for entry in entries:
                tmpf.write('chmod %s %s\n' % (mask, entry))
            tmpf.close()
            chmodsh = '/data/local/tmp/%s' % os.path.basename(tmpf.name)
            self.push(tmpf.name, chmodsh)
            self.shell_output('chmod 777 %s' % chmodsh, timeout=timeout,
                              root=root)
            self.shell_output('sh -c %s' % chmodsh, timeout=timeout,
                              root=root)
        finally:
            if tmpf:
                os.unlink(tmpf.name)
            if chmodsh:
                self.rm(chmodsh, timeout=timeout, root=root)

    def exists(self, path, timeout=None, root=False):
        """Returns True if the path exists on the device.

        :param str path: The directory name on the device.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should be
            executed as root.
        :returns: boolean - True if path exists.
        :raises: * ADBTimeoutError
                 * ADBRootError
        """
        path = posixpath.normpath(path)
        return self.shell_bool('ls -a %s' % path, timeout=timeout, root=root)

    def is_dir(self, path, timeout=None, root=False):
        """Returns True if path is an existing directory on the device.

        :param str path: The path on the device.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :returns: boolean - True if path exists on the device and is a
            directory.
        :raises: * ADBTimeoutError
                 * ADBRootError
        """
        path = posixpath.normpath(path)
        return self.shell_bool('ls -a %s/' % path, timeout=timeout, root=root)

    def is_file(self, path, timeout=None, root=False):
        """Returns True if path is an existing file on the device.

        :param str path: The file name on the device.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :returns: boolean - True if path exists on the device and is a
            file.
        :raises: * ADBTimeoutError
                 * ADBRootError
        """
        path = posixpath.normpath(path)
        return (
            self.exists(path, timeout=timeout, root=root) and
            not self.is_dir(path, timeout=timeout, root=root))

    def list_files(self, path, timeout=None, root=False):
        """Return a list of files/directories contained in a directory
        on the device.

        :param str path: The directory name on the device.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :returns: list of files/directories contained in the directory.
        :raises: * ADBTimeoutError
                 * ADBRootError
        """
        path = posixpath.normpath(path.strip())
        data = []
        if self.is_dir(path, timeout=timeout, root=root):
            try:
                data = self.shell_output("%s %s" % (self._ls, path),
                                         timeout=timeout,
                                         root=root).splitlines()
                self._logger.debug('list_files: data: %s' % data)
            except ADBError:
                self._logger.error('Ignoring exception in ADBDevice.list_files\n%s' %
                                   traceback.format_exc())
        data[:] = [item for item in data if item]
        self._logger.debug('list_files: %s' % data)
        return data

    def ls(self, path, recursive=False, timeout=None, root=False):
        """Return a list of matching files/directories on the device.

        The ls method emulates the behavior of the ls shell command.
        It differs from the list_files method by supporting wild cards
        and returning matches even if the path is not a directory and
        by allowing a recursive listing.

        ls /sdcard always returns /sdcard and not the contents of the
        sdcard path. The ls method makes the behavior consistent with
        others paths by adjusting /sdcard to /sdcard/. Note this is
        also the case of other sdcard related paths such as
        /storage/emulated/legacy but no adjustment is made in those
        cases.

        The ls method works around a Nexus 4 bug which prevents
        recursive listing of directories on the sdcard unless the path
        ends with "/*" by adjusting sdcard paths ending in "/" to end
        with "/*". This adjustment is only made on official Nexus 4
        builds with property ro.product.model "Nexus 4". Note that
        this will fail to return any "hidden" files or directories
        which begin with ".".

        :param str path: The directory name on the device.
        :param bool recursive: Flag specifying if a recursive listing
            is to be returned. If recursive is False, the returned
            matches will be relative to the path. If recursive is True,
            the returned matches will be absolute paths.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :returns: list of files/directories contained in the directory.
        :raises: * ADBTimeoutError
                 * ADBRootError
        """
        path = posixpath.normpath(path.strip())
        parent = ''
        entries = {}

        if path == '/sdcard':
            path += '/'

        # Android 2.3 and later all appear to support ls -R however
        # Nexus 4 does not perform a recursive search on the sdcard
        # unless the path is a directory with * wild card.
        if not recursive:
            recursive_flag = ''
        else:
            recursive_flag = '-R'
            if path.startswith('/sdcard') and path.endswith('/'):
                model = self.shell_output('getprop ro.product.model',
                                          timeout=timeout,
                                          root=root)
                if model == 'Nexus 4':
                    path += '*'
        lines = self.shell_output('%s %s %s' % (self._ls, recursive_flag, path),
                                  timeout=timeout,
                                  root=root).splitlines()
        for line in lines:
            line = line.strip()
            if not line:
                parent = ''
                continue
            if line.endswith(':'):  # This is a directory
                parent = line.replace(':', '/')
                entry = parent
                # Remove earlier entry which is marked as a file.
                if parent[:-1] in entries:
                    del entries[parent[:-1]]
            elif parent:
                entry = "%s%s" % (parent, line)
            else:
                entry = line
            entries[entry] = 1
        entry_list = entries.keys()
        entry_list.sort()
        return entry_list

    def mkdir(self, path, parents=False, timeout=None, root=False):
        """Create a directory on the device.

        :param str path: The directory name on the device
            to be created.
        :param bool parents: Flag indicating if the parent directories are
            also to be created. Think mkdir -p path.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        path = posixpath.normpath(path)
        if parents:
            if self._mkdir_p is None or self._mkdir_p:
                # Use shell_bool to catch the possible
                # non-zero exitcode if -p is not supported.
                if self.shell_bool('mkdir -p %s' % path, timeout=timeout,
                                   root=root):
                    self._mkdir_p = True
                    return
            # mkdir -p is not supported. create the parent
            # directories individually.
            if not self.is_dir(posixpath.dirname(path), root=root):
                parts = path.split('/')
                name = "/"
                for part in parts[:-1]:
                    if part != "":
                        name = posixpath.join(name, part)
                        if not self.is_dir(name, root=root):
                            # Use shell_output to allow any non-zero
                            # exitcode to raise an ADBError.
                            self.shell_output('mkdir %s' % name,
                                              timeout=timeout, root=root)

        # If parents is True and the directory does exist, we don't
        # need to do anything. Otherwise we call mkdir. If the
        # directory already exists or if it is a file instead of a
        # directory, mkdir will fail and we will raise an ADBError.
        if not parents or not self.is_dir(path, root=root):
            self.shell_output('mkdir %s' % path, timeout=timeout, root=root)
        if not self.is_dir(path, timeout=timeout, root=root):
            raise ADBError('mkdir %s Failed' % path)

    def push(self, local, remote, timeout=None):
        """Pushes a file or directory to the device.

        :param str local: The name of the local file or
            directory name.
        :param str remote: The name of the remote file or
            directory name.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError
        """
        # remove trailing /
        local = os.path.normpath(local)
        remote = posixpath.normpath(remote)
        copy_required = False
        if os.path.isdir(local):
            copy_required = True
            temp_parent = tempfile.mkdtemp()
            remote_name = os.path.basename(remote)
            new_local = os.path.join(temp_parent, remote_name)
            dir_util.copy_tree(local, new_local)
            local = new_local
            # See do_sync_push in
            # https://android.googlesource.com/platform/system/core/+/master/adb/file_sync_client.cpp
            # Work around change in behavior in adb 1.0.36 where if
            # the remote destination directory exists, adb push will
            # copy the source directory *into* the destination
            # directory otherwise it will copy the source directory
            # *onto* the destination directory.
            if self._adb_version >= '1.0.36':
                remote = '/'.join(remote.rstrip('/').split('/')[:-1])
        try:
            self.command_output(["push", local, remote], timeout=timeout)
        except BaseException:
            raise
        finally:
            if copy_required:
                shutil.rmtree(temp_parent)

    def pull(self, remote, local, timeout=None):
        """Pulls a file or directory from the device.

        :param str remote: The path of the remote file or
            directory.
        :param str local: The path of the local file or
            directory name.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError
        """
        # remove trailing /
        local = os.path.normpath(local)
        remote = posixpath.normpath(remote)
        copy_required = False
        original_local = local
        if self._adb_version >= '1.0.36' and \
           os.path.isdir(local) and self.is_dir(remote):
            # See do_sync_pull in
            # https://android.googlesource.com/platform/system/core/+/master/adb/file_sync_client.cpp
            # Work around change in behavior in adb 1.0.36 where if
            # the local destination directory exists, adb pull will
            # copy the source directory *into* the destination
            # directory otherwise it will copy the source directory
            # *onto* the destination directory.
            #
            # If the destination directory does exist, pull to its
            # parent directory. If the source and destination leaf
            # directory names are different, pull the source directory
            # into a temporary directory and then copy the temporary
            # directory onto the destination.
            local_name = os.path.basename(local)
            remote_name = os.path.basename(remote)
            if local_name != remote_name:
                copy_required = True
                temp_parent = tempfile.mkdtemp()
                local = os.path.join(temp_parent, remote_name)
            else:
                local = '/'.join(local.rstrip('/').split('/')[:-1])
        try:
            self.command_output(["pull", remote, local], timeout=timeout)
        except BaseException:
            raise
        finally:
            if copy_required:
                dir_util.copy_tree(local, original_local)
                shutil.rmtree(temp_parent)

    def get_file(self, remote, offset=None, length=None, timeout=None):
        """Pull file from device and return the file's content

        :param str remote: The path of the remote file.
        :param offset: If specified, return only content beyond this offset.
        :param length: If specified, limit content length accordingly.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :raises: * ADBTimeoutError
                 * ADBError
        """
        with tempfile.NamedTemporaryFile() as tf:
            self.pull(remote, tf.name, timeout=timeout)
            with open(tf.name) as tf2:
                # ADB pull does not support offset and length, but we can
                # instead read only the requested portion of the local file
                if offset is not None and length is not None:
                    tf2.seek(offset)
                    return tf2.read(length)
                elif offset is not None:
                    tf2.seek(offset)
                    return tf2.read()
                else:
                    return tf2.read()

    def rm(self, path, recursive=False, force=False, timeout=None, root=False):
        """Delete files or directories on the device.

        :param str path: The path of the remote file or directory.
        :param bool recursive: Flag specifying if the command is
            to be applied recursively to the target. Default is False.
        :param bool force: Flag which if True will not raise an
            error when attempting to delete a non-existent file. Default
            is False.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        cmd = "rm"
        if recursive:
            cmd += " -r"
        try:
            self.shell_output("%s %s" % (cmd, path), timeout=timeout, root=root)
            if self.is_file(path, timeout=timeout, root=root):
                raise ADBError('rm("%s") failed to remove file.' % path)
        except ADBError as e:
            if not force and 'No such file or directory' in e.message:
                raise

    def rmdir(self, path, timeout=None, root=False):
        """Delete empty directory on the device.

        :param str path: The directory name on the device.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        self.shell_output("rmdir %s" % path, timeout=timeout, root=root)
        if self.is_dir(path, timeout=timeout, root=root):
            raise ADBError('rmdir("%s") failed to remove directory.' % path)

    # Process management methods

    def get_process_list(self, timeout=None):
        """Returns list of tuples (pid, name, user) for running
        processes on device.

        :param timeout: The maximum time
            in seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified,
            the value set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: list of (pid, name, user) tuples for running processes
            on the device.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        adb_process = None
        try:
            adb_process = self.shell("ps", timeout=timeout)
            if adb_process.timedout:
                raise ADBTimeoutError("%s" % adb_process)
            elif adb_process.exitcode:
                raise ADBError("%s" % adb_process)
            # first line is the headers
            header = adb_process.stdout_file.readline()
            pid_i = -1
            user_i = -1
            els = header.split()
            for i in range(len(els)):
                item = els[i].lower()
                if item == 'user':
                    user_i = i
                elif item == 'pid':
                    pid_i = i
            if user_i == -1 or pid_i == -1:
                self._logger.error('get_process_list: %s' % header)
                raise ADBError('get_process_list: Unknown format: %s: %s' % (
                    header, adb_process))
            ret = []
            line = adb_process.stdout_file.readline()
            while line:
                els = line.split()
                try:
                    ret.append([int(els[pid_i]), els[-1], els[user_i]])
                except ValueError:
                    self._logger.error('get_process_list: %s %s\n%s' % (
                        header, line, traceback.format_exc()))
                    raise ADBError('get_process_list: %s: %s: %s' % (
                        header, line, adb_process))
                line = adb_process.stdout_file.readline()
            self._logger.debug('get_process_list: %s' % ret)
            return ret
        finally:
            if adb_process and isinstance(adb_process.stdout_file, file):
                adb_process.stdout_file.close()

    def kill(self, pids, sig=None, attempts=3, wait=5,
             timeout=None, root=False):
        """Kills processes on the device given a list of process ids.

        :param list pids: process ids to be killed.
        :param sig: signal to be sent to the process.
        :type sig: integer or None
        :param integer attempts: number of attempts to try to
            kill the processes.
        :param integer wait: number of seconds to wait after each attempt.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        pid_list = [str(pid) for pid in pids]
        for attempt in range(attempts):
            args = ["kill"]
            if sig:
                args.append("-%d" % sig)
            args.extend(pid_list)
            try:
                self.shell_output(' '.join(args), timeout=timeout, root=root)
            except ADBError as e:
                if 'No such process' not in e.message:
                    raise
            pid_set = set(pid_list)
            current_pid_set = set([str(proc[0]) for proc in
                                   self.get_process_list(timeout=timeout)])
            pid_list = list(pid_set.intersection(current_pid_set))
            if not pid_list:
                break
            self._logger.debug("Attempt %d of %d to kill processes %s failed" %
                               (attempt + 1, attempts, pid_list))
            time.sleep(wait)

        if pid_list:
            raise ADBError('kill: processes %s not killed' % pid_list)

    def pkill(self, appname, sig=None, attempts=3, wait=5,
              timeout=None, root=False):
        """Kills a processes on the device matching a name.

        :param str appname: The app name of the process to
            be killed. Note that only the first 75 characters of the
            process name are significant.
        :param sig: optional signal to be sent to the process.
        :type sig: integer or None
        :param integer attempts: number of attempts to try to
            kill the processes.
        :param integer wait: number of seconds to wait after each attempt.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :param bool root: Flag specifying if the command should
            be executed as root.

        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        procs = self.get_process_list(timeout=timeout)
        # limit the comparion to the first 75 characters due to a
        # limitation in processname length in android.
        pids = [proc[0] for proc in procs if proc[1] == appname[:75]]
        if not pids:
            return

        try:
            self.kill(pids, sig, attempts=attempts, wait=wait,
                      timeout=timeout, root=root)
        except ADBError as e:
            if self.process_exist(appname, timeout=timeout):
                raise e

    def process_exist(self, process_name, timeout=None):
        """Returns True if process with name process_name is running on
        device.

        :param str process_name: The name of the process
            to check. Note that only the first 75 characters of the
            process name are significant.
        :param timeout: The maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :type timeout: integer or None
        :returns: boolean - True if process exists.

        :raises: * ADBTimeoutError
                 * ADBError
        """
        if not isinstance(process_name, basestring):
            raise ADBError("Process name %s is not a string" % process_name)

        # Filter out extra spaces.
        parts = [x for x in process_name.split(' ') if x != '']
        process_name = ' '.join(parts)

        # Filter out the quoted env string if it exists
        # ex: '"name=value;name2=value2;etc=..." process args' -> 'process args'
        parts = process_name.split('"')
        if len(parts) > 2:
            process_name = ' '.join(parts[2:]).strip()

        pieces = process_name.split(' ')
        parts = pieces[0].split('/')
        app = parts[-1]

        proc_list = self.get_process_list(timeout=timeout)
        if not proc_list:
            return False

        for proc in proc_list:
            proc_name = proc[1].split('/')[-1]
            # limit the comparion to the first 75 characters due to a
            # limitation in processname length in android.
            if proc_name == app[:75]:
                return True
        return False

    def cp(self, source, destination, recursive=False, timeout=None,
           root=False):
        """Copies a file or directory on the device.

        :param source: string containing the path of the source file or
            directory.
        :param destination: string containing the path of the destination file
            or directory.
        :param recursive: optional boolean indicating if a recursive copy is to
            be performed. Required if the source is a directory. Defaults to
            False. Think cp -R source destination.
        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        source = posixpath.normpath(source)
        destination = posixpath.normpath(destination)
        if self._have_cp:
            r = '-R' if recursive else ''
            self.shell_output('cp %s %s %s' % (r, source, destination),
                              timeout=timeout, root=root)
            return

        # Emulate cp behavior depending on if source and destination
        # already exists and whether they are a directory or file.
        if not self.exists(source, timeout=timeout, root=root):
            raise ADBError("cp: can't stat '%s': No such file or directory" %
                           source)

        if self.is_file(source, timeout=timeout, root=root):
            if self.is_dir(destination, timeout=timeout, root=root):
                # Copy the source file into the destination directory
                destination = posixpath.join(destination,
                                             posixpath.basename(source))
            self.shell_output('dd if=%s of=%s' % (source, destination),
                              timeout=timeout, root=root)
            return

        if self.is_file(destination, timeout=timeout, root=root):
            raise ADBError('cp: %s: Not a directory' % destination)

        if not recursive:
            raise ADBError("cp: omitting directory '%s'" % source)

        if self.is_dir(destination, timeout=timeout, root=root):
            # Copy the source directory into the destination directory.
            destination_dir = posixpath.join(destination,
                                             posixpath.basename(source))
        else:
            # Copy the contents of the source directory into the
            # destination directory.
            destination_dir = destination

        try:
            # Do not create parent directories since cp does not.
            self.mkdir(destination_dir, timeout=timeout, root=root)
        except ADBError as e:
            if 'File exists' not in e.message:
                raise

        for i in self.list_files(source, timeout=timeout, root=root):
            self.cp(posixpath.join(source, i),
                    posixpath.join(destination_dir, i),
                    recursive=recursive,
                    timeout=timeout, root=root)

    def mv(self, source, destination, timeout=None, root=False):
        """Moves a file or directory on the device.

        :param source: string containing the path of the source file or
            directory.
        :param destination: string containing the path of the destination file
            or directory.
        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :raises: * ADBTimeoutError
                 * ADBRootError
                 * ADBError
        """
        source = posixpath.normpath(source)
        destination = posixpath.normpath(destination)
        self.shell_output('mv %s %s' % (source, destination), timeout=timeout,
                          root=root)

    def reboot(self, timeout=None):
        """Reboots the device.

        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADB constructor is used.
        :raises: * ADBTimeoutError
                 * ADBError

        reboot() reboots the device, issues an adb wait-for-device in order to
        wait for the device to complete rebooting, then calls is_device_ready()
        to determine if the device has completed booting.
        """
        self.command_output(["reboot"], timeout=timeout)
        # command_output automatically inserts a 'wait-for-device'
        # argument to adb. Issuing an empty command is the same as adb
        # -s <device> wait-for-device. We don't send an explicit
        # 'wait-for-device' since that would add duplicate
        # 'wait-for-device' arguments which is an error in newer
        # versions of adb.
        self.command_output([], timeout=timeout)
        self._check_adb_root(timeout=timeout)
        return self.is_device_ready(timeout=timeout)

    @abstractmethod
    def is_device_ready(self, timeout=None):
        """Abstract class that returns True if the device is ready.

        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADB constructor is used.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        return

    @abstractmethod
    def get_battery_percentage(self, timeout=None):
        """Abstract class that returns the battery charge as a percentage.

        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADBDevice constructor is used.
        :returns: battery charge as a percentage.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        return

    def get_info(self, directive=None, timeout=None):
        """
        Returns a dictionary of information strings about the device.

        :param directive: information you want to get. Options are:
             - `battery` - battery charge as a percentage
             - `disk` - total, free, available bytes on disk
             - `id` - unique id of the device
             - `os` - name of the os
             - `process` - list of running processes (same as ps)
             - `systime` - system time of the device
             - `uptime` - uptime of the device

            If `directive` is `None`, will return all available information
        :param timeout: optional integer specifying the maximum time in
            seconds for any spawned adb process to complete before
            throwing an ADBTimeoutError.
            This timeout is per adb call. The total time spent
            may exceed this value. If it is not specified, the value
            set in the ADB constructor is used.
        :raises: * ADBTimeoutError
                 * ADBError
        """
        directives = ['battery', 'disk', 'id', 'os', 'process', 'systime',
                      'uptime']

        if directive in directives:
            directives = [directive]

        info = {}
        if 'battery' in directives:
            info['battery'] = self.get_battery_percentage(timeout=timeout)
        if 'disk' in directives:
            info['disk'] = self.shell_output('df /data /system /sdcard',
                                             timeout=timeout).splitlines()
        if 'id' in directives:
            info['id'] = self.command_output(['get-serialno'], timeout=timeout)
        if 'os' in directives:
            info['os'] = self.shell_output('getprop ro.build.display.id',
                                           timeout=timeout)
        if 'process' in directives:
            ps = self.shell_output('ps', timeout=timeout)
            info['process'] = ps.splitlines()
        if 'systime' in directives:
            info['systime'] = self.shell_output('date', timeout=timeout)
        if 'uptime' in directives:
            uptime = self.shell_output('uptime', timeout=timeout)
            if uptime:
                m = re.match(r'up time: ((\d+) days, )*(\d{2}):(\d{2}):(\d{2})',
                             uptime)
                if m:
                    uptime = '%d days %d hours %d minutes %d seconds' % tuple(
                        [int(g or 0) for g in m.groups()[1:]])
                info['uptime'] = uptime
        return info