1"""distutils.spawn
2
3Provides the 'spawn()' function, a front-end to various platform-
4specific functions for launching another program in a sub-process.
5Also provides the 'find_executable()' to search the path for a given
6executable name.
7"""
8
9import sys
10import os
11
12from distutils.errors import DistutilsPlatformError, DistutilsExecError
13from distutils.debug import DEBUG
14from distutils import log
15
16def spawn(cmd, search_path=1, verbose=0, dry_run=0):
17    """Run another program, specified as a command list 'cmd', in a new process.
18
19    'cmd' is just the argument list for the new process, ie.
20    cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
21    There is no way to run a program with a name different from that of its
22    executable.
23
24    If 'search_path' is true (the default), the system's executable
25    search path will be used to find the program; otherwise, cmd[0]
26    must be the exact path to the executable.  If 'dry_run' is true,
27    the command will not actually be run.
28
29    Raise DistutilsExecError if running the program fails in any way; just
30    return on success.
31    """
32    # cmd is documented as a list, but just in case some code passes a tuple
33    # in, protect our %-formatting code against horrible death
34    cmd = list(cmd)
35    if os.name == 'posix':
36        _spawn_posix(cmd, search_path, dry_run=dry_run)
37    elif os.name == 'nt':
38        _spawn_nt(cmd, search_path, dry_run=dry_run)
39    else:
40        raise DistutilsPlatformError(
41              "don't know how to spawn programs on platform '%s'" % os.name)
42
43def _nt_quote_args(args):
44    """Quote command-line arguments for DOS/Windows conventions.
45
46    Just wraps every argument which contains blanks in double quotes, and
47    returns a new argument list.
48    """
49    # XXX this doesn't seem very robust to me -- but if the Windows guys
50    # say it'll work, I guess I'll have to accept it.  (What if an arg
51    # contains quotes?  What other magic characters, other than spaces,
52    # have to be escaped?  Is there an escaping mechanism other than
53    # quoting?)
54    for i, arg in enumerate(args):
55        if ' ' in arg:
56            args[i] = '"%s"' % arg
57    return args
58
59def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0):
60    executable = cmd[0]
61    cmd = _nt_quote_args(cmd)
62    if search_path:
63        # either we find one or it stays the same
64        executable = find_executable(executable) or executable
65    log.info(' '.join([executable] + cmd[1:]))
66    if not dry_run:
67        # spawn for NT requires a full path to the .exe
68        try:
69            rc = os.spawnv(os.P_WAIT, executable, cmd)
70        except OSError as exc:
71            # this seems to happen when the command isn't found
72            if not DEBUG:
73                cmd = executable
74            raise DistutilsExecError(
75                  "command %r failed: %s" % (cmd, exc.args[-1]))
76        if rc != 0:
77            # and this reflects the command running but failing
78            if not DEBUG:
79                cmd = executable
80            raise DistutilsExecError(
81                  "command %r failed with exit status %d" % (cmd, rc))
82
83if sys.platform == 'darwin':
84    _cfg_target = None
85    _cfg_target_split = None
86
87def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0):
88    log.info(' '.join(cmd))
89    if dry_run:
90        return
91    executable = cmd[0]
92    exec_fn = search_path and os.execvp or os.execv
93    env = None
94    if sys.platform == 'darwin':
95        global _cfg_target, _cfg_target_split
96        if _cfg_target is None:
97            from distutils import sysconfig
98            _cfg_target = sysconfig.get_config_var(
99                                  'MACOSX_DEPLOYMENT_TARGET') or ''
100            if _cfg_target:
101                _cfg_target_split = [int(x) for x in _cfg_target.split('.')]
102        if _cfg_target:
103            # ensure that the deployment target of build process is not less
104            # than that used when the interpreter was built. This ensures
105            # extension modules are built with correct compatibility values
106            cur_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target)
107            if _cfg_target_split > [int(x) for x in cur_target.split('.')]:
108                my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: '
109                          'now "%s" but "%s" during configure'
110                                % (cur_target, _cfg_target))
111                raise DistutilsPlatformError(my_msg)
112            env = dict(os.environ,
113                       MACOSX_DEPLOYMENT_TARGET=cur_target)
114            exec_fn = search_path and os.execvpe or os.execve
115    pid = os.fork()
116    if pid == 0: # in the child
117        try:
118            if env is None:
119                exec_fn(executable, cmd)
120            else:
121                exec_fn(executable, cmd, env)
122        except OSError as e:
123            if not DEBUG:
124                cmd = executable
125            sys.stderr.write("unable to execute %r: %s\n"
126                             % (cmd, e.strerror))
127            os._exit(1)
128
129        if not DEBUG:
130            cmd = executable
131        sys.stderr.write("unable to execute %r for unknown reasons" % cmd)
132        os._exit(1)
133    else: # in the parent
134        # Loop until the child either exits or is terminated by a signal
135        # (ie. keep waiting if it's merely stopped)
136        while True:
137            try:
138                pid, status = os.waitpid(pid, 0)
139            except OSError as exc:
140                if not DEBUG:
141                    cmd = executable
142                raise DistutilsExecError(
143                      "command %r failed: %s" % (cmd, exc.args[-1]))
144            if os.WIFSIGNALED(status):
145                if not DEBUG:
146                    cmd = executable
147                raise DistutilsExecError(
148                      "command %r terminated by signal %d"
149                      % (cmd, os.WTERMSIG(status)))
150            elif os.WIFEXITED(status):
151                exit_status = os.WEXITSTATUS(status)
152                if exit_status == 0:
153                    return   # hey, it succeeded!
154                else:
155                    if not DEBUG:
156                        cmd = executable
157                    raise DistutilsExecError(
158                          "command %r failed with exit status %d"
159                          % (cmd, exit_status))
160            elif os.WIFSTOPPED(status):
161                continue
162            else:
163                if not DEBUG:
164                    cmd = executable
165                raise DistutilsExecError(
166                      "unknown error executing %r: termination status %d"
167                      % (cmd, status))
168
169def find_executable(executable, path=None):
170    """Tries to find 'executable' in the directories listed in 'path'.
171
172    A string listing directories separated by 'os.pathsep'; defaults to
173    os.environ['PATH'].  Returns the complete filename or None if not found.
174    """
175    _, ext = os.path.splitext(executable)
176    if (sys.platform == 'win32') and (ext != '.exe'):
177        executable = executable + '.exe'
178
179    if os.path.isfile(executable):
180        return executable
181
182    if path is None:
183        path = os.environ.get('PATH', None)
184        if path is None:
185            try:
186                path = os.confstr("CS_PATH")
187            except (AttributeError, ValueError):
188                # os.confstr() or CS_PATH is not available
189                path = os.defpath
190        # bpo-35755: Don't use os.defpath if the PATH environment variable is
191        # set to an empty string
192
193    # PATH='' doesn't match, whereas PATH=':' looks in the current directory
194    if not path:
195        return None
196
197    paths = path.split(os.pathsep)
198    for p in paths:
199        f = os.path.join(p, executable)
200        if os.path.isfile(f):
201            # the file exists, we have a shot at spawn working
202            return f
203    return None
204