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