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 (882de07e4cbe)

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
# 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, print_function, unicode_literals
from __future__ import absolute_import, print_function, unicode_literals

import errno
import getpass
import io
import json
import json
import logging
import os
import shutil
import six
import six
import subprocess
import sys
import time

from collections import (
from collections import (
    Counter,
    namedtuple,
    OrderedDict,
)
from textwrap import (
from textwrap import (
    TextWrapper,
)

try:
    import psutil
    import psutil
except Exception:
    psutil = None

from mach.mixin.logging import LoggingMixin
import mozfile
import mozfile
from mozsystemmonitor.resourcemonitor import SystemResourceMonitor
from mozterm.widgets import Footer

import mozpack.path as mozpath


from .clobber import (
    Clobberer,
)
from ..base import (
    MozbuildObject,
)
from ..backend import (
from ..backend import (
    get_backend_class,
)
from ..testing import (
    install_test_files,
)
)
from ..compilation.warnings import (
    WarningsCollector,
    WarningsDatabase,
)
)
from ..shellutil import (
    quote as shell_quote,
)
from ..util import (
    FileAvoidWrite,
    FileAvoidWrite,
    mkdir,
    resolve_target_to_make,
)



FINDER_SLOW_MESSAGE = '''
===================
PERFORMANCE WARNING

The OS X Finder application (file indexing used by Spotlight) used a lot of CPU
The OS X Finder application (file indexing used by Spotlight) used a lot of CPU
during the build - an average of %f%% (100%% is 1 core). This made your build
slower.

Consider adding ".noindex" to the end of your object directory name to have
Finder ignore it. Or, add an indexing exclusion through the Spotlight System
Preferences.
===================
===================
'''.strip()



INSTALL_TESTS_CLOBBER = ''.join([TextWrapper().fill(line) + '\n' for line in
                                 '''
The build system was unable to install tests because the CLOBBER file has \
been updated. This means if you edited any test files, your changes may not \
be picked up until a full/clobber build is performed.
be picked up until a full/clobber build is performed.

The easiest and fastest way to perform a clobber build is to run:

 $ mach clobber
 $ mach build
 $ mach build

If you did not modify any test files, it is safe to ignore this message \
and proceed with running tests. To do this run:


 $ touch {clobber_file}
'''.splitlines()])

CLOBBER_REQUESTED_MESSAGE = '''
===================
===================
The CLOBBER file was updated prior to this build. A clobber build may be
required to succeed, but we weren't expecting it to.

Please consider filing a bug for this failure if you have reason to believe
this is a clobber bug and not due to local changes.
===================
'''.strip()



BuildOutputResult = namedtuple('BuildOutputResult',
                               ('warning', 'state_changed', 'message'))



class TierStatus(object):
    """Represents the state and progress of tier traversal.

    The build system is organized into linear phases called tiers. Each tier
    executes in the order it was defined, 1 at a time.
    executes in the order it was defined, 1 at a time.
    """

    def __init__(self, resources):
        """Accepts a SystemResourceMonitor to record results against."""
        self.tiers = OrderedDict()
        self.tiers = OrderedDict()
        self.tier_status = OrderedDict()
        self.resources = resources


    def set_tiers(self, tiers):
    def set_tiers(self, tiers):
        """Record the set of known tiers."""
        for tier in tiers:
        for tier in tiers:
            self.tiers[tier] = dict(
                begin_time=None,
                finish_time=None,
                duration=None,
            )
            )
            self.tier_status[tier] = None

    def begin_tier(self, tier):
        """Record that execution of a tier has begun."""
        self.tier_status[tier] = 'active'
        self.tier_status[tier] = 'active'
        t = self.tiers[tier]
        # We should ideally use a monotonic clock here. Unfortunately, we won't
        # have one until Python 3.
        t['begin_time'] = time.time()
        t['begin_time'] = time.time()
        self.resources.begin_phase(tier)

    def finish_tier(self, tier):
        """Record that execution of a tier has finished."""
        self.tier_status[tier] = 'finished'
        self.tier_status[tier] = 'finished'
        t = self.tiers[tier]
        t['finish_time'] = time.time()
        t['duration'] = self.resources.finish_phase(tier)

    def tiered_resource_usage(self):
    def tiered_resource_usage(self):
        """Obtains an object containing resource usage for tiers.

        The returned object is suitable for serialization.
        """
        o = []
        o = []

        for tier, state in self.tiers.items():
            t_entry = dict(
                name=tier,
                start=state['begin_time'],
                start=state['begin_time'],
                end=state['finish_time'],
                duration=state['duration'],
            )

            self.add_resources_to_dict(t_entry, phase=tier)
            self.add_resources_to_dict(t_entry, phase=tier)

            o.append(t_entry)

        return o
        return o

    def add_resources_to_dict(self, entry, start=None, end=None, phase=None):
        """Helper function to append resource information to a dict."""
        cpu_percent = self.resources.aggregate_cpu_percent(start=start,
                                                           end=end, phase=phase, per_cpu=False)
                                                           end=end, phase=phase, per_cpu=False)
        cpu_times = self.resources.aggregate_cpu_times(start=start, end=end,
                                                       phase=phase, per_cpu=False)
        io = self.resources.aggregate_io(start=start, end=end, phase=phase)

        if cpu_percent is None:
        if cpu_percent is None:
            return entry
            return entry

        entry['cpu_percent'] = cpu_percent
        entry['cpu_times'] = list(cpu_times)
        entry['cpu_times'] = list(cpu_times)
        entry['io'] = list(io)

        return entry

    def add_resource_fields_to_dict(self, d):
    def add_resource_fields_to_dict(self, d):
        for usage in self.resources.range_usage():
            cpu_times = self.resources.aggregate_cpu_times(per_cpu=False)

            d['cpu_times_fields'] = list(cpu_times._fields)
            d['io_fields'] = list(usage.io._fields)
            d['io_fields'] = list(usage.io._fields)
            d['virt_fields'] = list(usage.virt._fields)
            d['swap_fields'] = list(usage.swap._fields)

            return d



