• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2
3# Copyright (c) 2012 Google Inc. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Utility functions for Windows builds.
8
9These functions are executed via gyp-win-tool when using the ninja generator.
10"""
11
12from __future__ import print_function
13
14import os
15import re
16import shutil
17import subprocess
18import stat
19import string
20import sys
21
22BASE_DIR = os.path.dirname(os.path.abspath(__file__))
23PY3 = bytes != str
24
25# A regex matching an argument corresponding to the output filename passed to
26# link.exe.
27_LINK_EXE_OUT_ARG = re.compile("/OUT:(?P<out>.+)$", re.IGNORECASE)
28
29
30def main(args):
31    executor = WinTool()
32    exit_code = executor.Dispatch(args)
33    if exit_code is not None:
34        sys.exit(exit_code)
35
36
37class WinTool(object):
38    """This class performs all the Windows tooling steps. The methods can either
39  be executed directly, or dispatched from an argument list."""
40
41    def _UseSeparateMspdbsrv(self, env, args):
42        """Allows to use a unique instance of mspdbsrv.exe per linker instead of a
43    shared one."""
44        if len(args) < 1:
45            raise Exception("Not enough arguments")
46
47        if args[0] != "link.exe":
48            return
49
50        # Use the output filename passed to the linker to generate an endpoint name
51        # for mspdbsrv.exe.
52        endpoint_name = None
53        for arg in args:
54            m = _LINK_EXE_OUT_ARG.match(arg)
55            if m:
56                endpoint_name = re.sub(
57                    r"\W+", "", "%s_%d" % (m.group("out"), os.getpid())
58                )
59                break
60
61        if endpoint_name is None:
62            return
63
64        # Adds the appropriate environment variable. This will be read by link.exe
65        # to know which instance of mspdbsrv.exe it should connect to (if it's
66        # not set then the default endpoint is used).
67        env["_MSPDBSRV_ENDPOINT_"] = endpoint_name
68
69    def Dispatch(self, args):
70        """Dispatches a string command to a method."""
71        if len(args) < 1:
72            raise Exception("Not enough arguments")
73
74        method = "Exec%s" % self._CommandifyName(args[0])
75        return getattr(self, method)(*args[1:])
76
77    def _CommandifyName(self, name_string):
78        """Transforms a tool name like recursive-mirror to RecursiveMirror."""
79        return name_string.title().replace("-", "")
80
81    def _GetEnv(self, arch):
82        """Gets the saved environment from a file for a given architecture."""
83        # The environment is saved as an "environment block" (see CreateProcess
84        # and msvs_emulation for details). We convert to a dict here.
85        # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
86        pairs = open(arch).read()[:-2].split("\0")
87        kvs = [item.split("=", 1) for item in pairs]
88        return dict(kvs)
89
90    def ExecStamp(self, path):
91        """Simple stamp command."""
92        open(path, "w").close()
93
94    def ExecRecursiveMirror(self, source, dest):
95        """Emulation of rm -rf out && cp -af in out."""
96        if os.path.exists(dest):
97            if os.path.isdir(dest):
98
99                def _on_error(fn, path, excinfo):
100                    # The operation failed, possibly because the file is set to
101                    # read-only. If that's why, make it writable and try the op again.
102                    if not os.access(path, os.W_OK):
103                        os.chmod(path, stat.S_IWRITE)
104                    fn(path)
105
106                shutil.rmtree(dest, onerror=_on_error)
107            else:
108                if not os.access(dest, os.W_OK):
109                    # Attempt to make the file writable before deleting it.
110                    os.chmod(dest, stat.S_IWRITE)
111                os.unlink(dest)
112
113        if os.path.isdir(source):
114            shutil.copytree(source, dest)
115        else:
116            shutil.copy2(source, dest)
117
118    def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
119        """Filter diagnostic output from link that looks like:
120    '   Creating library ui.dll.lib and object ui.dll.exp'
121    This happens when there are exports from the dll or exe.
122    """
123        env = self._GetEnv(arch)
124        if use_separate_mspdbsrv == "True":
125            self._UseSeparateMspdbsrv(env, args)
126        if sys.platform == "win32":
127            args = list(args)  # *args is a tuple by default, which is read-only.
128            args[0] = args[0].replace("/", "\\")
129        # https://docs.python.org/2/library/subprocess.html:
130        # "On Unix with shell=True [...] if args is a sequence, the first item
131        # specifies the command string, and any additional items will be treated as
132        # additional arguments to the shell itself.  That is to say, Popen does the
133        # equivalent of:
134        #   Popen(['/bin/sh', '-c', args[0], args[1], ...])"
135        # For that reason, since going through the shell doesn't seem necessary on
136        # non-Windows don't do that there.
137        link = subprocess.Popen(
138            args,
139            shell=sys.platform == "win32",
140            env=env,
141            stdout=subprocess.PIPE,
142            stderr=subprocess.STDOUT,
143        )
144        out, _ = link.communicate()
145        if PY3:
146            out = out.decode("utf-8")
147        for line in out.splitlines():
148            if (
149                not line.startswith("   Creating library ")
150                and not line.startswith("Generating code")
151                and not line.startswith("Finished generating code")
152            ):
153                print(line)
154        return link.returncode
155
156    def ExecLinkWithManifests(
157        self,
158        arch,
159        embed_manifest,
160        out,
161        ldcmd,
162        resname,
163        mt,
164        rc,
165        intermediate_manifest,
166        *manifests
167    ):
168        """A wrapper for handling creating a manifest resource and then executing
169    a link command."""
170        # The 'normal' way to do manifests is to have link generate a manifest
171        # based on gathering dependencies from the object files, then merge that
172        # manifest with other manifests supplied as sources, convert the merged
173        # manifest to a resource, and then *relink*, including the compiled
174        # version of the manifest resource. This breaks incremental linking, and
175        # is generally overly complicated. Instead, we merge all the manifests
176        # provided (along with one that includes what would normally be in the
177        # linker-generated one, see msvs_emulation.py), and include that into the
178        # first and only link. We still tell link to generate a manifest, but we
179        # only use that to assert that our simpler process did not miss anything.
180        variables = {
181            "python": sys.executable,
182            "arch": arch,
183            "out": out,
184            "ldcmd": ldcmd,
185            "resname": resname,
186            "mt": mt,
187            "rc": rc,
188            "intermediate_manifest": intermediate_manifest,
189            "manifests": " ".join(manifests),
190        }
191        add_to_ld = ""
192        if manifests:
193            subprocess.check_call(
194                "%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo "
195                "-manifest %(manifests)s -out:%(out)s.manifest" % variables
196            )
197            if embed_manifest == "True":
198                subprocess.check_call(
199                    "%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest"
200                    " %(out)s.manifest.rc %(resname)s" % variables
201                )
202                subprocess.check_call(
203                    "%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s "
204                    "%(out)s.manifest.rc" % variables
205                )
206                add_to_ld = " %(out)s.manifest.res" % variables
207        subprocess.check_call(ldcmd + add_to_ld)
208
209        # Run mt.exe on the theoretically complete manifest we generated, merging
210        # it with the one the linker generated to confirm that the linker
211        # generated one does not add anything. This is strictly unnecessary for
212        # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
213        # used in a #pragma comment.
214        if manifests:
215            # Merge the intermediate one with ours to .assert.manifest, then check
216            # that .assert.manifest is identical to ours.
217            subprocess.check_call(
218                "%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo "
219                "-manifest %(out)s.manifest %(intermediate_manifest)s "
220                "-out:%(out)s.assert.manifest" % variables
221            )
222            assert_manifest = "%(out)s.assert.manifest" % variables
223            our_manifest = "%(out)s.manifest" % variables
224            # Load and normalize the manifests. mt.exe sometimes removes whitespace,
225            # and sometimes doesn't unfortunately.
226            with open(our_manifest, "r") as our_f:
227                with open(assert_manifest, "r") as assert_f:
228                    our_data = our_f.read().translate(None, string.whitespace)
229                    assert_data = assert_f.read().translate(None, string.whitespace)
230            if our_data != assert_data:
231                os.unlink(out)
232
233                def dump(filename):
234                    print(filename, file=sys.stderr)
235                    print("-----", file=sys.stderr)
236                    with open(filename, "r") as f:
237                        print(f.read(), file=sys.stderr)
238                        print("-----", file=sys.stderr)
239
240                dump(intermediate_manifest)
241                dump(our_manifest)
242                dump(assert_manifest)
243                sys.stderr.write(
244                    'Linker generated manifest "%s" added to final manifest "%s" '
245                    '(result in "%s"). '
246                    "Were /MANIFEST switches used in #pragma statements? "
247                    % (intermediate_manifest, our_manifest, assert_manifest)
248                )
249                return 1
250
251    def ExecManifestWrapper(self, arch, *args):
252        """Run manifest tool with environment set. Strip out undesirable warning
253    (some XML blocks are recognized by the OS loader, but not the manifest
254    tool)."""
255        env = self._GetEnv(arch)
256        popen = subprocess.Popen(
257            args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
258        )
259        out, _ = popen.communicate()
260        if PY3:
261            out = out.decode("utf-8")
262        for line in out.splitlines():
263            if line and "manifest authoring warning 81010002" not in line:
264                print(line)
265        return popen.returncode
266
267    def ExecManifestToRc(self, arch, *args):
268        """Creates a resource file pointing a SxS assembly manifest.
269    |args| is tuple containing path to resource file, path to manifest file
270    and resource name which can be "1" (for executables) or "2" (for DLLs)."""
271        manifest_path, resource_path, resource_name = args
272        with open(resource_path, "w") as output:
273            output.write(
274                '#include <windows.h>\n%s RT_MANIFEST "%s"'
275                % (resource_name, os.path.abspath(manifest_path).replace("\\", "/"))
276            )
277
278    def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags):
279        """Filter noisy filenames output from MIDL compile step that isn't
280    quietable via command line flags.
281    """
282        args = (
283            ["midl", "/nologo"]
284            + list(flags)
285            + [
286                "/out",
287                outdir,
288                "/tlb",
289                tlb,
290                "/h",
291                h,
292                "/dlldata",
293                dlldata,
294                "/iid",
295                iid,
296                "/proxy",
297                proxy,
298                idl,
299            ]
300        )
301        env = self._GetEnv(arch)
302        popen = subprocess.Popen(
303            args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
304        )
305        out, _ = popen.communicate()
306        if PY3:
307            out = out.decode("utf-8")
308        # Filter junk out of stdout, and write filtered versions. Output we want
309        # to filter is pairs of lines that look like this:
310        # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl
311        # objidl.idl
312        lines = out.splitlines()
313        prefixes = ("Processing ", "64 bit Processing ")
314        processing = set(os.path.basename(x) for x in lines if x.startswith(prefixes))
315        for line in lines:
316            if not line.startswith(prefixes) and line not in processing:
317                print(line)
318        return popen.returncode
319
320    def ExecAsmWrapper(self, arch, *args):
321        """Filter logo banner from invocations of asm.exe."""
322        env = self._GetEnv(arch)
323        popen = subprocess.Popen(
324            args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
325        )
326        out, _ = popen.communicate()
327        if PY3:
328            out = out.decode("utf-8")
329        for line in out.splitlines():
330            if (
331                not line.startswith("Copyright (C) Microsoft Corporation")
332                and not line.startswith("Microsoft (R) Macro Assembler")
333                and not line.startswith(" Assembling: ")
334                and line
335            ):
336                print(line)
337        return popen.returncode
338
339    def ExecRcWrapper(self, arch, *args):
340        """Filter logo banner from invocations of rc.exe. Older versions of RC
341    don't support the /nologo flag."""
342        env = self._GetEnv(arch)
343        popen = subprocess.Popen(
344            args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
345        )
346        out, _ = popen.communicate()
347        if PY3:
348            out = out.decode("utf-8")
349        for line in out.splitlines():
350            if (
351                not line.startswith("Microsoft (R) Windows (R) Resource Compiler")
352                and not line.startswith("Copyright (C) Microsoft Corporation")
353                and line
354            ):
355                print(line)
356        return popen.returncode
357
358    def ExecActionWrapper(self, arch, rspfile, *dir):
359        """Runs an action command line from a response file using the environment
360    for |arch|. If |dir| is supplied, use that as the working directory."""
361        env = self._GetEnv(arch)
362        # TODO(scottmg): This is a temporary hack to get some specific variables
363        # through to actions that are set after gyp-time. http://crbug.com/333738.
364        for k, v in os.environ.items():
365            if k not in env:
366                env[k] = v
367        args = open(rspfile).read()
368        dir = dir[0] if dir else None
369        return subprocess.call(args, shell=True, env=env, cwd=dir)
370
371    def ExecClCompile(self, project_dir, selected_files):
372        """Executed by msvs-ninja projects when the 'ClCompile' target is used to
373    build selected C/C++ files."""
374        project_dir = os.path.relpath(project_dir, BASE_DIR)
375        selected_files = selected_files.split(";")
376        ninja_targets = [
377            os.path.join(project_dir, filename) + "^^" for filename in selected_files
378        ]
379        cmd = ["ninja.exe"]
380        cmd.extend(ninja_targets)
381        return subprocess.call(cmd, shell=True, cwd=BASE_DIR)
382
383
384if __name__ == "__main__":
385    sys.exit(main(sys.argv[1:]))
386