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 (31ec81b5d7bb)

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
# 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 unicode_literals

import itertools
import logging
import os
import re
import types

from collections import namedtuple

import mozbuild.makeutil as mozmakeutil
from mozpack.copier import FilePurger
from mozpack.manifests import (
    InstallManifest,
)
import mozpack.path as mozpath

from .common import CommonBackend
from ..frontend.data import (
    ConfigFileSubstitution,
    Defines,
    DirectoryTraversal,
    Exports,
    GeneratedEventWebIDLFile,
    GeneratedInclude,
    GeneratedWebIDLFile,
    HeaderFileSubstitution,
    HostProgram,
    HostSimpleProgram,
    InstallationTarget,
    IPDLFile,
    JavaJarData,
    LibraryDefinition,
    LocalInclude,
    PreprocessedTestWebIDLFile,
    PreprocessedWebIDLFile,
    Program,
    SandboxDerived,
    SandboxWrapped,
    SimpleProgram,
    TestWebIDLFile,
    VariablePassthru,
    XPIDLFile,
    TestManifest,
    WebIDLFile,
)
from ..util import (
    ensureParentDir,
    FileAvoidWrite,
)
from ..makeutil import Makefile

class BackendMakeFile(object):
    """Represents a generated backend.mk file.

    This is both a wrapper around a file handle as well as a container that
    holds accumulated state.

    It's worth taking a moment to explain the make dependencies. The
    generated backend.mk as well as the Makefile.in (if it exists) are in the
    GLOBAL_DEPS list. This means that if one of them changes, all targets
    in that Makefile are invalidated. backend.mk also depends on all of its
    input files.

    It's worth considering the effect of file mtimes on build behavior.

    Since we perform an "all or none" traversal of moz.build files (the whole
    tree is scanned as opposed to individual files), if we were to blindly
    write backend.mk files, the net effect of updating a single mozbuild file
    in the tree is all backend.mk files have new mtimes. This would in turn
    invalidate all make targets across the whole tree! This would effectively
    undermine incremental builds as any mozbuild change would cause the entire
    tree to rebuild!

    The solution is to not update the mtimes of backend.mk files unless they
    actually change. We use FileAvoidWrite to accomplish this.
    """

    def __init__(self, srcdir, objdir, environment):
        self.srcdir = srcdir
        self.objdir = objdir
        self.relobjdir = objdir[len(environment.topobjdir) + 1:]
        self.environment = environment
        self.name = os.path.join(objdir, 'backend.mk')

        # XPIDLFiles attached to this file.
        self.idls = []
        self.xpt_name = None

        self.fh = FileAvoidWrite(self.name)
        self.fh.write('# THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT.\n')
        self.fh.write('\n')
        self.fh.write('MOZBUILD_DERIVED := 1\n')

    def write(self, buf):
        self.fh.write(buf)

    # For compatibility with makeutil.Makefile
    def add_statement(self, stmt):
        self.write('%s\n' % stmt)

    def close(self):
        if self.xpt_name:
            self.fh.write('XPT_NAME := %s\n' % self.xpt_name)

            # We just recompile all xpidls because it's easier and less error
            # prone.
            self.fh.write('NONRECURSIVE_TARGETS += export\n')
            self.fh.write('NONRECURSIVE_TARGETS_export += xpidl\n')
            self.fh.write('NONRECURSIVE_TARGETS_export_xpidl_DIRECTORY = '
                '$(DEPTH)/xpcom/xpidl\n')
            self.fh.write('NONRECURSIVE_TARGETS_export_xpidl_TARGETS += '
                'export\n')

        return self.fh.close()


