1#!/bin/sh
2# This Source Code Form is subject to the terms of the Mozilla Public
3# License, v. 2.0. If a copy of the MPL was not distributed with this
4# file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
6# The beginning of this script is both valid shell and valid python,
7# such that the script starts with the shell and is reexecuted with
8# the right python.
9'''which' python2.7 > /dev/null && exec python2.7 "$0" "$@" || exec python "$0" "$@"
10'''
11
12from __future__ import print_function, unicode_literals
13
14import os
15import sys
16
17def ancestors(path):
18    while path:
19        yield path
20        (path, child) = os.path.split(path)
21        if child == "":
22            break
23
24def load_mach(dir_path, mach_path):
25    import imp
26    with open(mach_path, 'r') as fh:
27        imp.load_module('mach_bootstrap', fh, mach_path,
28                        ('.py', 'r', imp.PY_SOURCE))
29    import mach_bootstrap
30    return mach_bootstrap.bootstrap(dir_path)
31
32
33def check_and_get_mach(dir_path):
34    bootstrap_paths = (
35        'build/mach_bootstrap.py',
36        # test package bootstrap
37        'tools/mach_bootstrap.py',
38    )
39    for bootstrap_path in bootstrap_paths:
40        mach_path = os.path.join(dir_path, bootstrap_path)
41        if os.path.isfile(mach_path):
42            return load_mach(dir_path, mach_path)
43    return None
44
45
46def get_mach():
47    # Check whether the current directory is within a mach src or obj dir.
48    for dir_path in ancestors(os.getcwd()):
49        # If we find a "config.status" and "mozinfo.json" file, we are in the objdir.
50        config_status_path = os.path.join(dir_path, 'config.status')
51        mozinfo_path = os.path.join(dir_path, 'mozinfo.json')
52        if os.path.isfile(config_status_path) and os.path.isfile(mozinfo_path):
53            import json
54            info = json.load(open(mozinfo_path))
55            if 'mozconfig' in info and 'MOZCONFIG' not in os.environ:
56                # If the MOZCONFIG environment variable is not already set, set it
57                # to the value from mozinfo.json.  This will tell the build system
58                # to look for a config file at the path in $MOZCONFIG rather than
59                # its default locations.
60                #
61                # Note: subprocess requires native strings in os.environ on Windows
62                os.environ[b'MOZCONFIG'] = str(info['mozconfig'])
63
64            if 'topsrcdir' in info:
65                # Continue searching for mach_bootstrap in the source directory.
66                dir_path = info['topsrcdir']
67
68        mach = check_and_get_mach(dir_path)
69        if mach:
70            return mach
71
72    # If we didn't find a source path by scanning for a mozinfo.json, check
73    # whether the directory containing this script is a source directory. We
74    # follow symlinks so mach can be run even if cwd is outside the srcdir.
75    return check_and_get_mach(os.path.dirname(os.path.realpath(__file__)))
76
77def main(args):
78    mach = get_mach()
79    if not mach:
80        print('Could not run mach: No mach source directory found.')
81        sys.exit(1)
82    sys.exit(mach.run(args))
83
84
85if __name__ == '__main__':
86    if sys.platform == 'win32':
87        # This is a complete hack to work around the fact that Windows
88        # multiprocessing needs to import the original module (ie: this
89        # file), but only works if it has a .py extension.
90        #
91        # We do this by a sort of two-level function interposing. The first
92        # level interposes forking.get_command_line() with our version defined
93        # in my_get_command_line(). Our version of get_command_line will
94        # replace the command string with the contents of the fork_interpose()
95        # function to be used in the subprocess.
96        #
97        # The subprocess then gets an interposed imp.find_module(), which we
98        # hack up to find 'mach' without the .py extension, since we already
99        # know where it is (it's us!). If we're not looking for 'mach', then
100        # the original find_module will suffice.
101        #
102        # See also: http://bugs.python.org/issue19946
103        # And: https://bugzilla.mozilla.org/show_bug.cgi?id=914563
104        import inspect
105        from multiprocessing import forking
106        global orig_command_line
107
108        def fork_interpose():
109            import imp
110            import os
111            import sys
112            orig_find_module = imp.find_module
113            def my_find_module(name, dirs):
114                if name == 'mach':
115                    path = os.path.join(dirs[0], 'mach')
116                    f = open(path)
117                    return (f, path, ('', 'r', imp.PY_SOURCE))
118                return orig_find_module(name, dirs)
119
120            # Don't allow writing bytecode file for mach module.
121            orig_load_module = imp.load_module
122            def my_load_module(name, file, path, description):
123                # multiprocess.forking invokes imp.load_module manually and
124                # hard-codes the name __parents_main__ as the module name.
125                if name == '__parents_main__':
126                    old_bytecode = sys.dont_write_bytecode
127                    sys.dont_write_bytecode = True
128                    try:
129                        return orig_load_module(name, file, path, description)
130                    finally:
131                        sys.dont_write_bytecode = old_bytecode
132
133                return orig_load_module(name, file, path, description)
134
135            imp.find_module = my_find_module
136            imp.load_module = my_load_module
137            from multiprocessing.forking import main; main()
138
139        def my_get_command_line():
140            fork_code, lineno = inspect.getsourcelines(fork_interpose)
141            # Remove the first line (for 'def fork_interpose():') and the three
142            # levels of indentation (12 spaces).
143            fork_string = ''.join(x[12:] for x in fork_code[1:])
144            cmdline = orig_command_line()
145            cmdline[2] = fork_string
146            return cmdline
147        orig_command_line = forking.get_command_line
148        forking.get_command_line = my_get_command_line
149
150    main(sys.argv[1:])
151