class BuildMonitor(MozbuildObject):
    """Monitors the output of the build."""
    """Monitors the output of the build."""

    def init(self, warnings_path):
        """Create a new monitor.

        warnings_path is a path of a warnings database to use.
        warnings_path is a path of a warnings database to use.
        """
        self._warnings_path = warnings_path
        self.resources = SystemResourceMonitor(poll_interval=1.0)
        self._resources_started = False


        self.tiers = TierStatus(self.resources)

        self.warnings_database = WarningsDatabase()
        if os.path.exists(warnings_path):
            try:
            try:
                self.warnings_database.load_from_file(warnings_path)
            except ValueError:
                os.remove(warnings_path)

        # Contains warnings unique to this invocation. Not populated with old
        # Contains warnings unique to this invocation. Not populated with old
        # warnings.
        self.instance_warnings = WarningsDatabase()

        def on_warning(warning):
            # Skip `errors`
            if warning['type'] == 'error':

                return

            filename = warning['filename']

            self.warnings_database.insert(warning)
            if not os.path.exists(filename):
                raise Exception('Could not find file containing warning: %s' %
                                filename)

            self.warnings_database.insert(warning)
                                                     objdir=self.topobjdir)
            # Make a copy so mutations don't impact other database.
            self.instance_warnings.insert(warning.copy())

        self._warnings_collector = WarningsCollector(on_warning,
                                                     objdir=self.topobjdir)
    def start(self):

        self.build_objects = []
        self.build_dirs = set()

    def start(self):
        """Record the start of the build."""
        self.start_time = time.time()
        self.resources.start()
        self._finder_start_cpu = self._get_finder_cpu_usage()

    def start_resource_recording(self):
    def on_line(self, line):
        # This should be merged into start() once bug 892342 lands.
        self.resources.start()
        self._resources_started = True

    def on_line(self, line):

        """Consume a line of output from the build system.

        This will parse the line for state and determine whether more action is
        needed.


        Returns a BuildOutputResult instance.

        In this named tuple, warning will be an object describing a new parsed
        warning. Otherwise it will be None.

        message is either None, or the content of a message to be
        state_changed indicates whether the build system changed state with
        this line. If the build system changed state, the caller may want to
        query this instance for the current state in order to update UI, etc.

        message is either None, or the content of a message to be
        if line.startswith('BUILDSTATUS'):
        displayed to the user.
        """
        message = None

        if line.startswith('BUILDSTATUS'):
            args = line.split()[1:]

            action = args.pop(0)
                update_needed = False
            update_needed = True

            if action == 'TIERS':
                self.tiers.set_tiers(args)
                update_needed = False
                tier, = args
            elif action == 'TIER_START':
                tier = args[0]
                self.tiers.begin_tier(tier)
            elif action == 'TIER_FINISH':
                tier, = args
            elif action == 'BUILD_VERBOSE':
                self.tiers.finish_tier(tier)
            elif action == 'OBJECT_FILE':
                self.build_objects.append(args[0])
                update_needed = False
            elif action == 'BUILD_VERBOSE':
                build_dir = args[0]
                update_needed = False
                if build_dir not in self.build_dirs:
                    self.build_dirs.add(build_dir)
                    message = build_dir
                update_needed = False
            else:

                raise Exception('Unknown build status: %s' % action)

        try:
            return BuildOutputResult(None, update_needed, message)

        warning = None

        try:
            pass
            warning = self._warnings_collector.process_line(line)
            message = line
        except Exception:
            pass

        if self._resources_started:
        return BuildOutputResult(warning, False, message)

    def stop_resource_recording(self):
        if self._resources_started:
            self.resources.stop()
    def finish(self, record_usage=True):

        self._resources_started = False

    def finish(self, record_usage=True):
        """Record the end of the build."""
        self.elapsed = self.end_time - self.start_time
        self.stop_resource_recording()
        self.end_time = time.time()
        self._finder_end_cpu = self._get_finder_cpu_usage()
        self.elapsed = self.end_time - self.start_time

        if not record_usage:
        self.warnings_database.prune()
        self.warnings_database.save_to_file(self._warnings_path)
        try:

        if not record_usage:
            return

        try:
            self.log_resource_usage(usage)
            usage = self.get_resource_usage()
            if not usage:
                return

            if 'MOZ_AUTOMATION' in os.environ and 'UPLOAD_PATH' in os.environ:
            self.log_resource_usage(usage)
            # When running on automation, we store the resource usage data in
            # the upload path, alongside, for convenience, a copy of the HTML
            # viewer.
            if 'MOZ_AUTOMATION' in os.environ and 'UPLOAD_PATH' in os.environ:
                        self.topsrcdir, 'python', 'mozbuild', 'mozbuild',
                build_resources_path = os.path.join(os.environ['UPLOAD_PATH'],
                                                    'build_resources.json')
                shutil.copy(
                    os.path.join(
                        self.topsrcdir, 'python', 'mozbuild', 'mozbuild',
                build_resources_path = self._get_state_filename('build_resources.json')
                        'resources', 'html-build-viewer',
                        'build_resources.html'),
                    os.environ['UPLOAD_PATH'])
            else:
                    json.dumps(self.resources.as_dict(), indent=2))
                build_resources_path = self._get_state_filename('build_resources.json')
            with io.open(build_resources_path, 'w',
                         encoding='utf-8', newline='\n') as fh:
                to_write = six.ensure_text(
                    json.dumps(self.resources.as_dict(), indent=2))
                fh.write(to_write)
                     'Exception when writing resource usage file: {msg}')
        except Exception as e:
            self.log(logging.WARNING, 'build_resources_error',
                     {'msg': str(e)},
                     'Exception when writing resource usage file: {msg}')

        This is used to detect high CPU usage.
    def _get_finder_cpu_usage(self):
        """Obtain the CPU usage of the Finder app on OS X.
            return None

        This is used to detect high CPU usage.

        """
        if not sys.platform.startswith('darwin'):

            return None

        if not psutil:
            if proc.name != 'Finder':
            return None

        for proc in psutil.process_iter():
                continue
            if proc.name != 'Finder':
                continue

            if proc.username != getpass.getuser():
                continue
                continue

            # Try to isolate system finder as opposed to other "Finder"
            # processes.
            if not proc.exe.endswith('CoreServices/Finder.app/Contents/MacOS/Finder'):
                continue


            return proc.get_cpu_times()

        return None

    def have_high_finder_usage(self):
        or None if there is nothing to report.
        """Determine whether there was high Finder CPU usage during the build.

        Returns True if there was high Finder CPU usage, False if there wasn't,
        or None if there is nothing to report.
        """
        # We only measure if the measured range is sufficiently long.
        if not self._finder_start_cpu:
            return None, None

        # We only measure if the measured range is sufficiently long.
        if not self._finder_end_cpu:
        if self.elapsed < 15:
            return None, None

        end = self._finder_end_cpu
        if not self._finder_end_cpu:
            return None, None

        start = self._finder_start_cpu
        end = self._finder_end_cpu
        cpu_seconds = end_total - start_total

        start_total = start.user + start.system
        end_total = end.user + end.system

        cpu_seconds = end_total - start_total


        # If Finder used more than 25% of 1 core during the build, report an
        # error.
        finder_percent = cpu_seconds / self.elapsed * 100


        return finder_percent > 25, finder_percent

    def have_excessive_swapping(self):
        """Determine whether there was excessive swapping during the build.

        Returns a tuple of (excessive, swap_in, swap_out). All values are None
        if no swap information is available.
        """
        if not self.have_resource_usage:
            return None, None, None


        swap_in = sum(m.swap.sin for m in self.resources.measurements)
        swap_out = sum(m.swap.sout for m in self.resources.measurements)

        # The threshold of 1024 MB has been arbitrarily chosen.
        # If a value is too low, the eventual warning produced does not carry
        #
        # Choosing a proper value that is ideal for everyone is hard. We will
        # likely iterate on the logic until people are generally satisfied.
        # If a value is too low, the eventual warning produced does not carry
        # much meaning. If the threshold is too high, people may not see the

        # warning and the warning will thus be ineffective.
        excessive = swap_in > 512 * 1048576 or swap_out > 512 * 1048576
        return excessive, swap_in, swap_out

    @property
    def have_resource_usage(self):
        """ Produce a data structure containing the low-level resource usage information.
        """Whether resource usage is available."""
        return self.resources.start_time is not None

    def get_resource_usage(self):
        """ Produce a data structure containing the low-level resource usage information.

        This data structure can e.g. be serialized into JSON and saved for
        if not self.have_resource_usage:
        subsequent analysis.

        If no resource usage is available, None is returned.
        """
        if not self.have_resource_usage:
                                                           per_cpu=False)
            return None

        cpu_percent = self.resources.aggregate_cpu_percent(phase=None,
                                                           per_cpu=False)
        cpu_times = self.resources.aggregate_cpu_times(phase=None,
        o = dict(
                                                       per_cpu=False)
        io = self.resources.aggregate_io(phase=None)

        o = dict(
            version=3,
            duration=self.end_time - self.start_time,
            argv=sys.argv,
            start=self.start_time,
            end=self.end_time,
            duration=self.end_time - self.start_time,
            resources=[],
            objects=self.build_objects
            cpu_percent=cpu_percent,
            cpu_times=cpu_times,
            io=io,
            objects=self.build_objects
        self.tiers.add_resource_fields_to_dict(o)
        )

        o['tiers'] = self.tiers.tiered_resource_usage()
            cpu_percent = self.resources.aggregate_cpu_percent(usage.start,

        self.tiers.add_resource_fields_to_dict(o)

        for usage in self.resources.range_usage():
            cpu_percent = self.resources.aggregate_cpu_percent(usage.start,
            entry = dict(
                                                               usage.end, per_cpu=False)
            cpu_times = self.resources.aggregate_cpu_times(usage.start,
                                                           usage.end, per_cpu=False)

            entry = dict(
                start=usage.start,
            )
                end=usage.end,
                virt=list(usage.virt),
                swap=list(usage.swap),
            )

            o['resources'].append(entry)
            self.tiers.add_resources_to_dict(entry, start=usage.start,
                                             end=usage.end)

        # psutil might not be available.
            o['resources'].append(entry)

        # If the imports for this file ran before the in-tree virtualenv
        # was bootstrapped (for instance, for a clobber build in automation),
        # psutil might not be available.
        #
        # Treat psutil as optional to avoid an outright failure to log resources
        # TODO: it would be nice to collect data on the storage device as well
                logical_cpu_count=psutil.cpu_count(),
        # in this case.
        o['system'] = {}
        if psutil:
            o['system'].update(dict(
                logical_cpu_count=psutil.cpu_count(),

                physical_cpu_count=psutil.cpu_count(logical=False),
                swap_total=psutil.swap_memory()[0],
                vmem_total=psutil.virtual_memory()[0],
            ))


        return o

    def log_resource_usage(self, usage):
        """Summarize the resource usage of this build in a log message."""

            duration=self.end_time - self.start_time,
        if not usage:
            return

        params = dict(
            duration=self.end_time - self.start_time,
            cpu_percent=usage['cpu_percent'],
            io_read_bytes=usage['io'].read_bytes,

            io_write_bytes=usage['io'].write_bytes,
            io_read_time=usage['io'].read_time,
            io_write_time=usage['io'].write_time,
        )


        message = 'Overall system resources - Wall time: {duration:.0f}s; ' \
            'CPU: {cpu_percent:.0f}%; ' \
            'Read bytes: {io_read_bytes}; Write bytes: {io_write_bytes}; ' \
            'Read time: {io_read_time}; Write time: {io_write_time}'

        self.log(logging.WARNING, 'resource_usage', params, message)
            sin /= 1048576

        excessive, sin, sout = self.have_excessive_swapping()
        if excessive is not None and (sin or sout):
            sin /= 1048576
            sout /= 1048576
            self.log(logging.WARNING, 'swap_activity',
        ccache_stats = None
                     {'sin': sin, 'sout': sout},
                     'Swap in/out (MB): {sin}/{sout}')

    def ccache_stats(self):
        ccache_stats = None

        ccache = mozfile.which('ccache')
        if ccache:
                ccache_stats = CCacheStats(output)
            try:
                output = subprocess.check_output(
                    [ccache, '-s'], universal_newlines=True)
                ccache_stats = CCacheStats(output)
            except ValueError as e:

                self.log(logging.WARNING, 'ccache', {'msg': str(e)}, '{msg}')
        return ccache_stats


class TerminalLoggingHandler(logging.Handler):
    this a proving ground for its usefulness.
    """Custom logging handler that works with terminal window dressing.

    This class should probably live elsewhere, like the mach core. Consider
        logging.Handler.__init__(self)
    this a proving ground for its usefulness.
    """

    def __init__(self):
        logging.Handler.__init__(self)
    def flush(self):

        self.fh = sys.stdout
        self.footer = None

    def flush(self):
        finally:
        self.acquire()

        try:
            self.fh.flush()
        finally:
            self.release()


    def emit(self, record):
        msg = self.format(record)

        self.acquire()
                self.footer.clear()

        try:
            if self.footer:
                self.footer.clear()

            if self.footer:
            self.fh.write(msg)
            self.fh.write('\n')

            if self.footer:
                self.footer.draw()
        finally:

            # If we don't flush, the footer may not get drawn.
            self.fh.flush()
        finally:
            self.release()
    """Handles display of a build progress indicator in a terminal.