class RecursiveMakeTraversal(object):
    """
    Helper class to keep track of how the "traditional" recursive make backend
    recurses subdirectories. This is useful until all adhoc rules are removed
    from Makefiles.

    Each directory may have one or more types of subdirectories:
        - parallel
        - static
        - (normal) dirs
        - tests
        - tools

    The "traditional" recursive make backend recurses through those by first
    building the current directory, followed by parallel directories (in
    parallel), then static directories, dirs, tests and tools (all
    sequentially).
    """
    SubDirectoryCategories = ['parallel', 'static', 'dirs', 'tests', 'tools']
    SubDirectoriesTuple = namedtuple('SubDirectories', SubDirectoryCategories)
    class SubDirectories(SubDirectoriesTuple):
        def __new__(self):
            return RecursiveMakeTraversal.SubDirectoriesTuple.__new__(self, [], [], [], [], [])

    def __init__(self):
        self._traversal = {}

    def add(self, dir, **kargs):
        """
        Function signature is, in fact:
            def add(self, dir, parallel=[], static=[], dirs=[],
                               tests=[], tools=[])
        but it's done with **kargs to avoid repetitive code.

        Adds a directory to traversal, registering its subdirectories,
        sorted by categories. If the directory was already added to
        traversal, adds the new subdirectories to the already known lists.
        """
        subdirs = self._traversal.setdefault(dir, self.SubDirectories())
        for key, value in kargs.items():
            assert(key in self.SubDirectoryCategories)
            getattr(subdirs, key).extend(value)

    @staticmethod
    def default_filter(current, subdirs):
        """
        Default filter for use with compute_dependencies and traverse.
        """
        return current, subdirs.parallel, \
               subdirs.static + subdirs.dirs + subdirs.tests + subdirs.tools

    def call_filter(self, current, filter):
        """
        Helper function to call a filter from compute_dependencies and
        traverse.
        """
        return filter(current, self._traversal.get(current,
            self.SubDirectories()))

    def compute_dependencies(self, filter=None):
        """
        Compute make dependencies corresponding to the registered directory
        traversal.

        filter is a function with the following signature:
            def filter(current, subdirs)
        where current is the directory being traversed, and subdirs the
        SubDirectories instance corresponding to it.
        The filter function returns a tuple (filtered_current, filtered_parallel,
        filtered_dirs) where filtered_current is either current or None if
        the current directory is to be skipped, and filtered_parallel and
        filtered_dirs are lists of parallel directories and sequential
        directories, which can be rearranged from whatever is given in the
        SubDirectories members.

        The default filter corresponds to a default recursive traversal.
        """
        filter = filter or self.default_filter

        deps = {}

        def recurse(start_node, prev_nodes=None):
            current, parallel, sequential = self.call_filter(start_node, filter)
            if current is not None:
                if start_node != '':
                    deps[start_node] = prev_nodes
                prev_nodes = (start_node,)
            if not start_node in self._traversal:
                return prev_nodes
            parallel_nodes = []
            for node in parallel:
                nodes = recurse(node, prev_nodes)
                if nodes and nodes != ('',):
                    parallel_nodes.extend(nodes)
            if parallel_nodes:
                prev_nodes = tuple(parallel_nodes)
            for dir in sequential:
                prev_nodes = recurse(dir, prev_nodes)
            return prev_nodes

        return recurse(''), deps

    def traverse(self, start, filter=None):
        """
        Iterate over the filtered subdirectories, following the traditional
        make traversal order.
        """
        if filter is None:
            filter = self.default_filter

        current, parallel, sequential = self.call_filter(start, filter)
        if current is not None:
            yield start
        if not start in self._traversal:
            return
        for node in parallel:
            for n in self.traverse(node, filter):
                yield n
        for dir in sequential:
            for d in self.traverse(dir, filter):
                yield d

    def get_subdirs(self, dir):
        """
        Returns all direct subdirectories under the given directory.
        """
        return self._traversal.get(dir, self.SubDirectories())


