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