class BuildProgressFooter(Footer):
    """Handles display of a build progress indicator in a terminal.

    """
    When mach builds inside a blessings-supported terminal, it will render
    progress information collected from a BuildMonitor. This class converts the
    state of BuildMonitor into terminal output.
        self.tiers = six.viewitems(monitor.tiers.tier_status)
    """

    def __init__(self, terminal, monitor):
        Footer.__init__(self, terminal)
        self.tiers = six.viewitems(monitor.tiers.tier_status)
        if not self.tiers:

    def draw(self):
        """Draws this footer in the terminal."""

        if not self.tiers:

            return

        # The drawn terminal looks something like:
        # TIER: static export libs tools

                append(tier)
        parts = [('bold', 'TIER:')]
        append = parts.append
        for tier, status in self.tiers:
            else:
            if status is None:
                append(tier)
            elif status == 'finished':
                append(('green', tier))
            else:

                append(('underline_yellow', tier))

        self.write(parts)


class OutputManager(LoggingMixin):
    """Handles writing job output to a terminal or log."""
        self.footer = None

    def __init__(self, log_manager, footer):
        self.populate_logger()

        self.footer = None
        terminal = log_manager.terminal
            return

        # TODO convert terminal footer to config file setting.
        if not terminal or os.environ.get('MACH_NO_TERMINAL_FOOTER', None):
            return
        if os.environ.get('INSIDE_EMACS', None):
        self.footer = footer
            return
        self._handler = TerminalLoggingHandler()

        self.t = terminal
        self.footer = footer

        self._handler = TerminalLoggingHandler()
        self._handler.level = old.level
        self._handler.setFormatter(log_manager.terminal_formatter)
        self._handler.footer = self.footer

        old = log_manager.replace_terminal_handler(self._handler)
        self._handler.level = old.level
    def __exit__(self, exc_type, exc_value, traceback):

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):

        if self.footer:
            self.footer.clear()
            # Prevents the footer from being redrawn if logging occurs.
            self._handler.footer = None

        print(line)
    def write_line(self, line):
        if self.footer:
            self.footer.clear()

        print(line)
    def refresh(self):

        if self.footer:
            self.footer.draw()

    def refresh(self):
        if not self.footer:

            return

        self.footer.clear()
        self.footer.draw()

    def __init__(self, log_manager, monitor, footer):

class BuildOutputManager(OutputManager):
    """Handles writing build output to a terminal, to logs, etc."""

    def __init__(self, log_manager, monitor, footer):
        OutputManager.__exit__(self, exc_type, exc_value, traceback)
        self.monitor = monitor
        OutputManager.__init__(self, log_manager, footer)

    def __exit__(self, exc_type, exc_value, traceback):
        OutputManager.__exit__(self, exc_type, exc_value, traceback)
        self.monitor.stop_resource_recording()

        # Ensure the resource monitor is stopped because leaving it running
        # could result in the process hanging on exit because the resource
        # collection child process hasn't been told to stop.
        self.monitor.stop_resource_recording()

        if message:
    def on_line(self, line):
        warning, state_changed, message = self.monitor.on_line(line)
        elif state_changed:

        if message:
            self.log(logging.INFO, 'build_output', {'line': message}, '{line}')
        elif state_changed:
                self.refresh()
            have_handler = hasattr(self, 'handler')
            if have_handler:
                self.handler.acquire()
            try:
                self.refresh()

            finally:
                if have_handler:
                    self.handler.release()


    def __init__(self, terminal, monitor):
class StaticAnalysisFooter(Footer):
    """Handles display of a static analysis progress indicator in a terminal.
    """

    def __init__(self, terminal, monitor):
        """Draws this footer in the terminal."""
        Footer.__init__(self, terminal)
        self.monitor = monitor

    def draw(self):
        """Draws this footer in the terminal."""

        parts = [
        monitor = self.monitor
        total = monitor.num_files
        processed = monitor.num_files_processed
        percent = '(%.2f%%)' % (processed * 100.0 / total)
            ('yellow', str(total)),
        parts = [
            ('dim', 'Processing'),
            ('yellow', str(processed)),
            ('dim', 'of'),
            ('yellow', str(total)),
            parts.append(('bold', monitor.current_file))
            ('dim', 'files'),
            ('green', percent)
        ]
        if monitor.current_file:
            parts.append(('bold', monitor.current_file))
class StaticAnalysisOutputManager(OutputManager):

        self.write(parts)


class StaticAnalysisOutputManager(OutputManager):
    """Handles writing static analysis output to a terminal or file."""

    def __init__(self, log_manager, monitor, footer):
    def on_line(self, line):
        self.monitor = monitor
        self.raw = ''
        OutputManager.__init__(self, log_manager, footer)

    def on_line(self, line):
        if warning:
        warning, relevant = self.monitor.on_line(line)
        if relevant:
            self.raw += line + '\n'

        if warning:
            self.log(logging.INFO, 'build_output', {'line': line}, '{line}')
            self.log(logging.INFO, 'compiler_warning', warning,
                     'Warning: {flag} in {filename}: {message}')

        if relevant:
            self.log(logging.INFO, 'build_output', {'line': line}, '{line}')
            try:
        else:
            have_handler = hasattr(self, 'handler')
            if have_handler:
                if have_handler:
                self.handler.acquire()
                    self.handler.release()
            try:
                self.refresh()
            finally:
                if have_handler:
                    self.handler.release()
        path = os.path.realpath(path)

    def write(self, path, output_format):
        assert output_format in ('text', 'json'), \
            'Invalid output format {}'.format(output_format)
        path = os.path.realpath(path)
        else:

        if output_format == 'json':
            self.monitor._warnings_database.save_to_file(path)

        else:
                 {'path': path, 'format': output_format},
            with io.open(path, 'w', encoding='utf-8', newline='\n') as f:
                f.write(self.raw)

        self.log(logging.INFO, 'write_output',
                 {'path': path, 'format': output_format},
class CCacheStats(object):
                 'Wrote {format} output in {path}')


class CCacheStats(object):
    """Holds statistics from ccache.

    Instances can be subtracted from each other to obtain differences.
    print() or str() the object to show a ``ccache -s`` like output
    STATS_KEYS = [
    of the captured stats.

    """
    STATS_KEYS = [
        # (key, description)
        ('stats_updated', 'stats updated'),
        # Refer to stats.c in ccache project for all the descriptions.
        ('stats_zeroed', 'stats zero time'),  # Old name prior to ccache 3.4
        ('stats_zeroed', 'stats zeroed'),
        ('stats_updated', 'stats updated'),
        ('cache_hit_direct', 'cache hit (direct)'),
        ('link', 'called for link'),
        ('cache_hit_preprocessed', 'cache hit (preprocessed)'),
        ('cache_hit_rate', 'cache hit rate'),
        ('cache_miss', 'cache miss'),
        ('link', 'called for link'),
        ('preprocessing', 'called for preprocessing'),
        ('multiple', 'multiple source files'),
        ('stdout', 'compiler produced stdout'),
        ('no_output', 'compiler produced no output'),
        ('cant_use_pch', "can't use precompiled header"),
        ('empty_output', 'compiler produced empty output'),
        ('failed', 'compile failed'),
        ('error', 'ccache internal error'),
        ('preprocessor_error', 'preprocessor error'),
        ('cant_use_pch', "can't use precompiled header"),
        ('compiler_check_failed', 'compiler check failed'),
        ('compiler_missing', "couldn't find the compiler"),
        ('cache_file_missing', 'cache file missing'),
        ('bad_args', 'bad compiler arguments'),
        ('unsupported_lang', 'unsupported source language'),
        ('compiler_check_failed', 'compiler check failed'),
        ('autoconf', 'autoconf compile/link'),
        ('out_device', 'output to a non-regular file'),
        ('unsupported_code_directive', 'unsupported code directive'),
        ('unsupported_compiler_option', 'unsupported compiler option'),
        ('out_stdout', 'output to stdout'),
        ('out_device', 'output to a non-regular file'),
        ('no_input', 'no input file'),
        ('cache_size', 'cache size'),
        ('bad_extra_file', 'error hashing extra file'),
        ('num_cleanups', 'cleanups performed'),
        ('cache_files', 'files in cache'),
        ('cache_size', 'cache size'),
    PRIMARY_CONFIG_DESCRIPTION = "primary config"
        ('cache_max_size', 'max cache size'),
    ]

    DIRECTORY_DESCRIPTION = "cache directory"
    PRIMARY_CONFIG_DESCRIPTION = "primary config"
    SECONDARY_CONFIG_DESCRIPTION = "secondary config      (readonly)"
    ABSOLUTE_KEYS = {'cache_files', 'cache_size', 'cache_max_size'}
    FORMAT_KEYS = {'cache_size', 'cache_max_size'}

    def __init__(self, output=None):
    GiB = 1024 ** 3
    MiB = 1024 ** 2
    KiB = 1024

    def __init__(self, output=None):
        self.secondary_config = ""
        """Construct an instance from the output of ccache -s."""
        self._values = {}
        self.cache_dir = ""
        self.primary_config = ""
        self.secondary_config = ""

        for line in output.splitlines():
        if not output:
            return

        for line in output.splitlines():
            line = line.strip()
    def _parse_line(self, line):
            if line:
                self._parse_line(line)

    def _parse_line(self, line):
        line = six.ensure_text(line)
        if line.startswith(self.DIRECTORY_DESCRIPTION):
        elif line.startswith(self.SECONDARY_CONFIG_DESCRIPTION):
            self.cache_dir = self._strip_prefix(line, self.DIRECTORY_DESCRIPTION)
        elif line.startswith(self.PRIMARY_CONFIG_DESCRIPTION):
            self.primary_config = self._strip_prefix(
                line, self.PRIMARY_CONFIG_DESCRIPTION)
        elif line.startswith(self.SECONDARY_CONFIG_DESCRIPTION):
            self.secondary_config = self._strip_prefix(
                    raw_value = self._strip_prefix(line, stat_description)
                line, self.SECONDARY_CONFIG_DESCRIPTION)
        else:
            for stat_key, stat_description in self.STATS_KEYS:
                if line.startswith(stat_description):
                    raw_value = self._strip_prefix(line, stat_description)

                    self._values[stat_key] = self._parse_value(raw_value)
                    break
            else:
                raise ValueError('Failed to parse ccache stats output: %s' % line)

    @staticmethod
    def _strip_prefix(line, prefix):
        return line[len(prefix):].strip() if line.startswith(prefix) else line
        try:

    @staticmethod
    def _parse_value(raw_value):
        try:
            # ccache calls strftime with '%c' (src/stats.c)
            pass
            ts = time.strptime(raw_value, '%c')
            return int(time.mktime(ts))
        except ValueError:
            pass
        if len(value) == 1:

        value = raw_value.split()
        unit = ''
        if len(value) == 1:
            numeric = value[0]
            raise ValueError('Failed to parse ccache stats value: %s' % raw_value)
        elif len(value) == 2:
            numeric, unit = value
        else:
            raise ValueError('Failed to parse ccache stats value: %s' % raw_value)

        if '.' in numeric:
        if unit in ('GB', 'Gbytes'):
            numeric = float(numeric)
        else:
            numeric = int(numeric)

        if unit in ('GB', 'Gbytes'):
            unit = CCacheStats.KiB
            unit = CCacheStats.GiB
        elif unit in ('MB', 'Mbytes'):
            unit = CCacheStats.MiB
        elif unit in ('KB', 'Kbytes'):
            unit = CCacheStats.KiB
        else:

            unit = 1

                ' miss rate: {:.1%}'.format(
        return int(numeric * unit)

    def hit_rate_message(self):
        return ('ccache (direct) hit rate: {:.1%}; (preprocessed) hit rate: {:.1%};'
                ' miss rate: {:.1%}'.format(
        direct = self._values['cache_hit_direct']
                    *self.hit_rates()
                ))

    def hit_rates(self):

        direct = self._values['cache_hit_direct']
        preprocessed = self._values['cache_hit_preprocessed']
        miss = self._values['cache_miss']
        total = float(direct + preprocessed + miss)


        if total > 0:
            direct /= total
            preprocessed /= total
            miss /= total

        result.cache_dir = self.cache_dir
        return (direct, preprocessed, miss)

    def __sub__(self, other):
        result = CCacheStats()
        result.cache_dir = self.cache_dir

        for k, prefix in self.STATS_KEYS:
            if k not in self._values and k not in other._values:

                continue

            our_value = self._values.get(k, 0)
            other_value = other._values.get(k, 0)
                result._values[k] = our_value - other_value

            if k in self.ABSOLUTE_KEYS:
                result._values[k] = our_value
            else:
                result._values[k] = our_value - other_value

        LEFT_ALIGN = 34
        return result

    def __str__(self):
        LEFT_ALIGN = 34
        lines = []
                                   self.cache_dir))

        if self.cache_dir:
            lines.append('%s%s' % (self.DIRECTORY_DESCRIPTION.ljust(LEFT_ALIGN),
                                   self.cache_dir))


        for stat_key, stat_description in self.STATS_KEYS:
            if stat_key not in self._values:
                continue

            value = self._values[stat_key]


            if stat_key in self.FORMAT_KEYS:
                value = '%15s' % self._format_value(value)
            else:
                value = '%8u' % value

    def __nonzero__(self):
            lines.append('%s%s' % (stat_description.ljust(LEFT_ALIGN), value))

        return '\n'.join(lines)

    def __nonzero__(self):

        relative_values = [v for k, v in self._values.items()
                           if k not in self.ABSOLUTE_KEYS]
        return (all(v >= 0 for v in relative_values) and
                any(v > 0 for v in relative_values))

    def _format_value(v):
    def __bool__(self):
        return self.__nonzero__()

    @staticmethod
    def _format_value(v):
        if v > CCacheStats.GiB:
        else:
            return '%.1f Gbytes' % (float(v) / CCacheStats.GiB)
        elif v > CCacheStats.MiB:
            return '%.1f Mbytes' % (float(v) / CCacheStats.MiB)
        else:
class BuildDriver(MozbuildObject):
            return '%.1f Kbytes' % (float(v) / CCacheStats.KiB)


class BuildDriver(MozbuildObject):
    """Provides a high-level API for build actions."""
        self.mach_context = None

    def __init__(self, *args, **kwargs):
        MozbuildObject.__init__(self, *args, **kwargs)
        self.mach_context = None

        """Invoke the build backend.
    def build(self, what=None, disable_extra_make_dependencies=None, jobs=0,
              directory=None, verbose=False, keep_going=False, mach_context=None,
              append_env=None):
        """Invoke the build backend.

        self.mach_context = mach_context
        ``what`` defines the thing to build. If not defined, the default
        target is used.
        """
        self.mach_context = mach_context
        warnings_path = self._get_state_filename('warnings.json')
        footer = BuildProgressFooter(self.log_manager.terminal, monitor)
        monitor = self._spawn(BuildMonitor)
        monitor.init(warnings_path)
        # down builds.
        ccache_start = monitor.ccache_stats()
        footer = BuildProgressFooter(self.log_manager.terminal, monitor)

        # Disable indexing in objdir because it is not necessary and can slow
        # down builds.

        mkdir(self.topobjdir, not_indexed=True)

        with BuildOutputManager(self.log_manager, monitor, footer) as output:
            monitor.start()


            if directory is not None and not what:
                print('Can only use -C/--directory with an explicit target '
                      'name.')
                return 1

                    directory = directory[1:]
            if directory is not None:
                disable_extra_make_dependencies = True
                directory = mozpath.normsep(directory)
                if directory.startswith('/'):
            self.mach_context.command_attrs['clobber'] = False
                    directory = directory[1:]

            monitor.start_resource_recording()

            self.mach_context.command_attrs['clobber'] = False
            config = None
            try:
                config = self.config_environment
            except Exception:
                self.mach_context.command_attrs['clobber'] = True
                # If we don't already have a config environment this is either
                # a fresh objdir or $OBJDIR/config.status has been removed for
                # some reason, which indicates a clobber of sorts.
                self.mach_context.command_attrs['clobber'] = True


            # Record whether a clobber was requested so we can print
            # a special message later if the build fails.
            clobber_requested = False

            # Write out any changes to the current mozconfig in case
            previous_backend = None
            # they should invalidate configure.
            self._write_mozconfig_json()

            previous_backend = None
            config_rc = None
            if config is not None:
                previous_backend = config.substs.get('BUILD_BACKENDS', [None])[0]

            config_rc = None
                                                        mozpath.join(self.topobjdir,
            # Even if we have a config object, it may be out of date
            # if something that influences its result has changed.
            if config is None or self.build_out_of_date(mozpath.join(self.topobjdir,
                                                                     'config.status'),
                    clobber_requested = self._clobber_configure()
                                                        mozpath.join(self.topobjdir,
                                                                     'config_status_deps.in')):
                if previous_backend and 'Make' not in previous_backend:
                    clobber_requested = self._clobber_configure()

                config_rc = self.configure(buildstatus_messages=True,
                if config is None:
                    print(" Config object not found by mach.")

                config_rc = self.configure(buildstatus_messages=True,
                                           line_handler=output.on_line,
                    return config_rc
                                           append_env=append_env)

                if config_rc != 0:
                    return config_rc

                config = self.reload_config_environment()
            status = None

            all_backends = config.substs.get('BUILD_BACKENDS', [None])
            active_backend = all_backends[0]

            status = None
                                                           backend))

            if (not config_rc and
                any([self.backend_out_of_date(mozpath.join(self.topobjdir,
                                                           'backend.%sBackend' %
                        mozpath.join(self.topobjdir, 'config.status')]
                                                           backend))
                     for backend in all_backends])):
                print('Build configuration changed. Regenerating backend.')
                args = [config.substs['PYTHON3'],
                        mozpath.join(self.topobjdir, 'config.status')]
                # make backend can determine when to run in single-threaded mode
                self.run_process(args, cwd=self.topobjdir, pass_thru=True)

            if 'Make' not in active_backend:
                # client.mk has its own handling of MOZ_PARALLEL_BUILD so the
                # make backend can determine when to run in single-threaded mode
                    for param in self.mozconfig['make_extra']:
                # or parallel mode. For other backends, we can pass in the value
                # of MOZ_PARALLEL_BUILD if -jX was not specified on the
                # commandline.
                if jobs == 0 and 'make_extra' in self.mozconfig:
                    for param in self.mozconfig['make_extra']:
                backend_cls = get_backend_class(active_backend)(config)
                        key, value = param.split('=')
                        if key == 'MOZ_PARALLEL_BUILD':
                            jobs = int(value)

                backend_cls = get_backend_class(active_backend)(config)
                status = backend_cls.build(self, output, jobs, verbose, what)


                if status and clobber_requested:
                    for line in CLOBBER_REQUESTED_MESSAGE.splitlines():
                        self.log(logging.WARNING, 'clobber',
                                 {'msg': line.rstrip()}, '{msg}')

                    path_arg = self._wrap_path_argument(target)
            if what and status is None:
                # Collect target pairs.
                target_pairs = []
                for target in what:
                    path_arg = self._wrap_path_argument(target)
                    else:

                    if directory is not None:
                        make_dir = os.path.join(self.topobjdir, directory)
                        make_target = target
                    else:
                    if make_dir is None and make_target is None:
                        make_dir, make_target = \
                            resolve_target_to_make(self.topobjdir,
                                                   path_arg.relpath())

                    if make_dir is None and make_target is None:
                        return 1

                        print("The specified directory doesn't contain a "
                    # See bug 886162 - we don't want to "accidentally" build
                    # the entire tree (if that's really the intent, it's
                    # unlikely they would have specified a directory.)
                    if not make_dir and not make_target:
                        print("The specified directory doesn't contain a "
                        return 1
                              "Makefile and the first parent with one is the "
                              "root of the tree. Please specify a directory "
                              "with a Makefile or run |mach build| if you "
                              "want to build the entire tree.")
                        return 1
                if not disable_extra_make_dependencies:

                    target_pairs.append((make_dir, make_target))

                    depfile = os.path.join(self.topsrcdir, 'build',
                # Possibly add extra make depencies using dumbmake.
                                           'dumbmake-dependencies')
                if not disable_extra_make_dependencies:
                    from dumbmake.dumbmake import (dependency_map,
                                                   add_extra_dependencies)
                    new_pairs = list(add_extra_dependencies(target_pairs, dm))
                    depfile = os.path.join(self.topsrcdir, 'build',
                                           'dumbmake-dependencies')
                    with io.open(depfile, encoding='utf-8', newline='\n') as f:
                        dm = dependency_map(f.readlines())
                             'Added extra dependencies: will build {new_pairs} ' +
                    new_pairs = list(add_extra_dependencies(target_pairs, dm))
                    self.log(logging.DEBUG, 'dumbmake',
                             {'target_pairs': target_pairs,
                              'new_pairs': new_pairs},
                             'Added extra dependencies: will build {new_pairs} ' +
                for make_dir, make_target in target_pairs:
                             'instead of {target_pairs}.')
                    target_pairs = new_pairs

                # Build target pairs.
                for make_dir, make_target in target_pairs:
                    no_build_status = '1' if make_dir is not None else ''
                    # We don't display build status messages during partial
                    # tree builds because they aren't reliable there. This
                    # could potentially be fixed if the build monitor were more
                    status = self._run_make(
                    # intelligent about encountering undefined state.
                        directory=make_dir, target=make_target,
                    no_build_status = '1' if make_dir is not None else ''
                    tgt_env = dict(append_env or {})
                    tgt_env['NO_BUILDSTATUS_MESSAGES'] = no_build_status
                        append_env=tgt_env,
                    status = self._run_make(
                        directory=make_dir, target=make_target,
                        line_handler=output.on_line, log=False, print_directory=False,
                        ensure_exit_code=False, num_jobs=jobs, silent=not verbose,
                    if status != 0:
                        append_env=tgt_env,
                        keep_going=keep_going)

                    if status != 0:
                        break
                # call client.mk directly.

            elif status is None:
                # If the backend doesn't specify a build() method, then just
                # call client.mk directly.
                status = self._run_client_mk(line_handler=output.on_line,
                                             append_env=append_env)
                                             jobs=jobs,
                                             verbose=verbose,
                                             keep_going=keep_going,
                                             append_env=append_env)


            self.log(logging.WARNING, 'warning_summary',
                     {'count': len(monitor.warnings_database)},
                     '{count} compiler warnings present.')

                    backend_cls = get_backend_class(active_backend)(config)
            # Try to run the active build backend's post-build step, if possible.
            try:
                active_backend = config.substs.get('BUILD_BACKENDS', [None])[0]
                if active_backend:
                    backend_cls = get_backend_class(active_backend)(config)
                    new_status = backend_cls.post_build(self, output, jobs, verbose, status)
                    status = new_status
                if not status:
            except Exception as ex:
                self.log(logging.DEBUG, 'post_build', {'ex': str(ex)},
                         "Unable to run active build backend's post-build step; " +
                         "failing the build due to exception: {ex}.")
                if not status:
            record_usage = status == 0
                    # If the underlying build provided a failing status, pass
                    # it through; otherwise, fail.
                    status = 1

            record_usage = status == 0


            # On automation, only record usage for plain `mach build`
            if 'MOZ_AUTOMATION' in os.environ and what:
                record_usage = False
            usage = monitor.get_resource_usage()

            monitor.finish(record_usage=record_usage)

        if status == 0:
            usage = monitor.get_resource_usage()
            if usage:
        # inline output from the compiler itself. However, unlike inline
                self.mach_context.command_attrs['usage'] = usage

        # Print the collected compiler warnings. This is redundant with
        # inline output from the compiler itself. However, unlike inline
        # output, this list is sorted and grouped by file, making it
        # whatever code we warned about.
        # easier to triage output.
        #
        # Only do this if we had a successful build. If the build failed,
        # there are more important things in the log to look for than
        # whatever code we warned about.
            # in these directories.
        if not status:
            # Suppress warnings for 3rd party projects in local builds
            # until we suppress them for real.
            # TODO remove entries/feature once we stop generating warnings
            # in these directories.

            pathToThirdparty = os.path.join(self.topsrcdir,
                                            "tools",
                                            "rewriting",
                                            "ThirdPartyPaths.txt")


            pathToGenerated = os.path.join(self.topsrcdir,
                                           "tools",
                                           "rewriting",
                                           "Generated.txt")
                     io.open(pathToGenerated, encoding='utf-8', newline='\n') as g:

            if os.path.exists(pathToThirdparty):
                with io.open(pathToThirdparty, encoding='utf-8', newline='\n') as f, \
                     io.open(pathToGenerated, encoding='utf-8', newline='\n') as g:
                    # Normalize the path (no trailing /)
                # For application based on gecko like thunderbird
                    suppress = f.readlines() + g.readlines()
                    LOCAL_SUPPRESS_DIRS = tuple(s.strip('/') for s in suppress)
            else:
                # For application based on gecko like thunderbird
                LOCAL_SUPPRESS_DIRS = ()
            for warning in sorted(monitor.instance_warnings):

            suppressed_by_dir = Counter()

            for warning in sorted(monitor.instance_warnings):
                path = mozpath.normsep(warning['filename'])
                warning['normpath'] = path
                if path.startswith(self.topsrcdir):
                    path = path[len(self.topsrcdir) + 1:]

                warning['normpath'] = path

                if (path.startswith(LOCAL_SUPPRESS_DIRS) and
                        'MOZ_AUTOMATION' not in os.environ):
                            break
                    for d in LOCAL_SUPPRESS_DIRS:
                        if path.startswith(d):

                            suppressed_by_dir[d] += 1
                            break

                    continue
                             '{message}')

                if warning['column'] is not None:
                    self.log(logging.WARNING, 'compiler_warning', warning,
                             'warning: {normpath}:{line}:{column} [{flag}] '
                             '{message}')
            for d, count in sorted(suppressed_by_dir.items()):
                else:
                    self.log(logging.WARNING, 'compiler_warning', warning,
                             'warning: {normpath}:{line} [{flag}] {message}')

            for d, count in sorted(suppressed_by_dir.items()):
        high_finder, finder_percent = monitor.have_high_finder_usage()
                self.log(logging.WARNING, 'suppressed_warning',
                         {'dir': d, 'count': count},
                         '(suppressed {count} warnings in {dir})')

        high_finder, finder_percent = monitor.have_high_finder_usage()

        if high_finder:
            print(FINDER_SLOW_MESSAGE % finder_percent)

        ccache_end = monitor.ccache_stats()
            ccache_diff = ccache_end - ccache_start

        ccache_diff = None
        if ccache_start and ccache_end:
            ccache_diff = ccache_end - ccache_start
            if ccache_diff:
        notify_minimum_time = 300
                self.log(logging.INFO, 'ccache',
                         {'msg': ccache_diff.hit_rate_message()}, "{msg}")

        notify_minimum_time = 300
        try:
            pass
            notify_minimum_time = int(os.environ.get('MACH_NOTIFY_MINTIME', '300'))
        except ValueError:
            # Just stick with the default
            pass


        if monitor.elapsed > notify_minimum_time:
            # Display a notification when the build completes.
            self.notify('Build complete' if not status else 'Build failed')

            excessive, swap_in, swap_out = monitor.have_excessive_swapping()
        if status:
            return status

        if monitor.have_resource_usage:
            excessive, swap_in, swap_out = monitor.have_excessive_swapping()
                  'resource-usage|.')
            # if excessive:
            #    print(EXCESSIVE_SWAP_MESSAGE)

            print('To view resource usage of the build, run |mach '
                  'resource-usage|.')
            output.on_line(

        long_build = monitor.elapsed > 600

        if long_build:
            output.on_line(
        # Only for full builds because incremental builders likely don't
                'We know it took a while, but your build finally finished successfully!')
        else:
            output.on_line('Your build was successful!')

                # Fennec doesn't have useful output from just building. We should
        # Only for full builds because incremental builders likely don't
        # need to be burdened with this.
        if not what:
            try:
                # Fennec doesn't have useful output from just building. We should
                # arguably make the build action useful for Fennec. Another day...
                if self.substs['MOZ_BUILD_APP'] != 'mobile/android':
                        'For more information on what to do now, see '
                    print('To take your build for a test drive, run: |mach run|')
                app = self.substs['MOZ_BUILD_APP']
                if app in ('browser', 'mobile/android'):
                    print(
                        'For more information on what to do now, see '
                # as when doing OSX Universal builds)
                        'https://developer.mozilla.org/docs/Developer_Guide/So_You_Just_Built_Firefox'  # noqa
                    )
            except Exception:
                # Ignore Exceptions in case we can't find config.status (such
                # as when doing OSX Universal builds)
    def configure(self, options=None, buildstatus_messages=False,
                pass

        return status

    def configure(self, options=None, buildstatus_messages=False,
        self._write_mozconfig_json()
                  line_handler=None, append_env=None):
        # Disable indexing in objdir because it is not necessary and can slow
        # down builds.
        mkdir(self.topobjdir, not_indexed=True)
        self._write_mozconfig_json()

        def on_line(line):
            self.log(logging.INFO, 'build_output', {'line': line}, '{line}')

        line_handler = line_handler or on_line
        append_env['CONFIGURE_ARGS'] = options

        options = ' '.join(shell_quote(o) for o in options or ())
        append_env = dict(append_env or {})
        append_env['CONFIGURE_ARGS'] = options

            append_env['NO_BUILDSTATUS_MESSAGES'] = '1'
        # Only print build status messages when we have an active
        # monitor.
        if not buildstatus_messages:
            append_env['NO_BUILDSTATUS_MESSAGES'] = '1'
        status = self._run_client_mk(target='configure',
        if not status:
                                     line_handler=line_handler,
                                     append_env=append_env)

        return status
        if not status:
            print('Configure complete!')
            print('Be sure to run |mach build| to pick up any changes')

        return status
        if self.is_clobber_needed():

    def install_tests(self):
        """Install test files."""

        if self.is_clobber_needed():
        install_test_files(mozpath.normpath(self.topsrcdir), self.topobjdir,
            print(INSTALL_TESTS_CLOBBER.format(
                  clobber_file=os.path.join(self.topobjdir, 'CLOBBER')))
            sys.exit(1)

        install_test_files(mozpath.normpath(self.topsrcdir), self.topobjdir,
        # some trust in the build system: an update to the CLOBBER file is
                           '_tests')

    def _clobber_configure(self):
        # This is an optimistic treatment of the CLOBBER file for when we have
        # some trust in the build system: an update to the CLOBBER file is
        clobberer = Clobberer(self.topsrcdir, self.topobjdir)
        # interpreted to mean that configure will fail during an incremental
        # build, which is handled by removing intermediate configure artifacts
        # and subsections of the objdir related to python and testing before
        # proceeding.
        required, performed, message = res
        clobberer = Clobberer(self.topsrcdir, self.topobjdir)
        clobber_output = io.StringIO()
        res = clobberer.maybe_do_clobber(os.getcwd(), False,
                                         clobber_output)
        required, performed, message = res
        def remove_objdir_path(path):
        assert not performed
        if not required:
            return False
            self.log(logging.WARNING,

        def remove_objdir_path(path):
            path = mozpath.join(self.topobjdir, path)
            self.log(logging.WARNING,
                     'clobber',

                     {'path': path},
                     'CLOBBER file has been updated, removing {path}.')
            mozfile.remove(path)

        # Remove files we think could cause "configure" clobber bugs.
        for f in ('old-configure.vars', 'config.cache', 'configure.pkl'):
            # Stale paths in our virtualenv may cause build-backend
            remove_objdir_path(f)
            remove_objdir_path(mozpath.join('js', 'src', f))

        rm_dirs = [
            # Stale paths in our virtualenv may cause build-backend
            '_tests',
            # to fail.
            '_virtualenvs',
            # Some tests may accumulate state in the objdir that may
            # become invalid after srcdir changes.
            '_tests',
        ]

        os.utime(mozpath.join(self.topobjdir, 'CLOBBER'), None)
        for d in rm_dirs:
            remove_objdir_path(d)

        os.utime(mozpath.join(self.topobjdir, 'CLOBBER'), None)
        return True
        with FileAvoidWrite(mozconfig_json) as fh:

    def _write_mozconfig_json(self):
        mozconfig_json = os.path.join(self.topobjdir, '.mozconfig.json')
        with FileAvoidWrite(mozconfig_json) as fh:
            }, sort_keys=True, indent=2))
            to_write = six.ensure_text(json.dumps({
                'topsrcdir': self.topsrcdir,
                'topobjdir': self.topobjdir,
                'mozconfig': self.mozconfig,
            }, sort_keys=True, indent=2))
            to_write = '\n'.join([line.rstrip() for line in to_write.splitlines()])
            # json.dumps in python2 inserts some trailing whitespace while
            # json.dumps in python3 does not, which defeats the FileAvoidWrite
            # mechanism. Strip the trailing whitespace to avoid rewriting this
            # file unnecessarily.
            to_write = '\n'.join([line.rstrip() for line in to_write.splitlines()])
            fh.write(to_write)
        append_env = dict(append_env or {})


    def _run_client_mk(self, target=None, line_handler=None, jobs=0,
                       verbose=None, keep_going=False, append_env=None):
        append_env = dict(append_env or {})
        append_env['TOPSRCDIR'] = self.topsrcdir

        if self._check_clobber(mozconfig, os.environ):
        append_env['CONFIG_GUESS'] = self.resolve_config_guess()

        mozconfig = self.mozconfig

        if self._check_clobber(mozconfig, os.environ):
            mozconfig_make_lines.append(arg)
            return 1

        mozconfig_make_lines = []
        for arg in mozconfig['make_extra'] or []:
                                        ' '.join(mozconfig['make_flags']))
            mozconfig_make_lines.append(arg)

        if mozconfig['make_flags']:
            mozconfig_make_lines.append('MOZ_MAKE_FLAGS=%s' %
                                        ' '.join(mozconfig['make_flags']))
        objdir = mozpath.normsep(self.topobjdir)
        if mozconfig['path']:
        mozconfig_make_lines.append('MOZ_OBJDIR=%s' % objdir)
        mozconfig_make_lines.append('OBJDIR=%s' % objdir)
            mozconfig_make_lines.append('export FOUND_MOZCONFIG')

        if mozconfig['path']:
            mozconfig_make_lines.append('FOUND_MOZCONFIG=%s' %
                                        mozpath.normsep(mozconfig['path']))
            mozconfig_make_lines.append('export FOUND_MOZCONFIG')
            line for line in mozconfig_make_lines

        # The .mozconfig.mk file only contains exported variables and lines with
        # UPLOAD_EXTRA_FILES.
        mozconfig_filtered_lines = [
            line for line in mozconfig_make_lines

            # Bug 1418122 investigate why UPLOAD_EXTRA_FILES is special and
            # remove it.
            if line.startswith('export ') or 'UPLOAD_EXTRA_FILES' in line
        ]


        mozconfig_client_mk = os.path.join(self.topobjdir,
                                           '.mozconfig-client-mk')
        with FileAvoidWrite(mozconfig_client_mk) as fh:
            fh.write('\n'.join(mozconfig_make_lines))

        # Copy the original mozconfig to the objdir.
        mozconfig_mk = os.path.join(self.topobjdir, '.mozconfig.mk')
        with FileAvoidWrite(mozconfig_mk) as fh:
            fh.write('\n'.join(mozconfig_filtered_lines))

            with open(mozconfig['path'], 'r') as ifh:
        # Copy the original mozconfig to the objdir.
        mozconfig_objdir = os.path.join(self.topobjdir, '.mozconfig')
        if mozconfig['path']:
            with open(mozconfig['path'], 'r') as ifh:
                with FileAvoidWrite(mozconfig_objdir) as ofh:
                os.unlink(mozconfig_objdir)
                    ofh.write(ifh.read())
        else:
            try:
                os.unlink(mozconfig_objdir)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise

            }, 'Adding make options from {path}\n    {content}')
        if mozconfig_make_lines:
            self.log(logging.WARNING, 'mozconfig_content', {
                'path': mozconfig['path'],
                'content': '\n    '.join(mozconfig_make_lines),
            }, 'Adding make options from {path}\n    {content}')

                              allow_parallel=False,
        append_env['OBJDIR'] = mozpath.normsep(self.topobjdir)

        return self._run_make(srcdir=True,
                              filename='client.mk',
                              allow_parallel=False,
                              log=False,
                              ensure_exit_code=False,
                              print_directory=False,
                              target=target,
                              line_handler=line_handler,
                              log=False,

                              num_jobs=jobs,
                              silent=not verbose,
                              keep_going=keep_going,
                              append_env=append_env)

            'AUTOCLOBBER=1' in (mozconfig['make_extra'] or []),
    def _check_clobber(self, mozconfig, env):
        auto_clobber = any([
            env.get('AUTOCLOBBER', False),
            (mozconfig['env'] or {}).get('added', {}).get('AUTOCLOBBER', False),
            'AUTOCLOBBER=1' in (mozconfig['make_extra'] or []),
        ])
            substs = self.substs
        from mozbuild.base import BuildEnvironmentNotFoundException
        substs = dict()
        try:
            substs = self.substs
        except BuildEnvironmentNotFoundException:
        res = clobberer.maybe_do_clobber(os.getcwd(), auto_clobber,
            # We'll just use an empty substs if there is no config.
            pass
        clobberer = Clobberer(self.topsrcdir, self.topobjdir, substs)
        clobber_output = six.StringIO()
        res = clobberer.maybe_do_clobber(os.getcwd(), auto_clobber,
                                         clobber_output)
                     {'msg': line.rstrip()}, '{msg}')
        clobber_output.seek(0)
        for line in clobber_output.readlines():
            self.log(logging.WARNING, 'clobber',
            self.mach_context.command_attrs['clobber'] = True
                     {'msg': line.rstrip()}, '{msg}')

        clobber_required, clobber_performed, clobber_message = res
        if self.mach_context is not None and clobber_performed:
            self.mach_context.command_attrs['clobber'] = True
        else:
        if not clobber_required or clobber_performed:
            if clobber_performed and env.get('TINDERBOX_OUTPUT'):
                self.log(logging.WARNING, 'clobber',
                         {'msg': 'TinderboxPrint: auto clobber'}, '{msg}')
        else:

            for line in clobber_message.splitlines():
                self.log(logging.WARNING, 'clobber',
                         {'msg': line.rstrip()}, '{msg}')
            return True

        return False