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.
7 """Utility functions for Windows builds.
9 These functions are executed via gyp-win-tool when using the ninja generator.
19 BASE_DIR = os.path.dirname(os.path.abspath(__file__))
21 # A regex matching an argument corresponding to the output filename passed to
23 _LINK_EXE_OUT_ARG = re.compile('/OUT:(?P<out>.+)$', re.IGNORECASE)
27 exit_code = executor.Dispatch(args)
28 if exit_code is not None:
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."""
36 def _UseSeparateMspdbsrv(self, env, args):
37 """Allows to use a unique instance of mspdbsrv.exe per linker instead of a
40 raise Exception("Not enough arguments")
42 if args[0] != 'link.exe':
45 # Use the output filename passed to the linker to generate an endpoint name
49 m = _LINK_EXE_OUT_ARG.match(arg)
51 endpoint_name = '%s_%d' % (m.group('out'), os.getpid())
54 if endpoint_name is None:
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
62 def Dispatch(self, args):
63 """Dispatches a string command to a method."""
65 raise Exception("Not enough arguments")
67 method = "Exec%s" % self._CommandifyName(args[0])
68 return getattr(self, method)(*args[1:])
70 def _CommandifyName(self, name_string):
71 """Transforms a tool name like recursive-mirror to RecursiveMirror."""
72 return name_string.title().replace('-', '')
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]
83 def ExecStamp(self, path):
84 """Simple stamp command."""
85 open(path, 'w').close()
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):
94 if os.path.isdir(source):
95 shutil.copytree(source, dest)
97 shutil.copy2(source, dest)
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.
104 env = self._GetEnv(arch)
105 if use_separate_mspdbsrv == 'True':
106 self._UseSeparateMspdbsrv(env, args)
107 link = subprocess.Popen(args,
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 '):
116 return link.returncode
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
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.
133 'python': sys.executable,
140 'intermediate_manifest': intermediate_manifest,
141 'manifests': ' '.join(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)
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.
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:
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)
186 dump(assert_manifest)
188 'Linker generated manifest "%s" added to final manifest "%s" '
190 'Were /MANIFEST switches used in #pragma statements? ' % (
191 intermediate_manifest, our_manifest, assert_manifest))
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
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:
205 return popen.returncode
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"' % (
215 os.path.abspath(manifest_path).replace('\\', '/')))
217 def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
219 """Filter noisy filenames output from MIDL compile step that isn't
220 quietable via command line flags.
222 args = ['midl', '/nologo'] + list(flags) + [
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
238 lines = out.splitlines()
239 prefix = 'Processing '
240 processing = set(os.path.basename(x) for x in lines if x.startswith(prefix))
242 if not line.startswith(prefix) and line not in processing:
244 return popen.returncode
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':
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
261 return popen.returncode
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
275 return popen.returncode
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():
286 args = open(rspfile).read()
287 dir = dir[0] if dir else None
288 return subprocess.call(args, shell=True, env=env, cwd=dir)
290 if __name__ == '__main__':
291 sys.exit(main(sys.argv[1:]))