class RecursiveMakeBackend(CommonBackend):
    """Backend that integrates with the existing recursive make build system.

    This backend facilitates the transition from Makefile.in to moz.build
    files.

    This backend performs Makefile.in -> Makefile conversion. It also writes
    out .mk files containing content derived from moz.build files. Both are
    consumed by the recursive make builder.

    This backend may eventually evolve to write out non-recursive make files.
    However, as long as there are Makefile.in files in the tree, we are tied to
    recursive make and thus will need this backend.
    """

    def _init(self):
        CommonBackend._init(self)

        self._backend_files = {}
        self._ipdl_sources = set()
        self._webidl_sources = set()
        self._generated_events_webidl_sources = set()
        self._test_webidl_sources = set()
        self._preprocessed_test_webidl_sources = set()
        self._preprocessed_webidl_sources = set()
        self._generated_webidl_sources = set()

        def detailed(summary):
            s = '{:d} total backend files. {:d} created; {:d} updated; {:d} unchanged'.format(
                summary.created_count + summary.updated_count +
                summary.unchanged_count, summary.created_count,
                summary.updated_count, summary.unchanged_count)
            if summary.deleted_count:
                s+= '; {:d} deleted'.format(summary.deleted_count)
            return s

        # This is a little kludgy and could be improved with a better API.
        self.summary.backend_detailed_summary = types.MethodType(detailed,
            self.summary)

        self._test_manifests = {}

        self.backend_input_files.add(os.path.join(self.environment.topobjdir,
            'config', 'autoconf.mk'))

        self._install_manifests = {
            k: InstallManifest() for k in [
                'dist_bin',
                'dist_idl',
                'dist_include',
                'dist_public',
                'dist_private',
                'dist_sdk',
                'tests',
                'xpidl',
            ]}

        self._traversal = RecursiveMakeTraversal()
        self._may_skip = {
            'export': set(),
            'compile': set(),
            'binaries': set(),
            'libs': set(),
            'tools': set(),
        }

        derecurse = self.environment.substs.get('MOZ_PSEUDO_DERECURSE', '').split(',')
        self._parallel_export = False
        self._no_skip = False
        if derecurse != ['']:
            self._parallel_export = 'no-parallel-export' not in derecurse
            self._no_skip = 'no-skip' in derecurse

    def consume_object(self, obj):
        """Write out build files necessary to build with recursive make."""

        CommonBackend.consume_object(self, obj)

        if not isinstance(obj, SandboxDerived):
            return

        if obj.srcdir not in self._backend_files:
            self._backend_files[obj.srcdir] = \
                BackendMakeFile(obj.srcdir, obj.objdir, self.get_environment(obj))
        backend_file = self._backend_files[obj.srcdir]

        if isinstance(obj, DirectoryTraversal):
            self._process_directory_traversal(obj, backend_file)
        elif isinstance(obj, ConfigFileSubstitution):
            with self._write_file(obj.output_path) as fh:
                backend_file.environment.create_config_file(fh)
            self.backend_input_files.add(obj.input_path)
        elif isinstance(obj, HeaderFileSubstitution):
            with self._write_file(obj.output_path) as fh:
                backend_file.environment.create_config_header(fh)
            self.backend_input_files.add(obj.input_path)
        elif isinstance(obj, XPIDLFile):
            backend_file.idls.append(obj)
            backend_file.xpt_name = '%s.xpt' % obj.module
        elif isinstance(obj, VariablePassthru):
            unified_suffixes = dict(
                UNIFIED_CSRCS='c',
                UNIFIED_CMMSRCS='mm',
                UNIFIED_CPPSRCS='cpp',
            )

            files_per_unification = 16
            if 'FILES_PER_UNIFIED_FILE' in obj.variables.keys():
                files_per_unification = obj.variables['FILES_PER_UNIFIED_FILE']

            do_unify = not self.environment.substs.get(
                'MOZ_DISABLE_UNIFIED_COMPILATION') and files_per_unification > 1

            # Sorted so output is consistent and we don't bump mtimes.
            for k, v in sorted(obj.variables.items()):
                if k in unified_suffixes:
                    if do_unify:
                        self._add_unified_build_rules(backend_file, v,
                            backend_file.objdir,
                            unified_prefix='Unified_%s_%s' % (
                                unified_suffixes[k],
                                backend_file.relobjdir.replace('/', '_')),
                            unified_suffix=unified_suffixes[k],
                            unified_files_makefile_variable=k,
                            include_curdir_build_rules=False,
                            files_per_unified_file=files_per_unification)
                        backend_file.write('%s += $(%s)\n' % (k[len('UNIFIED_'):], k))
                    else:
                        backend_file.write('%s += %s\n' % (
                            k[len('UNIFIED_'):], ' '.join(sorted(v))))
                elif isinstance(v, list):
                    for item in v:
                        backend_file.write('%s += %s\n' % (k, item))
                elif isinstance(v, bool):
                    if v:
                        backend_file.write('%s := 1\n' % k)
                else:
                    backend_file.write('%s := %s\n' % (k, v))

        elif isinstance(obj, Defines):
            defines = obj.get_defines()
            if defines:
                backend_file.write('DEFINES +=')
                for define in defines:
                    backend_file.write(' %s' % define)
                backend_file.write('\n')

        elif isinstance(obj, Exports):
            self._process_exports(obj, obj.exports, backend_file)

        elif isinstance(obj, IPDLFile):
            self._ipdl_sources.add(mozpath.join(obj.srcdir, obj.basename))

        elif isinstance(obj, WebIDLFile):
            self._webidl_sources.add(mozpath.join(obj.srcdir, obj.basename))
            self._process_webidl_basename(obj.basename)

        elif isinstance(obj, GeneratedEventWebIDLFile):
            self._generated_events_webidl_sources.add(mozpath.join(obj.srcdir, obj.basename))

        elif isinstance(obj, TestWebIDLFile):
            self._test_webidl_sources.add(mozpath.join(obj.srcdir,
                                                       obj.basename))
            # Test WebIDL files are not exported.

        elif isinstance(obj, PreprocessedTestWebIDLFile):
            self._preprocessed_test_webidl_sources.add(mozpath.join(obj.srcdir,
                                                                    obj.basename))
            # Test WebIDL files are not exported.

        elif isinstance(obj, GeneratedWebIDLFile):
            self._generated_webidl_sources.add(mozpath.join(obj.srcdir,
                                                            obj.basename))
            self._process_webidl_basename(obj.basename)

        elif isinstance(obj, PreprocessedWebIDLFile):
            self._preprocessed_webidl_sources.add(mozpath.join(obj.srcdir,
                                                               obj.basename))
            self._process_webidl_basename(obj.basename)

        elif isinstance(obj, Program):
            self._process_program(obj.program, backend_file)

        elif isinstance(obj, HostProgram):
            self._process_host_program(obj.program, backend_file)

        elif isinstance(obj, SimpleProgram):
            self._process_simple_program(obj.program, backend_file)

        elif isinstance(obj, HostSimpleProgram):
            self._process_host_simple_program(obj.program, backend_file)

        elif isinstance(obj, TestManifest):
            self._process_test_manifest(obj, backend_file)

        elif isinstance(obj, LocalInclude):
            self._process_local_include(obj.path, backend_file)

        elif isinstance(obj, GeneratedInclude):
            self._process_generated_include(obj.path, backend_file)

        elif isinstance(obj, InstallationTarget):
            self._process_installation_target(obj, backend_file)

        elif isinstance(obj, SandboxWrapped):
            # Process a rich build system object from the front-end
            # as-is.  Please follow precedent and handle CamelCaseData
            # in a function named _process_camel_case_data.  At some
            # point in the future, this unwrapping process may be
            # automated.
            if isinstance(obj.wrapped, JavaJarData):
                self._process_java_jar_data(obj.wrapped, backend_file)
            else:
                return

        elif isinstance(obj, LibraryDefinition):
            self._process_library_definition(obj, backend_file)

        else:
            return
        obj.ack()

    def _fill_root_mk(self):
        """
        Create two files, root.mk and root-deps.mk, the first containing
        convenience variables, and the other dependency definitions for a
        hopefully proper directory traversal.
        """
        if not self._no_skip:
            for tier, skip in self._may_skip.items():
                self.log(logging.DEBUG, 'fill_root_mk', {
                    'number': len(skip), 'tier': tier
                    }, 'Ignoring {number} directories during {tier}')

        # Traverse directories in parallel, and skip static dirs
        def parallel_filter(current, subdirs):
            all_subdirs = subdirs.parallel + subdirs.dirs + \
                          subdirs.tests + subdirs.tools
            if current in self._may_skip[tier]:
                current = None
            # subtiers/*_start and subtiers/*_finish, under subtiers/*, are
            # kept sequential. Others are all forced parallel.
            if current and current.startswith('subtiers/') and all_subdirs and \
                    all_subdirs[0].startswith('subtiers/'):
                return current, [], all_subdirs
            return current, all_subdirs, []

        # Skip static dirs during export traversal, or build everything in
        # parallel when enabled.
        def export_filter(current, subdirs):
            if self._parallel_export:
                return parallel_filter(current, subdirs)
            return current, subdirs.parallel, \
                subdirs.dirs + subdirs.tests + subdirs.tools

        # Skip tools dirs during libs traversal. Because of bug 925236 and
        # possible other unknown race conditions, don't parallelize the libs
        # tier.
        def libs_filter(current, subdirs):
            if current in self._may_skip[tier]:
                current = None
            return current, [], subdirs.parallel + \
                subdirs.static + subdirs.dirs + subdirs.tests

        # Because of bug 925236 and possible other unknown race conditions,
        # don't parallelize the tools tier.
        def tools_filter(current, subdirs):
            if current in self._may_skip[tier]:
                current = None
            return current, subdirs.parallel, \
                subdirs.static + subdirs.dirs + subdirs.tests + subdirs.tools

        # compile, binaries and tools tiers use the same traversal as export
        filters = {
            'export': export_filter,
            'compile': parallel_filter,
            'binaries': parallel_filter,
            'libs': libs_filter,
            'tools': tools_filter,
        }

        root_deps_mk = Makefile()

        # Fill the dependencies for traversal of each tier.
        for tier, filter in filters.items():
            main, all_deps = \
                self._traversal.compute_dependencies(filter)
            for dir, deps in all_deps.items():
                rule = root_deps_mk.create_rule(['%s/%s' % (dir, tier)])
                if deps is not None:
                    rule.add_dependencies('%s/%s' % (d, tier) for d in deps if d)
            rule = root_deps_mk.create_rule(['recurse_%s' % tier])
            if main:
                rule.add_dependencies('%s/%s' % (d, tier) for d in main)

        root_mk = Makefile()

        # Fill root.mk with the convenience variables.
        for tier, filter in filters.items() + [('all', self._traversal.default_filter)]:
            # Gather filtered subtiers for the given tier
            all_direct_subdirs = reduce(lambda x, y: x + y,
                                        self._traversal.get_subdirs(''), [])
            direct_subdirs = [d for d in all_direct_subdirs
                              if filter(d, self._traversal.get_subdirs(d))[0]]
            subtiers = [d.replace('subtiers/', '') for d in direct_subdirs
                        if d.startswith('subtiers/')]

            if tier != 'all':
                # Gather filtered directories for the given tier
                dirs = [d for d in direct_subdirs if not d.startswith('subtiers/')]
                if dirs:
                    # For build systems without tiers (js/src), output a list
                    # of directories for each tier.
                    root_mk.add_statement('%s_dirs := %s' % (tier, ' '.join(dirs)))
                    continue
                if subtiers:
                    # Output the list of filtered subtiers for the given tier.
                    root_mk.add_statement('%s_subtiers := %s' % (tier, ' '.join(subtiers)))

            for subtier in subtiers:
                # subtier_dirs[0] is 'subtiers/%s_start' % subtier, skip it
                subtier_dirs = list(self._traversal.traverse('subtiers/%s_start' % subtier, filter))[1:]
                if tier == 'all':
                    for dir in subtier_dirs:
                        # Output convenience variables to be able to map directories
                        # to subtier names from Makefiles.
                        stamped = dir.replace('/', '_')
                        root_mk.add_statement('subtier_of_%s := %s' % (stamped, subtier))

                else:
                    # Output the list of filtered directories for each tier/subtier
                    # pair.
                    root_mk.add_statement('%s_subtier_%s := %s' % (tier, subtier, ' '.join(subtier_dirs)))

        root_mk.add_statement('$(call include_deps,root-deps.mk)')

        with self._write_file(
                os.path.join(self.environment.topobjdir, 'root.mk')) as root:
            root_mk.dump(root, removal_guard=False)

        with self._write_file(
                os.path.join(self.environment.topobjdir, 'root-deps.mk')) as root_deps:
            root_deps_mk.dump(root_deps, removal_guard=False)

    def _add_unified_build_rules(self, makefile, files, output_directory,
                                 unified_prefix='Unified',
                                 unified_suffix='cpp',
                                 extra_dependencies=[],
                                 unified_files_makefile_variable='unified_files',
                                 include_curdir_build_rules=True,
                                 poison_windows_h=False,
                                 files_per_unified_file=16):

        explanation = "\n" \
            "# We build files in 'unified' mode by including several files\n" \
            "# together into a single source file.  This cuts down on\n" \
            "# compilation times and debug information size.  %d was chosen as\n" \
            "# a reasonable compromise between clobber rebuild time, incremental\n" \
            "# rebuild time, and compiler memory usage." % files_per_unified_file
        makefile.add_statement(explanation)

        def unified_files():
            "Return an iterator of (unified_filename, source_filenames) tuples."
            # Our last returned list of source filenames may be short, and we
            # don't want the fill value inserted by izip_longest to be an
            # issue.  So we do a little dance to filter it out ourselves.
            dummy_fill_value = ("dummy",)
            def filter_out_dummy(iterable):
                return itertools.ifilter(lambda x: x != dummy_fill_value,
                                         iterable)

            # From the itertools documentation, slightly modified:
            def grouper(n, iterable):
                "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
                args = [iter(iterable)] * n
                return itertools.izip_longest(fillvalue=dummy_fill_value, *args)

            for i, unified_group in enumerate(grouper(files_per_unified_file,
                                                      sorted(files))):
                just_the_filenames = list(filter_out_dummy(unified_group))
                yield '%s%d.%s' % (unified_prefix, i, unified_suffix), just_the_filenames

        all_sources = ' '.join(source for source, _ in unified_files())
        makefile.add_statement('%s := %s' % (unified_files_makefile_variable,
                                               all_sources))

        for unified_file, source_filenames in unified_files():
            if extra_dependencies:
                rule = makefile.create_rule([unified_file])
                rule.add_dependencies(extra_dependencies)

            # The rule we just defined is only for cases where the cpp files get
            # blown away and we need to regenerate them.  The rule doesn't correctly
            # handle source files being added/removed/renamed.  Therefore, we
            # generate them here also to make sure everything's up-to-date.
            with self._write_file(os.path.join(output_directory, unified_file)) as f:
                f.write('#define MOZ_UNIFIED_BUILD\n')
                includeTemplate = '#include "%(cppfile)s"'
                if poison_windows_h:
                    includeTemplate += (
                        '\n'
                        '#ifdef _WINDOWS_\n'
                        '#error "%(cppfile)s included windows.h"\n'
                        "#endif")
                includeTemplate += (
                    '\n'
                    '#ifdef PL_ARENA_CONST_ALIGN_MASK\n'
                    '#error "%(cppfile)s uses PL_ARENA_CONST_ALIGN_MASK, '
                    'so it cannot be built in unified mode."\n'
                    '#undef PL_ARENA_CONST_ALIGN_MASK\n'
                    '#endif\n'
                    '#ifdef FORCE_PR_LOG\n'
                    '#error "%(cppfile)s forces NSPR logging, '
                    'so it cannot be built in unified mode."\n'
                    '#undef FORCE_PR_LOG\n'
                    '#endif')
                f.write('\n'.join(includeTemplate % { "cppfile": s } for
                                  s in source_filenames))

        if include_curdir_build_rules:
            makefile.add_statement('\n'
                '# Make sometimes gets confused between "foo" and "$(CURDIR)/foo".\n'
                '# Help it out by explicitly specifiying dependencies.')
            makefile.add_statement('all_absolute_unified_files := \\\n'
                                   '  $(addprefix $(CURDIR)/,$(%s))'
                                   % unified_files_makefile_variable)
            rule = makefile.create_rule(['$(all_absolute_unified_files)'])
            rule.add_dependencies(['$(CURDIR)/%: %'])

    def consume_finished(self):
        CommonBackend.consume_finished(self)

        for srcdir in sorted(self._backend_files.keys()):
            with self._write_file(fh=self._backend_files[srcdir]) as bf:
                makefile_in = os.path.join(srcdir, 'Makefile.in')
                makefile = os.path.join(bf.objdir, 'Makefile')

                # If Makefile.in exists, use it as a template. Otherwise,
                # create a stub.
                stub = not os.path.exists(makefile_in)
                if not stub:
                    self.log(logging.DEBUG, 'substitute_makefile',
                        {'path': makefile}, 'Substituting makefile: {path}')

                    # Adding the Makefile.in here has the desired side-effect
                    # that if the Makefile.in disappears, this will force
                    # moz.build traversal. This means that when we remove empty
                    # Makefile.in files, the old file will get replaced with
                    # the autogenerated one automatically.
                    self.backend_input_files.add(makefile_in)

                    for tier, skiplist in self._may_skip.items():
                        if tier in ('compile', 'binaries'):
                            continue
                        if bf.relobjdir in skiplist:
                            skiplist.remove(bf.relobjdir)
                else:
                    self.log(logging.DEBUG, 'stub_makefile',
                        {'path': makefile}, 'Creating stub Makefile: {path}')

                # Can't skip directories with a jar.mn for the 'libs' tier.
                if bf.relobjdir in self._may_skip['libs'] and \
                        os.path.exists(os.path.join(srcdir, 'jar.mn')):
                    self._may_skip['libs'].remove(bf.relobjdir)

                with self._write_file(makefile) as fh:
                    bf.environment.create_makefile(fh, stub=stub)

        # Write out a master list of all IPDL source files.
        ipdl_dir = os.path.join(self.environment.topobjdir, 'ipc', 'ipdl')
        mk = mozmakeutil.Makefile()

        sorted_ipdl_sources = list(sorted(self._ipdl_sources))
        mk.add_statement('ALL_IPDLSRCS := %s' % ' '.join(sorted_ipdl_sources))

        def files_from(ipdl):
            base = os.path.basename(ipdl)
            root, ext = os.path.splitext(base)

            # Both .ipdl and .ipdlh become .cpp files
            files = ['%s.cpp' % root]
            if ext == '.ipdl':
                # .ipdl also becomes Child/Parent.cpp files
                files.extend(['%sChild.cpp' % root,
                              '%sParent.cpp' % root])
            return files

        ipdl_cppsrcs = list(itertools.chain(*[files_from(p) for p in sorted_ipdl_sources]))
        self._add_unified_build_rules(mk, ipdl_cppsrcs, ipdl_dir,
                                      unified_prefix='UnifiedProtocols',
                                      unified_files_makefile_variable='CPPSRCS')

        mk.add_statement('IPDLDIRS := %s' % ' '.join(sorted(set(os.path.dirname(p)
            for p in self._ipdl_sources))))

        with self._write_file(os.path.join(ipdl_dir, 'ipdlsrcs.mk')) as ipdls:
            mk.dump(ipdls, removal_guard=False)

        self._may_skip['compile'] -= set(['ipc/ipdl'])

        # Write out master lists of WebIDL source files.
        bindings_dir = os.path.join(self.environment.topobjdir, 'dom', 'bindings')

        mk = mozmakeutil.Makefile()

        def write_var(variable, sources):
            files = [os.path.basename(f) for f in sorted(sources)]
            mk.add_statement('%s += %s' % (variable, ' '.join(files)))
        write_var('webidl_files', self._webidl_sources)
        write_var('generated_events_webidl_files', self._generated_events_webidl_sources)
        write_var('test_webidl_files', self._test_webidl_sources)
        write_var('preprocessed_test_webidl_files', self._preprocessed_test_webidl_sources)
        write_var('generated_webidl_files', self._generated_webidl_sources)
        write_var('preprocessed_webidl_files', self._preprocessed_webidl_sources)

        all_webidl_files = itertools.chain(iter(self._webidl_sources),
                                           iter(self._generated_events_webidl_sources),
                                           iter(self._generated_webidl_sources),
                                           iter(self._preprocessed_webidl_sources))
        all_webidl_files = [os.path.basename(x) for x in all_webidl_files]
        all_webidl_sources = [re.sub(r'\.webidl$', 'Binding.cpp', x) for x in all_webidl_files]

        self._add_unified_build_rules(mk, all_webidl_sources,
                                      bindings_dir,
                                      unified_prefix='UnifiedBindings',
                                      unified_files_makefile_variable='unified_binding_cpp_files',
                                      poison_windows_h=True)

        # Assume that Somebody Else has responsibility for correctly
        # specifying removal dependencies for |all_webidl_sources|.
        with self._write_file(os.path.join(bindings_dir, 'webidlsrcs.mk')) as webidls:
            mk.dump(webidls, removal_guard=False)

        self._may_skip['compile'] -= set(['dom/bindings', 'dom/bindings/test'])

        self._fill_root_mk()

        # Write out a dependency file used to determine whether a config.status
        # re-run is needed.
        inputs = sorted(p.replace(os.sep, '/') for p in self.backend_input_files)

        # We need to use $(DEPTH) so the target here matches what's in
        # rules.mk. If they are different, the dependencies don't get pulled in
        # properly.
        with self._write_file('%s.pp' % self._backend_output_list_file) as backend_deps:
            backend_deps.write('$(DEPTH)/backend.%s: %s\n' %
                (self.__class__.__name__, ' '.join(inputs)))
            for path in inputs:
                backend_deps.write('%s:\n' % path)

        with open(self._backend_output_list_file, 'a'):
            pass
        os.utime(self._backend_output_list_file, None)

        # Make the master test manifest files.
        for flavor, t in self._test_manifests.items():
            install_prefix, manifests = t
            manifest_stem = os.path.join(install_prefix, '%s.ini' % flavor)
            self._write_master_test_manifest(os.path.join(
                self.environment.topobjdir, '_tests', manifest_stem),
                manifests)

            # Catch duplicate inserts.
            try:
                self._install_manifests['tests'].add_optional_exists(manifest_stem)
            except ValueError:
                pass

        self._write_manifests('install', self._install_manifests)

        ensureParentDir(os.path.join(self.environment.topobjdir, 'dist', 'foo'))

    def _process_directory_traversal(self, obj, backend_file):
        """Process a data.DirectoryTraversal instance."""
        fh = backend_file.fh

        def relativize(dirs):
            return [mozpath.normpath(mozpath.join(backend_file.relobjdir, d))
                for d in dirs]

        for tier, dirs in obj.tier_dirs.iteritems():
            fh.write('TIERS += %s\n' % tier)
            # For pseudo derecursification, subtiers are treated as pseudo
            # directories, with a special hierarchy:
            # - subtier1 - subtier1_start - dirA - dirAA
            # |          |                |      + dirAB
            # |          |                ...
            # |          |                + dirB
            # |          + subtier1_finish
            # + subtier2 - subtier2_start ...
            # ...        + subtier2_finish
            self._traversal.add('subtiers/%s' % tier,
                                dirs=['subtiers/%s_start' % tier,
                                      'subtiers/%s_finish' % tier])

            if dirs:
                fh.write('tier_%s_dirs += %s\n' % (tier, ' '.join(dirs)))
                fh.write('DIRS += $(tier_%s_dirs)\n' % tier)
                self._traversal.add('subtiers/%s_start' % tier,
                                    dirs=relativize(dirs))

            # tier_static_dirs should have the same keys as tier_dirs.
            if obj.tier_static_dirs[tier]:
                fh.write('tier_%s_staticdirs += %s\n' % (
                    tier, ' '.join(obj.tier_static_dirs[tier])))
                self._traversal.add('subtiers/%s_start' % tier,
                                    static=relativize(obj.tier_static_dirs[tier]))

            self._traversal.add('subtiers/%s_start' % tier)
            self._traversal.add('subtiers/%s_finish' % tier)
            self._traversal.add('', dirs=['subtiers/%s' % tier])

        if obj.dirs:
            fh.write('DIRS := %s\n' % ' '.join(obj.dirs))
            self._traversal.add(backend_file.relobjdir, dirs=relativize(obj.dirs))

        if obj.parallel_dirs:
            fh.write('PARALLEL_DIRS := %s\n' % ' '.join(obj.parallel_dirs))
            self._traversal.add(backend_file.relobjdir,
                                parallel=relativize(obj.parallel_dirs))

        if obj.tool_dirs:
            fh.write('TOOL_DIRS := %s\n' % ' '.join(obj.tool_dirs))
            self._traversal.add(backend_file.relobjdir,
                                tools=relativize(obj.tool_dirs))

        if obj.test_dirs:
            fh.write('TEST_DIRS := %s\n' % ' '.join(obj.test_dirs))
            if self.environment.substs.get('ENABLE_TESTS', False):
                self._traversal.add(backend_file.relobjdir,
                                    tests=relativize(obj.test_dirs))

        if obj.test_tool_dirs and \
            self.environment.substs.get('ENABLE_TESTS', False):

            fh.write('TOOL_DIRS += %s\n' % ' '.join(obj.test_tool_dirs))
            self._traversal.add(backend_file.relobjdir,
                                tools=relativize(obj.test_tool_dirs))

        if len(obj.external_make_dirs):
            fh.write('DIRS += %s\n' % ' '.join(obj.external_make_dirs))
            self._traversal.add(backend_file.relobjdir,
                                dirs=relativize(obj.external_make_dirs))

        if len(obj.parallel_external_make_dirs):
            fh.write('PARALLEL_DIRS += %s\n' %
                ' '.join(obj.parallel_external_make_dirs))
            self._traversal.add(backend_file.relobjdir,
                                parallel=relativize(obj.parallel_external_make_dirs))

        # The directory needs to be registered whether subdirectories have been
        # registered or not.
        self._traversal.add(backend_file.relobjdir)

        if obj.is_tool_dir:
            fh.write('IS_TOOL_DIR := 1\n')

        if self._no_skip:
            return

        affected_tiers = set(obj.affected_tiers)
        # Until all SOURCES are really in moz.build, consider all directories
        # building binaries to require a pass at compile, too.
        if 'binaries' in affected_tiers:
            affected_tiers.add('compile')
        if 'compile' in affected_tiers or 'binaries' in affected_tiers:
            affected_tiers.add('libs')
        if obj.is_tool_dir and 'libs' in affected_tiers:
            affected_tiers.remove('libs')
            affected_tiers.add('tools')

        for tier in set(self._may_skip.keys()) - affected_tiers:
            self._may_skip[tier].add(backend_file.relobjdir)

    def _process_exports(self, obj, exports, backend_file, namespace=""):
        # This may not be needed, but is present for backwards compatibility
        # with the old make rules, just in case.
        if not obj.dist_install:
            return

        strings = exports.get_strings()
        if namespace:
            namespace += '/'

        for s in strings:
            source = os.path.normpath(os.path.join(obj.srcdir, s))
            dest = '%s%s' % (namespace, os.path.basename(s))
            self._install_manifests['dist_include'].add_symlink(source, dest)

            if not os.path.exists(source):
                raise Exception('File listed in EXPORTS does not exist: %s' % source)

        children = exports.get_children()
        for subdir in sorted(children):
            self._process_exports(obj, children[subdir], backend_file,
                namespace=namespace + subdir)

    def _process_installation_target(self, obj, backend_file):
        # A few makefiles need to be able to override the following rules via
        # make XPI_NAME=blah commands, so we default to the lazy evaluation as
        # much as possible here to avoid breaking things.
        if obj.xpiname:
            backend_file.write('XPI_NAME = %s\n' % (obj.xpiname))
        if obj.subdir:
            backend_file.write('DIST_SUBDIR = %s\n' % (obj.subdir))
        if obj.target and not obj.is_custom():
            backend_file.write('FINAL_TARGET = $(DEPTH)/%s\n' % (obj.target))
        else:
            backend_file.write('FINAL_TARGET = $(if $(XPI_NAME),$(DIST)/xpi-stage/$(XPI_NAME),$(DIST)/bin)$(DIST_SUBDIR:%=/%)\n')

        if not obj.enabled:
            backend_file.write('NO_DIST_INSTALL := 1\n')

    def _handle_idl_manager(self, manager):
        build_files = self._install_manifests['xpidl']

        for p in ('Makefile', 'backend.mk', '.deps/.mkdir.done',
            'xpt/.mkdir.done'):
            build_files.add_optional_exists(p)

        for idl in manager.idls.values():
            self._install_manifests['dist_idl'].add_symlink(idl['source'],
                idl['basename'])
            self._install_manifests['dist_include'].add_optional_exists('%s.h'
                % idl['root'])

        for module in manager.modules:
            build_files.add_optional_exists(mozpath.join('xpt',
                '%s.xpt' % module))
            build_files.add_optional_exists(mozpath.join('.deps',
                '%s.pp' % module))

        modules = manager.modules
        xpt_modules = sorted(modules.keys())
        rules = []

        for module in xpt_modules:
            deps = sorted(modules[module])
            idl_deps = ['$(dist_idl_dir)/%s.idl' % dep for dep in deps]
            rules.extend([
                # It may seem strange to have the .idl files listed as
                # prerequisites both here and in the auto-generated .pp files.
                # It is necessary to list them here to handle the case where a
                # new .idl is added to an xpt. If we add a new .idl and nothing
                # else has changed, the new .idl won't be referenced anywhere
                # except in the command invocation. Therefore, the .xpt won't
                # be rebuilt because the dependencies say it is up to date. By
                # listing the .idls here, we ensure the make file has a
                # reference to the new .idl. Since the new .idl presumably has
                # an mtime newer than the .xpt, it will trigger xpt generation.
                '$(idl_xpt_dir)/%s.xpt: %s' % (module, ' '.join(idl_deps)),
                '\t@echo "$(notdir $@)"',
                '\t$(idlprocess) $(basename $(notdir $@)) %s' % ' '.join(deps),
                '',
            ])

        # Create dependency for output header so we force regeneration if the
        # header was deleted. This ideally should not be necessary. However,
        # some processes (such as PGO at the time this was implemented) wipe
        # out dist/include without regard to our install manifests.

        out_path = os.path.join(self.environment.topobjdir, 'config',
            'makefiles', 'xpidl', 'Makefile')
        with self._write_file(out_path) as fh:
            self.environment.create_config_file(fh, extra=dict(
                xpidl_rules='\n'.join(rules),
                xpidl_modules=' '.join(xpt_modules),
            ))

        # The Makefile can't regenerate itself because of custom substitution.
        # We need to list it here to ensure changes cause regeneration.
        self.backend_input_files.add(os.path.join(self.environment.topsrcdir,
            'config', 'makefiles', 'xpidl', 'Makefile.in'))

    def _process_program(self, program, backend_file):
        backend_file.write('PROGRAM = %s\n' % program)

    def _process_host_program(self, program, backend_file):
        backend_file.write('HOST_PROGRAM = %s\n' % program)

    def _process_simple_program(self, program, backend_file):
        backend_file.write('SIMPLE_PROGRAMS += %s\n' % program)

    def _process_host_simple_program(self, program, backend_file):
        backend_file.write('HOST_SIMPLE_PROGRAMS += %s\n' % program)

    def _process_webidl_basename(self, basename):
        header = 'mozilla/dom/%sBinding.h' % os.path.splitext(basename)[0]
        self._install_manifests['dist_include'].add_optional_exists(header)

    def _process_test_manifest(self, obj, backend_file):
        # Much of the logic in this function could be moved to CommonBackend.
        self.backend_input_files.add(os.path.join(obj.topsrcdir,
            obj.manifest_relpath))

        # Duplicate manifests may define the same file. That's OK.
        for source, dest in obj.installs.items():
            try:
                self._install_manifests['tests'].add_symlink(source, dest)
            except ValueError:
                if not obj.dupe_manifest:
                    raise

        for dest in obj.external_installs:
            try:
                self._install_manifests['tests'].add_optional_exists(dest)
            except ValueError:
                if not obj.dupe_manifest:
                    raise

        m = self._test_manifests.setdefault(obj.flavor,
            (obj.install_prefix, set()))
        m[1].add(obj.manifest_relpath)

    def _process_local_include(self, local_include, backend_file):
        if local_include.startswith('/'):
            path = '$(topsrcdir)'
        else:
            path = '$(srcdir)/'
        backend_file.write('LOCAL_INCLUDES += -I%s%s\n' % (path, local_include))

    def _process_generated_include(self, generated_include, backend_file):
        if generated_include.startswith('/'):
            path = self.environment.topobjdir.replace('\\', '/')
        else:
            path = ''
        backend_file.write('LOCAL_INCLUDES += -I%s%s\n' % (path, generated_include))

    def _process_java_jar_data(self, jar, backend_file):
        target = jar.name
        backend_file.write('JAVA_JAR_TARGETS += %s\n' % target)
        backend_file.write('%s_DEST := %s.jar\n' % (target, jar.name))
        if jar.sources:
            backend_file.write('%s_JAVAFILES := %s\n' %
                (target, ' '.join(jar.sources)))
        if jar.generated_sources:
            backend_file.write('%s_PP_JAVAFILES := %s\n' %
                (target, ' '.join(os.path.join('generated', f) for f in jar.generated_sources)))
        if jar.extra_jars:
            backend_file.write('%s_EXTRA_JARS := %s\n' %
                (target, ' '.join(jar.extra_jars)))
        if jar.javac_flags:
            backend_file.write('%s_JAVAC_FLAGS := %s\n' %
                (target, ' '.join(jar.javac_flags)))

    def _process_library_definition(self, libdef, backend_file):
        backend_file.write('LIBRARY_NAME = %s\n' % libdef.basename)
        thisobjdir = libdef.objdir
        topobjdir = libdef.topobjdir.replace(os.sep, '/')
        for objdir, basename in libdef.static_libraries:
            # If this is an external objdir (i.e., comm-central), use the other
            # directory instead of $(DEPTH).
            if objdir.startswith(topobjdir + '/'):
                relpath = '$(DEPTH)/%s' % mozpath.relpath(objdir, topobjdir)
            else:
                relpath = mozpath.relpath(objdir, thisobjdir)
            backend_file.write('SHARED_LIBRARY_LIBS += %s/$(LIB_PREFIX)%s.$(LIB_SUFFIX)\n'
                               % (relpath, basename))

    def _write_manifests(self, dest, manifests):
        man_dir = os.path.join(self.environment.topobjdir, '_build_manifests',
            dest)

        # We have a purger for the manifests themselves to ensure legacy
        # manifests are deleted.
        purger = FilePurger()

        for k, manifest in manifests.items():
            purger.add(k)

            with self._write_file(os.path.join(man_dir, k)) as fh:
                manifest.write(fileobj=fh)

        purger.purge(man_dir)

    def _write_master_test_manifest(self, path, manifests):
        with self._write_file(path) as master:
            master.write(
                '; THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT MODIFY BY HAND.\n\n')

            for manifest in sorted(manifests):
                master.write('[include:%s]\n' % manifest)