Merge remote-tracking branch 'origin/v0.10'
[platform/upstream/nodejs.git] / tools / gyp / pylib / gyp / win_tool.py
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
9 These functions are executed via gyp-win-tool when using the ninja generator.
10 """
11
12 import os
13 import re
14 import shutil
15 import subprocess
16 import string
17 import sys
18
19 BASE_DIR = os.path.dirname(os.path.abspath(__file__))
20
21 # A regex matching an argument corresponding to the output filename passed to
22 # link.exe.
23 _LINK_EXE_OUT_ARG = re.compile('/OUT:(?P<out>.+)$', re.IGNORECASE)
24
25 def main(args):
26   executor = WinTool()
27   exit_code = executor.Dispatch(args)
28   if exit_code is not None:
29     sys.exit(exit_code)
30
31
32 class WinTool(object):
33   """This class performs all the Windows tooling steps. The methods can either
34   be executed directly, or dispatched from an argument list."""
35
36   def _UseSeparateMspdbsrv(self, env, args):
37     """Allows to use a unique instance of mspdbsrv.exe per linker instead of a
38     shared one."""
39     if len(args) < 1:
40       raise Exception("Not enough arguments")
41
42     if args[0] != 'link.exe':
43       return
44
45     # Use the output filename passed to the linker to generate an endpoint name
46     # for mspdbsrv.exe.
47     endpoint_name = None
48     for arg in args:
49       m = _LINK_EXE_OUT_ARG.match(arg)
50       if m:
51         endpoint_name = '%s_%d' % (m.group('out'), os.getpid())
52         break
53
54     if endpoint_name is None:
55       return
56
57     # Adds the appropriate environment variable. This will be read by link.exe
58     # to know which instance of mspdbsrv.exe it should connect to (if it's
59     # not set then the default endpoint is used).
60     env['_MSPDBSRV_ENDPOINT_'] = endpoint_name
61
62   def Dispatch(self, args):
63     """Dispatches a string command to a method."""
64     if len(args) < 1:
65       raise Exception("Not enough arguments")
66
67     method = "Exec%s" % self._CommandifyName(args[0])
68     return getattr(self, method)(*args[1:])
69
70   def _CommandifyName(self, name_string):
71     """Transforms a tool name like recursive-mirror to RecursiveMirror."""
72     return name_string.title().replace('-', '')
73
74   def _GetEnv(self, arch):
75     """Gets the saved environment from a file for a given architecture."""
76     # The environment is saved as an "environment block" (see CreateProcess
77     # and msvs_emulation for details). We convert to a dict here.
78     # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
79     pairs = open(arch).read()[:-2].split('\0')
80     kvs = [item.split('=', 1) for item in pairs]
81     return dict(kvs)
82
83   def ExecStamp(self, path):
84     """Simple stamp command."""
85     open(path, 'w').close()
86
87   def ExecRecursiveMirror(self, source, dest):
88     """Emulation of rm -rf out && cp -af in out."""
89     if os.path.exists(dest):
90       if os.path.isdir(dest):
91         shutil.rmtree(dest)
92       else:
93         os.unlink(dest)
94     if os.path.isdir(source):
95       shutil.copytree(source, dest)
96     else:
97       shutil.copy2(source, dest)
98
99   def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
100     """Filter diagnostic output from link that looks like:
101     '   Creating library ui.dll.lib and object ui.dll.exp'
102     This happens when there are exports from the dll or exe.
103     """
104     env = self._GetEnv(arch)
105     if use_separate_mspdbsrv == 'True':
106       self._UseSeparateMspdbsrv(env, args)
107     link = subprocess.Popen(args,
108                             shell=True,
109                             env=env,
110                             stdout=subprocess.PIPE,
111                             stderr=subprocess.STDOUT)
112     out, _ = link.communicate()
113     for line in out.splitlines():
114       if not line.startswith('   Creating library '):
115         print line
116     return link.returncode
117
118   def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
119                             mt, rc, intermediate_manifest, *manifests):
120     """A wrapper for handling creating a manifest resource and then executing
121     a link command."""
122     # The 'normal' way to do manifests is to have link generate a manifest
123     # based on gathering dependencies from the object files, then merge that
124     # manifest with other manifests supplied as sources, convert the merged
125     # manifest to a resource, and then *relink*, including the compiled
126     # version of the manifest resource. This breaks incremental linking, and
127     # is generally overly complicated. Instead, we merge all the manifests
128     # provided (along with one that includes what would normally be in the
129     # linker-generated one, see msvs_emulation.py), and include that into the
130     # first and only link. We still tell link to generate a manifest, but we
131     # only use that to assert that our simpler process did not miss anything.
132     variables = {
133       'python': sys.executable,
134       'arch': arch,
135       'out': out,
136       'ldcmd': ldcmd,
137       'resname': resname,
138       'mt': mt,
139       'rc': rc,
140       'intermediate_manifest': intermediate_manifest,
141       'manifests': ' '.join(manifests),
142     }
143     add_to_ld = ''
144     if manifests:
145       subprocess.check_call(
146           '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
147           '-manifest %(manifests)s -out:%(out)s.manifest' % variables)
148       if embed_manifest == 'True':
149         subprocess.check_call(
150             '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
151           ' %(out)s.manifest.rc %(resname)s' % variables)
152         subprocess.check_call(
153             '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
154             '%(out)s.manifest.rc' % variables)
155         add_to_ld = ' %(out)s.manifest.res' % variables
156     subprocess.check_call(ldcmd + add_to_ld)
157
158     # Run mt.exe on the theoretically complete manifest we generated, merging
159     # it with the one the linker generated to confirm that the linker
160     # generated one does not add anything. This is strictly unnecessary for
161     # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
162     # used in a #pragma comment.
163     if manifests:
164       # Merge the intermediate one with ours to .assert.manifest, then check
165       # that .assert.manifest is identical to ours.
166       subprocess.check_call(
167           '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
168           '-manifest %(out)s.manifest %(intermediate_manifest)s '
169           '-out:%(out)s.assert.manifest' % variables)
170       assert_manifest = '%(out)s.assert.manifest' % variables
171       our_manifest = '%(out)s.manifest' % variables
172       # Load and normalize the manifests. mt.exe sometimes removes whitespace,
173       # and sometimes doesn't unfortunately.
174       with open(our_manifest, 'rb') as our_f:
175         with open(assert_manifest, 'rb') as assert_f:
176           our_data = our_f.read().translate(None, string.whitespace)
177           assert_data = assert_f.read().translate(None, string.whitespace)
178       if our_data != assert_data:
179         os.unlink(out)
180         def dump(filename):
181           sys.stderr.write('%s\n-----\n' % filename)
182           with open(filename, 'rb') as f:
183             sys.stderr.write(f.read() + '\n-----\n')
184         dump(intermediate_manifest)
185         dump(our_manifest)
186         dump(assert_manifest)
187         sys.stderr.write(
188             'Linker generated manifest "%s" added to final manifest "%s" '
189             '(result in "%s"). '
190             'Were /MANIFEST switches used in #pragma statements? ' % (
191               intermediate_manifest, our_manifest, assert_manifest))
192         return 1
193
194   def ExecManifestWrapper(self, arch, *args):
195     """Run manifest tool with environment set. Strip out undesirable warning
196     (some XML blocks are recognized by the OS loader, but not the manifest
197     tool)."""
198     env = self._GetEnv(arch)
199     popen = subprocess.Popen(args, shell=True, env=env,
200                              stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
201     out, _ = popen.communicate()
202     for line in out.splitlines():
203       if line and 'manifest authoring warning 81010002' not in line:
204         print line
205     return popen.returncode
206
207   def ExecManifestToRc(self, arch, *args):
208     """Creates a resource file pointing a SxS assembly manifest.
209     |args| is tuple containing path to resource file, path to manifest file
210     and resource name which can be "1" (for executables) or "2" (for DLLs)."""
211     manifest_path, resource_path, resource_name = args
212     with open(resource_path, 'wb') as output:
213       output.write('#include <windows.h>\n%s RT_MANIFEST "%s"' % (
214         resource_name,
215         os.path.abspath(manifest_path).replace('\\', '/')))
216
217   def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
218                       *flags):
219     """Filter noisy filenames output from MIDL compile step that isn't
220     quietable via command line flags.
221     """
222     args = ['midl', '/nologo'] + list(flags) + [
223         '/out', outdir,
224         '/tlb', tlb,
225         '/h', h,
226         '/dlldata', dlldata,
227         '/iid', iid,
228         '/proxy', proxy,
229         idl]
230     env = self._GetEnv(arch)
231     popen = subprocess.Popen(args, shell=True, env=env,
232                              stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
233     out, _ = popen.communicate()
234     # Filter junk out of stdout, and write filtered versions. Output we want
235     # to filter is pairs of lines that look like this:
236     # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl
237     # objidl.idl
238     lines = out.splitlines()
239     prefix = 'Processing '
240     processing = set(os.path.basename(x) for x in lines if x.startswith(prefix))
241     for line in lines:
242       if not line.startswith(prefix) and line not in processing:
243         print line
244     return popen.returncode
245
246   def ExecAsmWrapper(self, arch, *args):
247     """Filter logo banner from invocations of asm.exe."""
248     env = self._GetEnv(arch)
249     # MSVS doesn't assemble x64 asm files.
250     if arch == 'environment.x64':
251       return 0
252     popen = subprocess.Popen(args, shell=True, env=env,
253                              stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
254     out, _ = popen.communicate()
255     for line in out.splitlines():
256       if (not line.startswith('Copyright (C) Microsoft Corporation') and
257           not line.startswith('Microsoft (R) Macro Assembler') and
258           not line.startswith(' Assembling: ') and
259           line):
260         print line
261     return popen.returncode
262
263   def ExecRcWrapper(self, arch, *args):
264     """Filter logo banner from invocations of rc.exe. Older versions of RC
265     don't support the /nologo flag."""
266     env = self._GetEnv(arch)
267     popen = subprocess.Popen(args, shell=True, env=env,
268                              stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
269     out, _ = popen.communicate()
270     for line in out.splitlines():
271       if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and
272           not line.startswith('Copyright (C) Microsoft Corporation') and
273           line):
274         print line
275     return popen.returncode
276
277   def ExecActionWrapper(self, arch, rspfile, *dir):
278     """Runs an action command line from a response file using the environment
279     for |arch|. If |dir| is supplied, use that as the working directory."""
280     env = self._GetEnv(arch)
281     # TODO(scottmg): This is a temporary hack to get some specific variables
282     # through to actions that are set after gyp-time. http://crbug.com/333738.
283     for k, v in os.environ.iteritems():
284       if k not in env:
285         env[k] = v
286     args = open(rspfile).read()
287     dir = dir[0] if dir else None
288     return subprocess.call(args, shell=True, env=env, cwd=dir)
289
290 if __name__ == '__main__':
291   sys.exit(main(sys.argv[1:]))