casbin-async-django-orm-adapter 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. async_casbin_adapter/__init__.py +0 -0
  2. async_casbin_adapter/adapter.py +100 -0
  3. async_casbin_adapter/apps.py +24 -0
  4. async_casbin_adapter/enforcer.py +81 -0
  5. async_casbin_adapter/migrations/0001_initial.py +37 -0
  6. async_casbin_adapter/migrations/__init__.py +0 -0
  7. async_casbin_adapter/models.py +48 -0
  8. async_casbin_adapter/utils.py +25 -0
  9. casbin_async_django_orm_adapter-1.0.0.dist-info/METADATA +116 -0
  10. casbin_async_django_orm_adapter-1.0.0.dist-info/RECORD +74 -0
  11. casbin_async_django_orm_adapter-1.0.0.dist-info/WHEEL +5 -0
  12. casbin_async_django_orm_adapter-1.0.0.dist-info/licenses/LICENSE +201 -0
  13. casbin_async_django_orm_adapter-1.0.0.dist-info/top_level.txt +3 -0
  14. node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  15. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +365 -0
  16. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  17. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1272 -0
  18. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  19. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  20. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +152 -0
  21. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +270 -0
  22. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  23. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +704 -0
  24. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py +709 -0
  25. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +173 -0
  26. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +169 -0
  27. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +113 -0
  28. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  29. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  30. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +805 -0
  31. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1172 -0
  32. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1319 -0
  33. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +128 -0
  34. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +104 -0
  35. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +462 -0
  36. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  37. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +56 -0
  38. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2745 -0
  39. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3976 -0
  40. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  41. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2965 -0
  42. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +67 -0
  43. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1391 -0
  44. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +26 -0
  45. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py +3112 -0
  46. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +99 -0
  47. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +767 -0
  48. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1260 -0
  49. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  50. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  51. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +373 -0
  52. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  53. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py +54 -0
  54. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +303 -0
  55. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3196 -0
  56. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  57. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/__init__.py +15 -0
  58. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py +108 -0
  59. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_manylinux.py +252 -0
  60. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_musllinux.py +83 -0
  61. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_parser.py +359 -0
  62. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_structures.py +61 -0
  63. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_tokenizer.py +192 -0
  64. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/markers.py +252 -0
  65. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/metadata.py +825 -0
  66. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/py.typed +0 -0
  67. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/requirements.py +90 -0
  68. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/specifiers.py +1030 -0
  69. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/tags.py +553 -0
  70. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/utils.py +172 -0
  71. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/version.py +563 -0
  72. node_modules/npm/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  73. node_modules/semantic-release-pypi/dist/py/set_version.py +32 -0
  74. node_modules/semantic-release-pypi/dist/py/verify_setup.py +24 -0
@@ -0,0 +1,1260 @@
1
+ # Copyright (c) 2012 Google Inc. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """
6
+ This module helps emulate Visual Studio 2008 behavior on top of other
7
+ build systems, primarily ninja.
8
+ """
9
+
10
+ import os
11
+ import re
12
+ import subprocess
13
+ import sys
14
+ from collections import namedtuple
15
+
16
+ import gyp.MSVSUtil
17
+ import gyp.MSVSVersion
18
+ from gyp.common import OrderedSet
19
+
20
+ windows_quoter_regex = re.compile(r'(\\*)"')
21
+
22
+
23
+ def QuoteForRspFile(arg, quote_cmd=True):
24
+ """Quote a command line argument so that it appears as one argument when
25
+ processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for
26
+ Windows programs)."""
27
+ # See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment
28
+ # threads. This is actually the quoting rules for CommandLineToArgvW, not
29
+ # for the shell, because the shell doesn't do anything in Windows. This
30
+ # works more or less because most programs (including the compiler, etc.)
31
+ # use that function to handle command line arguments.
32
+
33
+ # Use a heuristic to try to find args that are paths, and normalize them
34
+ if arg.find("/") > 0 or arg.count("/") > 1:
35
+ arg = os.path.normpath(arg)
36
+
37
+ # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes
38
+ # preceding it, and results in n backslashes + the quote. So we substitute
39
+ # in 2* what we match, +1 more, plus the quote.
40
+ if quote_cmd:
41
+ arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg)
42
+
43
+ # %'s also need to be doubled otherwise they're interpreted as batch
44
+ # positional arguments. Also make sure to escape the % so that they're
45
+ # passed literally through escaping so they can be singled to just the
46
+ # original %. Otherwise, trying to pass the literal representation that
47
+ # looks like an environment variable to the shell (e.g. %PATH%) would fail.
48
+ arg = arg.replace("%", "%%")
49
+
50
+ # These commands are used in rsp files, so no escaping for the shell (via ^)
51
+ # is necessary.
52
+
53
+ # As a workaround for programs that don't use CommandLineToArgvW, gyp
54
+ # supports msvs_quote_cmd=0, which simply disables all quoting.
55
+ if quote_cmd:
56
+ # Finally, wrap the whole thing in quotes so that the above quote rule
57
+ # applies and whitespace isn't a word break.
58
+ return f'"{arg}"'
59
+
60
+ return arg
61
+
62
+
63
+ def EncodeRspFileList(args, quote_cmd):
64
+ """Process a list of arguments using QuoteCmdExeArgument."""
65
+ # Note that the first argument is assumed to be the command. Don't add
66
+ # quotes around it because then built-ins like 'echo', etc. won't work.
67
+ # Take care to normpath only the path in the case of 'call ../x.bat' because
68
+ # otherwise the whole thing is incorrectly interpreted as a path and not
69
+ # normalized correctly.
70
+ if not args:
71
+ return ""
72
+ if args[0].startswith("call "):
73
+ call, program = args[0].split(" ", 1)
74
+ program = call + " " + os.path.normpath(program)
75
+ else:
76
+ program = os.path.normpath(args[0])
77
+ return (program + " "
78
+ + " ".join(QuoteForRspFile(arg, quote_cmd) for arg in args[1:]))
79
+
80
+
81
+ def _GenericRetrieve(root, default, path):
82
+ """Given a list of dictionary keys |path| and a tree of dicts |root|, find
83
+ value at path, or return |default| if any of the path doesn't exist."""
84
+ if not root:
85
+ return default
86
+ if not path:
87
+ return root
88
+ return _GenericRetrieve(root.get(path[0]), default, path[1:])
89
+
90
+
91
+ def _AddPrefix(element, prefix):
92
+ """Add |prefix| to |element| or each subelement if element is iterable."""
93
+ if element is None:
94
+ return element
95
+ # Note, not Iterable because we don't want to handle strings like that.
96
+ if isinstance(element, (list, tuple)):
97
+ return [prefix + e for e in element]
98
+ else:
99
+ return prefix + element
100
+
101
+
102
+ def _DoRemapping(element, map):
103
+ """If |element| then remap it through |map|. If |element| is iterable then
104
+ each item will be remapped. Any elements not found will be removed."""
105
+ if map is not None and element is not None:
106
+ if not callable(map):
107
+ map = map.get # Assume it's a dict, otherwise a callable to do the remap.
108
+ if isinstance(element, (list, tuple)):
109
+ element = filter(None, [map(elem) for elem in element])
110
+ else:
111
+ element = map(element)
112
+ return element
113
+
114
+
115
+ def _AppendOrReturn(append, element):
116
+ """If |append| is None, simply return |element|. If |append| is not None,
117
+ then add |element| to it, adding each item in |element| if it's a list or
118
+ tuple."""
119
+ if append is not None and element is not None:
120
+ if isinstance(element, (list, tuple)):
121
+ append.extend(element)
122
+ else:
123
+ append.append(element)
124
+ else:
125
+ return element
126
+
127
+
128
+ def _FindDirectXInstallation():
129
+ """Try to find an installation location for the DirectX SDK. Check for the
130
+ standard environment variable, and if that doesn't exist, try to find
131
+ via the registry. May return None if not found in either location."""
132
+ # Return previously calculated value, if there is one
133
+ if hasattr(_FindDirectXInstallation, "dxsdk_dir"):
134
+ return _FindDirectXInstallation.dxsdk_dir
135
+
136
+ dxsdk_dir = os.environ.get("DXSDK_DIR")
137
+ if not dxsdk_dir:
138
+ # Setup params to pass to and attempt to launch reg.exe.
139
+ cmd = ["reg.exe", "query", r"HKLM\Software\Microsoft\DirectX", "/s"]
140
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
141
+ stdout = p.communicate()[0].decode("utf-8")
142
+ for line in stdout.splitlines():
143
+ if "InstallPath" in line:
144
+ dxsdk_dir = line.split(" ")[3] + "\\"
145
+
146
+ # Cache return value
147
+ _FindDirectXInstallation.dxsdk_dir = dxsdk_dir
148
+ return dxsdk_dir
149
+
150
+
151
+ def GetGlobalVSMacroEnv(vs_version):
152
+ """Get a dict of variables mapping internal VS macro names to their gyp
153
+ equivalents. Returns all variables that are independent of the target."""
154
+ env = {}
155
+ # '$(VSInstallDir)' and '$(VCInstallDir)' are available when and only when
156
+ # Visual Studio is actually installed.
157
+ if vs_version.Path():
158
+ env["$(VSInstallDir)"] = vs_version.Path()
159
+ env["$(VCInstallDir)"] = os.path.join(vs_version.Path(), "VC") + "\\"
160
+ # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be
161
+ # set. This happens when the SDK is sync'd via src-internal, rather than
162
+ # by typical end-user installation of the SDK. If it's not set, we don't
163
+ # want to leave the unexpanded variable in the path, so simply strip it.
164
+ dxsdk_dir = _FindDirectXInstallation()
165
+ env["$(DXSDK_DIR)"] = dxsdk_dir if dxsdk_dir else ""
166
+ # Try to find an installation location for the Windows DDK by checking
167
+ # the WDK_DIR environment variable, may be None.
168
+ env["$(WDK_DIR)"] = os.environ.get("WDK_DIR", "")
169
+ return env
170
+
171
+
172
+ def ExtractSharedMSVSSystemIncludes(configs, generator_flags):
173
+ """Finds msvs_system_include_dirs that are common to all targets, removes
174
+ them from all targets, and returns an OrderedSet containing them."""
175
+ all_system_includes = OrderedSet(configs[0].get("msvs_system_include_dirs", []))
176
+ for config in configs[1:]:
177
+ system_includes = config.get("msvs_system_include_dirs", [])
178
+ all_system_includes = all_system_includes & OrderedSet(system_includes)
179
+ if not all_system_includes:
180
+ return None
181
+ # Expand macros in all_system_includes.
182
+ env = GetGlobalVSMacroEnv(GetVSVersion(generator_flags))
183
+ expanded_system_includes = OrderedSet(
184
+ [ExpandMacros(include, env) for include in all_system_includes]
185
+ )
186
+ if any("$" in include for include in expanded_system_includes):
187
+ # Some path relies on target-specific variables, bail.
188
+ return None
189
+
190
+ # Remove system includes shared by all targets from the targets.
191
+ for config in configs:
192
+ includes = config.get("msvs_system_include_dirs", [])
193
+ if includes: # Don't insert a msvs_system_include_dirs key if not needed.
194
+ # This must check the unexpanded includes list:
195
+ new_includes = [i for i in includes if i not in all_system_includes]
196
+ config["msvs_system_include_dirs"] = new_includes
197
+ return expanded_system_includes
198
+
199
+
200
+ class MsvsSettings:
201
+ """A class that understands the gyp 'msvs_...' values (especially the
202
+ msvs_settings field). They largely correpond to the VS2008 IDE DOM. This
203
+ class helps map those settings to command line options."""
204
+
205
+ def __init__(self, spec, generator_flags):
206
+ self.spec = spec
207
+ self.vs_version = GetVSVersion(generator_flags)
208
+
209
+ supported_fields = [
210
+ ("msvs_configuration_attributes", dict),
211
+ ("msvs_settings", dict),
212
+ ("msvs_system_include_dirs", list),
213
+ ("msvs_disabled_warnings", list),
214
+ ("msvs_precompiled_header", str),
215
+ ("msvs_precompiled_source", str),
216
+ ("msvs_configuration_platform", str),
217
+ ("msvs_target_platform", str),
218
+ ]
219
+ configs = spec["configurations"]
220
+ for field, default in supported_fields:
221
+ setattr(self, field, {})
222
+ for configname, config in configs.items():
223
+ getattr(self, field)[configname] = config.get(field, default())
224
+
225
+ self.msvs_cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."])
226
+
227
+ unsupported_fields = [
228
+ "msvs_prebuild",
229
+ "msvs_postbuild",
230
+ ]
231
+ unsupported = []
232
+ for field in unsupported_fields:
233
+ for config in configs.values():
234
+ if field in config:
235
+ unsupported += [
236
+ "{} not supported (target {}).".format(
237
+ field, spec["target_name"]
238
+ )
239
+ ]
240
+ if unsupported:
241
+ raise Exception("\n".join(unsupported))
242
+
243
+ def GetExtension(self):
244
+ """Returns the extension for the target, with no leading dot.
245
+
246
+ Uses 'product_extension' if specified, otherwise uses MSVS defaults based on
247
+ the target type.
248
+ """
249
+ ext = self.spec.get("product_extension", None)
250
+ if ext:
251
+ return ext
252
+ return gyp.MSVSUtil.TARGET_TYPE_EXT.get(self.spec["type"], "")
253
+
254
+ def GetVSMacroEnv(self, base_to_build=None, config=None):
255
+ """Get a dict of variables mapping internal VS macro names to their gyp
256
+ equivalents."""
257
+ target_arch = self.GetArch(config)
258
+ target_platform = "Win32" if target_arch == "x86" else target_arch
259
+ target_name = self.spec.get("product_prefix", "") + self.spec.get(
260
+ "product_name", self.spec["target_name"]
261
+ )
262
+ target_dir = base_to_build + "\\" if base_to_build else ""
263
+ target_ext = "." + self.GetExtension()
264
+ target_file_name = target_name + target_ext
265
+
266
+ replacements = {
267
+ "$(InputName)": "${root}",
268
+ "$(InputPath)": "${source}",
269
+ "$(IntDir)": "$!INTERMEDIATE_DIR",
270
+ "$(OutDir)\\": target_dir,
271
+ "$(PlatformName)": target_platform,
272
+ "$(ProjectDir)\\": "",
273
+ "$(ProjectName)": self.spec["target_name"],
274
+ "$(TargetDir)\\": target_dir,
275
+ "$(TargetExt)": target_ext,
276
+ "$(TargetFileName)": target_file_name,
277
+ "$(TargetName)": target_name,
278
+ "$(TargetPath)": os.path.join(target_dir, target_file_name),
279
+ }
280
+ replacements.update(GetGlobalVSMacroEnv(self.vs_version))
281
+ return replacements
282
+
283
+ def ConvertVSMacros(self, s, base_to_build=None, config=None):
284
+ """Convert from VS macro names to something equivalent."""
285
+ env = self.GetVSMacroEnv(base_to_build, config=config)
286
+ return ExpandMacros(s, env)
287
+
288
+ def AdjustLibraries(self, libraries):
289
+ """Strip -l from library if it's specified with that."""
290
+ libs = [lib[2:] if lib.startswith("-l") else lib for lib in libraries]
291
+ return [
292
+ lib + ".lib"
293
+ if not lib.lower().endswith(".lib") and not lib.lower().endswith(".obj")
294
+ else lib
295
+ for lib in libs
296
+ ]
297
+
298
+ def _GetAndMunge(self, field, path, default, prefix, append, map):
299
+ """Retrieve a value from |field| at |path| or return |default|. If
300
+ |append| is specified, and the item is found, it will be appended to that
301
+ object instead of returned. If |map| is specified, results will be
302
+ remapped through |map| before being returned or appended."""
303
+ result = _GenericRetrieve(field, default, path)
304
+ result = _DoRemapping(result, map)
305
+ result = _AddPrefix(result, prefix)
306
+ return _AppendOrReturn(append, result)
307
+
308
+ class _GetWrapper:
309
+ def __init__(self, parent, field, base_path, append=None):
310
+ self.parent = parent
311
+ self.field = field
312
+ self.base_path = [base_path]
313
+ self.append = append
314
+
315
+ def __call__(self, name, map=None, prefix="", default=None):
316
+ return self.parent._GetAndMunge(
317
+ self.field,
318
+ self.base_path + [name],
319
+ default=default,
320
+ prefix=prefix,
321
+ append=self.append,
322
+ map=map,
323
+ )
324
+
325
+ def GetArch(self, config):
326
+ """Get architecture based on msvs_configuration_platform and
327
+ msvs_target_platform. Returns either 'x86' or 'x64'."""
328
+ configuration_platform = self.msvs_configuration_platform.get(config, "")
329
+ platform = self.msvs_target_platform.get(config, "")
330
+ if not platform: # If no specific override, use the configuration's.
331
+ platform = configuration_platform
332
+ # Map from platform to architecture.
333
+ return {"Win32": "x86", "x64": "x64", "ARM64": "arm64"}.get(platform, "x86")
334
+
335
+ def _TargetConfig(self, config):
336
+ """Returns the target-specific configuration."""
337
+ # There's two levels of architecture/platform specification in VS. The
338
+ # first level is globally for the configuration (this is what we consider
339
+ # "the" config at the gyp level, which will be something like 'Debug' or
340
+ # 'Release'), VS2015 and later only use this level
341
+ if int(self.vs_version.short_name) >= 2015:
342
+ return config
343
+ # and a second target-specific configuration, which is an
344
+ # override for the global one. |config| is remapped here to take into
345
+ # account the local target-specific overrides to the global configuration.
346
+ arch = self.GetArch(config)
347
+ if arch == "x64" and not config.endswith("_x64"):
348
+ config += "_x64"
349
+ if arch == "x86" and config.endswith("_x64"):
350
+ config = config.rsplit("_", 1)[0]
351
+ return config
352
+
353
+ def _Setting(self, path, config, default=None, prefix="", append=None, map=None):
354
+ """_GetAndMunge for msvs_settings."""
355
+ return self._GetAndMunge(
356
+ self.msvs_settings[config], path, default, prefix, append, map
357
+ )
358
+
359
+ def _ConfigAttrib(
360
+ self, path, config, default=None, prefix="", append=None, map=None
361
+ ):
362
+ """_GetAndMunge for msvs_configuration_attributes."""
363
+ return self._GetAndMunge(
364
+ self.msvs_configuration_attributes[config],
365
+ path,
366
+ default,
367
+ prefix,
368
+ append,
369
+ map,
370
+ )
371
+
372
+ def AdjustIncludeDirs(self, include_dirs, config):
373
+ """Updates include_dirs to expand VS specific paths, and adds the system
374
+ include dirs used for platform SDK and similar."""
375
+ config = self._TargetConfig(config)
376
+ includes = include_dirs + self.msvs_system_include_dirs[config]
377
+ includes.extend(
378
+ self._Setting(
379
+ ("VCCLCompilerTool", "AdditionalIncludeDirectories"), config, default=[]
380
+ )
381
+ )
382
+ return [self.ConvertVSMacros(p, config=config) for p in includes]
383
+
384
+ def AdjustMidlIncludeDirs(self, midl_include_dirs, config):
385
+ """Updates midl_include_dirs to expand VS specific paths, and adds the
386
+ system include dirs used for platform SDK and similar."""
387
+ config = self._TargetConfig(config)
388
+ includes = midl_include_dirs + self.msvs_system_include_dirs[config]
389
+ includes.extend(
390
+ self._Setting(
391
+ ("VCMIDLTool", "AdditionalIncludeDirectories"), config, default=[]
392
+ )
393
+ )
394
+ return [self.ConvertVSMacros(p, config=config) for p in includes]
395
+
396
+ def GetComputedDefines(self, config):
397
+ """Returns the set of defines that are injected to the defines list based
398
+ on other VS settings."""
399
+ config = self._TargetConfig(config)
400
+ defines = []
401
+ if self._ConfigAttrib(["CharacterSet"], config) == "1":
402
+ defines.extend(("_UNICODE", "UNICODE"))
403
+ if self._ConfigAttrib(["CharacterSet"], config) == "2":
404
+ defines.append("_MBCS")
405
+ defines.extend(
406
+ self._Setting(
407
+ ("VCCLCompilerTool", "PreprocessorDefinitions"), config, default=[]
408
+ )
409
+ )
410
+ return defines
411
+
412
+ def GetCompilerPdbName(self, config, expand_special):
413
+ """Get the pdb file name that should be used for compiler invocations, or
414
+ None if there's no explicit name specified."""
415
+ config = self._TargetConfig(config)
416
+ pdbname = self._Setting(("VCCLCompilerTool", "ProgramDataBaseFileName"), config)
417
+ if pdbname:
418
+ pdbname = expand_special(self.ConvertVSMacros(pdbname))
419
+ return pdbname
420
+
421
+ def GetMapFileName(self, config, expand_special):
422
+ """Gets the explicitly overridden map file name for a target or returns None
423
+ if it's not set."""
424
+ config = self._TargetConfig(config)
425
+ map_file = self._Setting(("VCLinkerTool", "MapFileName"), config)
426
+ if map_file:
427
+ map_file = expand_special(self.ConvertVSMacros(map_file, config=config))
428
+ return map_file
429
+
430
+ def GetOutputName(self, config, expand_special):
431
+ """Gets the explicitly overridden output name for a target or returns None
432
+ if it's not overridden."""
433
+ config = self._TargetConfig(config)
434
+ type = self.spec["type"]
435
+ root = "VCLibrarianTool" if type == "static_library" else "VCLinkerTool"
436
+ # TODO(scottmg): Handle OutputDirectory without OutputFile.
437
+ output_file = self._Setting((root, "OutputFile"), config)
438
+ if output_file:
439
+ output_file = expand_special(
440
+ self.ConvertVSMacros(output_file, config=config)
441
+ )
442
+ return output_file
443
+
444
+ def GetPDBName(self, config, expand_special, default):
445
+ """Gets the explicitly overridden pdb name for a target or returns
446
+ default if it's not overridden, or if no pdb will be generated."""
447
+ config = self._TargetConfig(config)
448
+ output_file = self._Setting(("VCLinkerTool", "ProgramDatabaseFile"), config)
449
+ generate_debug_info = self._Setting(
450
+ ("VCLinkerTool", "GenerateDebugInformation"), config
451
+ )
452
+ if generate_debug_info == "true":
453
+ if output_file:
454
+ return expand_special(self.ConvertVSMacros(output_file, config=config))
455
+ else:
456
+ return default
457
+ else:
458
+ return None
459
+
460
+ def GetNoImportLibrary(self, config):
461
+ """If NoImportLibrary: true, ninja will not expect the output to include
462
+ an import library."""
463
+ config = self._TargetConfig(config)
464
+ noimplib = self._Setting(("NoImportLibrary",), config)
465
+ return noimplib == "true"
466
+
467
+ def GetAsmflags(self, config):
468
+ """Returns the flags that need to be added to ml invocations."""
469
+ config = self._TargetConfig(config)
470
+ asmflags = []
471
+ safeseh = self._Setting(("MASM", "UseSafeExceptionHandlers"), config)
472
+ if safeseh == "true":
473
+ asmflags.append("/safeseh")
474
+ return asmflags
475
+
476
+ def GetCflags(self, config):
477
+ """Returns the flags that need to be added to .c and .cc compilations."""
478
+ config = self._TargetConfig(config)
479
+ cflags = []
480
+ cflags.extend(["/wd" + w for w in self.msvs_disabled_warnings[config]])
481
+ cl = self._GetWrapper(
482
+ self, self.msvs_settings[config], "VCCLCompilerTool", append=cflags
483
+ )
484
+ cl(
485
+ "Optimization",
486
+ map={"0": "d", "1": "1", "2": "2", "3": "x"},
487
+ prefix="/O",
488
+ default="2",
489
+ )
490
+ cl("InlineFunctionExpansion", prefix="/Ob")
491
+ cl("DisableSpecificWarnings", prefix="/wd")
492
+ cl("StringPooling", map={"true": "/GF"})
493
+ cl("EnableFiberSafeOptimizations", map={"true": "/GT"})
494
+ cl("OmitFramePointers", map={"false": "-", "true": ""}, prefix="/Oy")
495
+ cl("EnableIntrinsicFunctions", map={"false": "-", "true": ""}, prefix="/Oi")
496
+ cl("FavorSizeOrSpeed", map={"1": "t", "2": "s"}, prefix="/O")
497
+ cl(
498
+ "FloatingPointModel",
499
+ map={"0": "precise", "1": "strict", "2": "fast"},
500
+ prefix="/fp:",
501
+ default="0",
502
+ )
503
+ cl("CompileAsManaged", map={"false": "", "true": "/clr"})
504
+ cl("WholeProgramOptimization", map={"true": "/GL"})
505
+ cl("WarningLevel", prefix="/W")
506
+ cl("WarnAsError", map={"true": "/WX"})
507
+ cl(
508
+ "CallingConvention",
509
+ map={"0": "d", "1": "r", "2": "z", "3": "v"},
510
+ prefix="/G",
511
+ )
512
+ cl("DebugInformationFormat", map={"1": "7", "3": "i", "4": "I"}, prefix="/Z")
513
+ cl("RuntimeTypeInfo", map={"true": "/GR", "false": "/GR-"})
514
+ cl("EnableFunctionLevelLinking", map={"true": "/Gy", "false": "/Gy-"})
515
+ cl("MinimalRebuild", map={"true": "/Gm"})
516
+ cl("BufferSecurityCheck", map={"true": "/GS", "false": "/GS-"})
517
+ cl("BasicRuntimeChecks", map={"1": "s", "2": "u", "3": "1"}, prefix="/RTC")
518
+ cl(
519
+ "RuntimeLibrary",
520
+ map={"0": "T", "1": "Td", "2": "D", "3": "Dd"},
521
+ prefix="/M",
522
+ )
523
+ cl("ExceptionHandling", map={"1": "sc", "2": "a"}, prefix="/EH")
524
+ cl("DefaultCharIsUnsigned", map={"true": "/J"})
525
+ cl(
526
+ "TreatWChar_tAsBuiltInType",
527
+ map={"false": "-", "true": ""},
528
+ prefix="/Zc:wchar_t",
529
+ )
530
+ cl("EnablePREfast", map={"true": "/analyze"})
531
+ cl("AdditionalOptions", prefix="")
532
+ cl(
533
+ "EnableEnhancedInstructionSet",
534
+ map={"1": "SSE", "2": "SSE2", "3": "AVX", "4": "IA32", "5": "AVX2"},
535
+ prefix="/arch:",
536
+ )
537
+ cflags.extend(
538
+ [
539
+ "/FI" + f
540
+ for f in self._Setting(
541
+ ("VCCLCompilerTool", "ForcedIncludeFiles"), config, default=[]
542
+ )
543
+ ]
544
+ )
545
+ if float(self.vs_version.project_version) >= 12.0:
546
+ # New flag introduced in VS2013 (project version 12.0) Forces writes to
547
+ # the program database (PDB) to be serialized through MSPDBSRV.EXE.
548
+ # https://msdn.microsoft.com/en-us/library/dn502518.aspx
549
+ cflags.append("/FS")
550
+ # ninja handles parallelism by itself, don't have the compiler do it too.
551
+ cflags = [x for x in cflags if not x.startswith("/MP")]
552
+ return cflags
553
+
554
+ def _GetPchFlags(self, config, extension):
555
+ """Get the flags to be added to the cflags for precompiled header support."""
556
+ config = self._TargetConfig(config)
557
+ # The PCH is only built once by a particular source file. Usage of PCH must
558
+ # only be for the same language (i.e. C vs. C++), so only include the pch
559
+ # flags when the language matches.
560
+ if self.msvs_precompiled_header[config]:
561
+ source_ext = os.path.splitext(self.msvs_precompiled_source[config])[1]
562
+ if _LanguageMatchesForPch(source_ext, extension):
563
+ pch = self.msvs_precompiled_header[config]
564
+ pchbase = os.path.split(pch)[1]
565
+ return ["/Yu" + pch, "/FI" + pch, "/Fp${pchprefix}." + pchbase + ".pch"]
566
+ return []
567
+
568
+ def GetCflagsC(self, config):
569
+ """Returns the flags that need to be added to .c compilations."""
570
+ config = self._TargetConfig(config)
571
+ return self._GetPchFlags(config, ".c")
572
+
573
+ def GetCflagsCC(self, config):
574
+ """Returns the flags that need to be added to .cc compilations."""
575
+ config = self._TargetConfig(config)
576
+ return ["/TP"] + self._GetPchFlags(config, ".cc")
577
+
578
+ def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path):
579
+ """Get and normalize the list of paths in AdditionalLibraryDirectories
580
+ setting."""
581
+ config = self._TargetConfig(config)
582
+ libpaths = self._Setting(
583
+ (root, "AdditionalLibraryDirectories"), config, default=[]
584
+ )
585
+ libpaths = [
586
+ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(p, config=config)))
587
+ for p in libpaths
588
+ ]
589
+ return ['/LIBPATH:"' + p + '"' for p in libpaths]
590
+
591
+ def GetLibFlags(self, config, gyp_to_build_path):
592
+ """Returns the flags that need to be added to lib commands."""
593
+ config = self._TargetConfig(config)
594
+ libflags = []
595
+ lib = self._GetWrapper(
596
+ self, self.msvs_settings[config], "VCLibrarianTool", append=libflags
597
+ )
598
+ libflags.extend(
599
+ self._GetAdditionalLibraryDirectories(
600
+ "VCLibrarianTool", config, gyp_to_build_path
601
+ )
602
+ )
603
+ lib("LinkTimeCodeGeneration", map={"true": "/LTCG"})
604
+ lib(
605
+ "TargetMachine",
606
+ map={"1": "X86", "17": "X64", "3": "ARM"},
607
+ prefix="/MACHINE:",
608
+ )
609
+ lib("AdditionalOptions")
610
+ return libflags
611
+
612
+ def GetDefFile(self, gyp_to_build_path):
613
+ """Returns the .def file from sources, if any. Otherwise returns None."""
614
+ spec = self.spec
615
+ if spec["type"] in ("shared_library", "loadable_module", "executable"):
616
+ def_files = [
617
+ s for s in spec.get("sources", []) if s.lower().endswith(".def")
618
+ ]
619
+ if len(def_files) == 1:
620
+ return gyp_to_build_path(def_files[0])
621
+ elif len(def_files) > 1:
622
+ raise Exception("Multiple .def files")
623
+ return None
624
+
625
+ def _GetDefFileAsLdflags(self, ldflags, gyp_to_build_path):
626
+ """.def files get implicitly converted to a ModuleDefinitionFile for the
627
+ linker in the VS generator. Emulate that behaviour here."""
628
+ def_file = self.GetDefFile(gyp_to_build_path)
629
+ if def_file:
630
+ ldflags.append('/DEF:"%s"' % def_file)
631
+
632
+ def GetPGDName(self, config, expand_special):
633
+ """Gets the explicitly overridden pgd name for a target or returns None
634
+ if it's not overridden."""
635
+ config = self._TargetConfig(config)
636
+ output_file = self._Setting(("VCLinkerTool", "ProfileGuidedDatabase"), config)
637
+ if output_file:
638
+ output_file = expand_special(
639
+ self.ConvertVSMacros(output_file, config=config)
640
+ )
641
+ return output_file
642
+
643
+ def GetLdflags(
644
+ self,
645
+ config,
646
+ gyp_to_build_path,
647
+ expand_special,
648
+ manifest_base_name,
649
+ output_name,
650
+ is_executable,
651
+ build_dir,
652
+ ):
653
+ """Returns the flags that need to be added to link commands, and the
654
+ manifest files."""
655
+ config = self._TargetConfig(config)
656
+ ldflags = []
657
+ ld = self._GetWrapper(
658
+ self, self.msvs_settings[config], "VCLinkerTool", append=ldflags
659
+ )
660
+ self._GetDefFileAsLdflags(ldflags, gyp_to_build_path)
661
+ ld("GenerateDebugInformation", map={"true": "/DEBUG"})
662
+ # TODO: These 'map' values come from machineTypeOption enum,
663
+ # and does not have an official value for ARM64 in VS2017 (yet).
664
+ # It needs to verify the ARM64 value when machineTypeOption is updated.
665
+ ld(
666
+ "TargetMachine",
667
+ map={"1": "X86", "17": "X64", "3": "ARM", "18": "ARM64"},
668
+ prefix="/MACHINE:",
669
+ )
670
+ ldflags.extend(
671
+ self._GetAdditionalLibraryDirectories(
672
+ "VCLinkerTool", config, gyp_to_build_path
673
+ )
674
+ )
675
+ ld("DelayLoadDLLs", prefix="/DELAYLOAD:")
676
+ ld("TreatLinkerWarningAsErrors", prefix="/WX", map={"true": "", "false": ":NO"})
677
+ out = self.GetOutputName(config, expand_special)
678
+ if out:
679
+ ldflags.append("/OUT:" + out)
680
+ pdb = self.GetPDBName(config, expand_special, output_name + ".pdb")
681
+ if pdb:
682
+ ldflags.append("/PDB:" + pdb)
683
+ pgd = self.GetPGDName(config, expand_special)
684
+ if pgd:
685
+ ldflags.append("/PGD:" + pgd)
686
+ map_file = self.GetMapFileName(config, expand_special)
687
+ ld("GenerateMapFile", map={"true": "/MAP:" + map_file if map_file else "/MAP"})
688
+ ld("MapExports", map={"true": "/MAPINFO:EXPORTS"})
689
+ ld("AdditionalOptions", prefix="")
690
+
691
+ minimum_required_version = self._Setting(
692
+ ("VCLinkerTool", "MinimumRequiredVersion"), config, default=""
693
+ )
694
+ if minimum_required_version:
695
+ minimum_required_version = "," + minimum_required_version
696
+ ld(
697
+ "SubSystem",
698
+ map={
699
+ "1": "CONSOLE%s" % minimum_required_version,
700
+ "2": "WINDOWS%s" % minimum_required_version,
701
+ },
702
+ prefix="/SUBSYSTEM:",
703
+ )
704
+
705
+ stack_reserve_size = self._Setting(
706
+ ("VCLinkerTool", "StackReserveSize"), config, default=""
707
+ )
708
+ if stack_reserve_size:
709
+ stack_commit_size = self._Setting(
710
+ ("VCLinkerTool", "StackCommitSize"), config, default=""
711
+ )
712
+ if stack_commit_size:
713
+ stack_commit_size = "," + stack_commit_size
714
+ ldflags.append(f"/STACK:{stack_reserve_size}{stack_commit_size}")
715
+
716
+ ld("TerminalServerAware", map={"1": ":NO", "2": ""}, prefix="/TSAWARE")
717
+ ld("LinkIncremental", map={"1": ":NO", "2": ""}, prefix="/INCREMENTAL")
718
+ ld("BaseAddress", prefix="/BASE:")
719
+ ld("FixedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/FIXED")
720
+ ld("RandomizedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/DYNAMICBASE")
721
+ ld("DataExecutionPrevention", map={"1": ":NO", "2": ""}, prefix="/NXCOMPAT")
722
+ ld("OptimizeReferences", map={"1": "NOREF", "2": "REF"}, prefix="/OPT:")
723
+ ld("ForceSymbolReferences", prefix="/INCLUDE:")
724
+ ld("EnableCOMDATFolding", map={"1": "NOICF", "2": "ICF"}, prefix="/OPT:")
725
+ ld(
726
+ "LinkTimeCodeGeneration",
727
+ map={"1": "", "2": ":PGINSTRUMENT", "3": ":PGOPTIMIZE", "4": ":PGUPDATE"},
728
+ prefix="/LTCG",
729
+ )
730
+ ld("IgnoreDefaultLibraryNames", prefix="/NODEFAULTLIB:")
731
+ ld("ResourceOnlyDLL", map={"true": "/NOENTRY"})
732
+ ld("EntryPointSymbol", prefix="/ENTRY:")
733
+ ld("Profile", map={"true": "/PROFILE"})
734
+ ld("LargeAddressAware", map={"1": ":NO", "2": ""}, prefix="/LARGEADDRESSAWARE")
735
+ # TODO(scottmg): This should sort of be somewhere else (not really a flag).
736
+ ld("AdditionalDependencies", prefix="")
737
+
738
+ safeseh_default = "true" if self.GetArch(config) == "x86" else None
739
+ ld(
740
+ "ImageHasSafeExceptionHandlers",
741
+ map={"false": ":NO", "true": ""},
742
+ prefix="/SAFESEH",
743
+ default=safeseh_default,
744
+ )
745
+
746
+ # If the base address is not specifically controlled, DYNAMICBASE should
747
+ # be on by default.
748
+ if not any("DYNAMICBASE" in flag or flag == "/FIXED" for flag in ldflags):
749
+ ldflags.append("/DYNAMICBASE")
750
+
751
+ # If the NXCOMPAT flag has not been specified, default to on. Despite the
752
+ # documentation that says this only defaults to on when the subsystem is
753
+ # Vista or greater (which applies to the linker), the IDE defaults it on
754
+ # unless it's explicitly off.
755
+ if not any("NXCOMPAT" in flag for flag in ldflags):
756
+ ldflags.append("/NXCOMPAT")
757
+
758
+ have_def_file = any(flag.startswith("/DEF:") for flag in ldflags)
759
+ (
760
+ manifest_flags,
761
+ intermediate_manifest,
762
+ manifest_files,
763
+ ) = self._GetLdManifestFlags(
764
+ config,
765
+ manifest_base_name,
766
+ gyp_to_build_path,
767
+ is_executable and not have_def_file,
768
+ build_dir,
769
+ )
770
+ ldflags.extend(manifest_flags)
771
+ return ldflags, intermediate_manifest, manifest_files
772
+
773
+ def _GetLdManifestFlags(
774
+ self, config, name, gyp_to_build_path, allow_isolation, build_dir
775
+ ):
776
+ """Returns a 3-tuple:
777
+ - the set of flags that need to be added to the link to generate
778
+ a default manifest
779
+ - the intermediate manifest that the linker will generate that should be
780
+ used to assert it doesn't add anything to the merged one.
781
+ - the list of all the manifest files to be merged by the manifest tool and
782
+ included into the link."""
783
+ generate_manifest = self._Setting(
784
+ ("VCLinkerTool", "GenerateManifest"), config, default="true"
785
+ )
786
+ if generate_manifest != "true":
787
+ # This means not only that the linker should not generate the intermediate
788
+ # manifest but also that the manifest tool should do nothing even when
789
+ # additional manifests are specified.
790
+ return ["/MANIFEST:NO"], [], []
791
+
792
+ output_name = name + ".intermediate.manifest"
793
+ flags = [
794
+ "/MANIFEST",
795
+ "/ManifestFile:" + output_name,
796
+ ]
797
+
798
+ # Instead of using the MANIFESTUAC flags, we generate a .manifest to
799
+ # include into the list of manifests. This allows us to avoid the need to
800
+ # do two passes during linking. The /MANIFEST flag and /ManifestFile are
801
+ # still used, and the intermediate manifest is used to assert that the
802
+ # final manifest we get from merging all the additional manifest files
803
+ # (plus the one we generate here) isn't modified by merging the
804
+ # intermediate into it.
805
+
806
+ # Always NO, because we generate a manifest file that has what we want.
807
+ flags.append("/MANIFESTUAC:NO")
808
+
809
+ config = self._TargetConfig(config)
810
+ enable_uac = self._Setting(
811
+ ("VCLinkerTool", "EnableUAC"), config, default="true"
812
+ )
813
+ manifest_files = []
814
+ generated_manifest_outer = (
815
+ "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"
816
+ "<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>"
817
+ "%s</assembly>"
818
+ )
819
+ if enable_uac == "true":
820
+ execution_level = self._Setting(
821
+ ("VCLinkerTool", "UACExecutionLevel"), config, default="0"
822
+ )
823
+ execution_level_map = {
824
+ "0": "asInvoker",
825
+ "1": "highestAvailable",
826
+ "2": "requireAdministrator",
827
+ }
828
+
829
+ ui_access = self._Setting(
830
+ ("VCLinkerTool", "UACUIAccess"), config, default="false"
831
+ )
832
+
833
+ level = execution_level_map[execution_level]
834
+ inner = f"""
835
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
836
+ <security>
837
+ <requestedPrivileges>
838
+ <requestedExecutionLevel level='{level}' uiAccess='{ui_access}' />
839
+ </requestedPrivileges>
840
+ </security>
841
+ </trustInfo>"""
842
+ else:
843
+ inner = ""
844
+
845
+ generated_manifest_contents = generated_manifest_outer % inner
846
+ generated_name = name + ".generated.manifest"
847
+ # Need to join with the build_dir here as we're writing it during
848
+ # generation time, but we return the un-joined version because the build
849
+ # will occur in that directory. We only write the file if the contents
850
+ # have changed so that simply regenerating the project files doesn't
851
+ # cause a relink.
852
+ build_dir_generated_name = os.path.join(build_dir, generated_name)
853
+ gyp.common.EnsureDirExists(build_dir_generated_name)
854
+ f = gyp.common.WriteOnDiff(build_dir_generated_name)
855
+ f.write(generated_manifest_contents)
856
+ f.close()
857
+ manifest_files = [generated_name]
858
+
859
+ if allow_isolation:
860
+ flags.append("/ALLOWISOLATION")
861
+
862
+ manifest_files += self._GetAdditionalManifestFiles(config, gyp_to_build_path)
863
+ return flags, output_name, manifest_files
864
+
865
+ def _GetAdditionalManifestFiles(self, config, gyp_to_build_path):
866
+ """Gets additional manifest files that are added to the default one
867
+ generated by the linker."""
868
+ files = self._Setting(
869
+ ("VCManifestTool", "AdditionalManifestFiles"), config, default=[]
870
+ )
871
+ if isinstance(files, str):
872
+ files = files.split(";")
873
+ return [
874
+ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(f, config=config)))
875
+ for f in files
876
+ ]
877
+
878
+ def IsUseLibraryDependencyInputs(self, config):
879
+ """Returns whether the target should be linked via Use Library Dependency
880
+ Inputs (using component .objs of a given .lib)."""
881
+ config = self._TargetConfig(config)
882
+ uldi = self._Setting(("VCLinkerTool", "UseLibraryDependencyInputs"), config)
883
+ return uldi == "true"
884
+
885
+ def IsEmbedManifest(self, config):
886
+ """Returns whether manifest should be linked into binary."""
887
+ config = self._TargetConfig(config)
888
+ embed = self._Setting(
889
+ ("VCManifestTool", "EmbedManifest"), config, default="true"
890
+ )
891
+ return embed == "true"
892
+
893
+ def IsLinkIncremental(self, config):
894
+ """Returns whether the target should be linked incrementally."""
895
+ config = self._TargetConfig(config)
896
+ link_inc = self._Setting(("VCLinkerTool", "LinkIncremental"), config)
897
+ return link_inc != "1"
898
+
899
+ def GetRcflags(self, config, gyp_to_ninja_path):
900
+ """Returns the flags that need to be added to invocations of the resource
901
+ compiler."""
902
+ config = self._TargetConfig(config)
903
+ rcflags = []
904
+ rc = self._GetWrapper(
905
+ self, self.msvs_settings[config], "VCResourceCompilerTool", append=rcflags
906
+ )
907
+ rc("AdditionalIncludeDirectories", map=gyp_to_ninja_path, prefix="/I")
908
+ rcflags.append("/I" + gyp_to_ninja_path("."))
909
+ rc("PreprocessorDefinitions", prefix="/d")
910
+ # /l arg must be in hex without leading '0x'
911
+ rc("Culture", prefix="/l", map=lambda x: hex(int(x))[2:])
912
+ return rcflags
913
+
914
+ def BuildCygwinBashCommandLine(self, args, path_to_base):
915
+ """Build a command line that runs args via cygwin bash. We assume that all
916
+ incoming paths are in Windows normpath'd form, so they need to be
917
+ converted to posix style for the part of the command line that's passed to
918
+ bash. We also have to do some Visual Studio macro emulation here because
919
+ various rules use magic VS names for things. Also note that rules that
920
+ contain ninja variables cannot be fixed here (for example ${source}), so
921
+ the outer generator needs to make sure that the paths that are written out
922
+ are in posix style, if the command line will be used here."""
923
+ cygwin_dir = os.path.normpath(
924
+ os.path.join(path_to_base, self.msvs_cygwin_dirs[0])
925
+ )
926
+ cd = ("cd %s" % path_to_base).replace("\\", "/")
927
+ args = [a.replace("\\", "/").replace('"', '\\"') for a in args]
928
+ args = ["'%s'" % a.replace("'", "'\\''") for a in args]
929
+ bash_cmd = " ".join(args)
930
+ cmd = (
931
+ 'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir
932
+ + f'bash -c "{cd} ; {bash_cmd}"'
933
+ )
934
+ return cmd
935
+
936
+ RuleShellFlags = namedtuple("RuleShellFlags", ["cygwin", "quote"]) # noqa: PYI024
937
+
938
+ def GetRuleShellFlags(self, rule):
939
+ """Return RuleShellFlags about how the given rule should be run. This
940
+ includes whether it should run under cygwin (msvs_cygwin_shell), and
941
+ whether the commands should be quoted (msvs_quote_cmd)."""
942
+ # If the variable is unset, or set to 1 we use cygwin
943
+ cygwin = int(rule.get("msvs_cygwin_shell",
944
+ self.spec.get("msvs_cygwin_shell", 1))) != 0
945
+ # Default to quoting. There's only a few special instances where the
946
+ # target command uses non-standard command line parsing and handle quotes
947
+ # and quote escaping differently.
948
+ quote_cmd = int(rule.get("msvs_quote_cmd", 1))
949
+ assert quote_cmd != 0 or cygwin != 1, \
950
+ "msvs_quote_cmd=0 only applicable for msvs_cygwin_shell=0"
951
+ return MsvsSettings.RuleShellFlags(cygwin, quote_cmd)
952
+
953
+ def _HasExplicitRuleForExtension(self, spec, extension):
954
+ """Determine if there's an explicit rule for a particular extension."""
955
+ return any(rule["extension"] == extension for rule in spec.get("rules", []))
956
+
957
+ def _HasExplicitIdlActions(self, spec):
958
+ """Determine if an action should not run midl for .idl files."""
959
+ return any(
960
+ action.get("explicit_idl_action", 0) for action in spec.get("actions", [])
961
+ )
962
+
963
+ def HasExplicitIdlRulesOrActions(self, spec):
964
+ """Determine if there's an explicit rule or action for idl files. When
965
+ there isn't we need to generate implicit rules to build MIDL .idl files."""
966
+ return self._HasExplicitRuleForExtension(
967
+ spec, "idl"
968
+ ) or self._HasExplicitIdlActions(spec)
969
+
970
+ def HasExplicitAsmRules(self, spec):
971
+ """Determine if there's an explicit rule for asm files. When there isn't we
972
+ need to generate implicit rules to assemble .asm files."""
973
+ return self._HasExplicitRuleForExtension(spec, "asm")
974
+
975
+ def GetIdlBuildData(self, source, config):
976
+ """Determine the implicit outputs for an idl file. Returns output
977
+ directory, outputs, and variables and flags that are required."""
978
+ config = self._TargetConfig(config)
979
+ midl_get = self._GetWrapper(self, self.msvs_settings[config], "VCMIDLTool")
980
+
981
+ def midl(name, default=None):
982
+ return self.ConvertVSMacros(midl_get(name, default=default), config=config)
983
+
984
+ tlb = midl("TypeLibraryName", default="${root}.tlb")
985
+ header = midl("HeaderFileName", default="${root}.h")
986
+ dlldata = midl("DLLDataFileName", default="dlldata.c")
987
+ iid = midl("InterfaceIdentifierFileName", default="${root}_i.c")
988
+ proxy = midl("ProxyFileName", default="${root}_p.c")
989
+ # Note that .tlb is not included in the outputs as it is not always
990
+ # generated depending on the content of the input idl file.
991
+ outdir = midl("OutputDirectory", default="")
992
+ output = [header, dlldata, iid, proxy]
993
+ variables = [
994
+ ("tlb", tlb),
995
+ ("h", header),
996
+ ("dlldata", dlldata),
997
+ ("iid", iid),
998
+ ("proxy", proxy),
999
+ ]
1000
+ # TODO(scottmg): Are there configuration settings to set these flags?
1001
+ target_platform = self.GetArch(config)
1002
+ if target_platform == "x86":
1003
+ target_platform = "win32"
1004
+ flags = ["/char", "signed", "/env", target_platform, "/Oicf"]
1005
+ return outdir, output, variables, flags
1006
+
1007
+
1008
+ def _LanguageMatchesForPch(source_ext, pch_source_ext):
1009
+ c_exts = (".c",)
1010
+ cc_exts = (".cc", ".cxx", ".cpp")
1011
+ return (source_ext in c_exts and pch_source_ext in c_exts) or (
1012
+ source_ext in cc_exts and pch_source_ext in cc_exts
1013
+ )
1014
+
1015
+
1016
+ class PrecompiledHeader:
1017
+ """Helper to generate dependencies and build rules to handle generation of
1018
+ precompiled headers. Interface matches the GCH handler in xcode_emulation.py.
1019
+ """
1020
+
1021
+ def __init__(
1022
+ self, settings, config, gyp_to_build_path, gyp_to_unique_output, obj_ext
1023
+ ):
1024
+ self.settings = settings
1025
+ self.config = config
1026
+ pch_source = self.settings.msvs_precompiled_source[self.config]
1027
+ self.pch_source = gyp_to_build_path(pch_source)
1028
+ filename, _ = os.path.splitext(pch_source)
1029
+ self.output_obj = gyp_to_unique_output(filename + obj_ext).lower()
1030
+
1031
+ def _PchHeader(self):
1032
+ """Get the header that will appear in an #include line for all source
1033
+ files."""
1034
+ return self.settings.msvs_precompiled_header[self.config]
1035
+
1036
+ def GetObjDependencies(self, sources, objs, arch):
1037
+ """Given a list of sources files and the corresponding object files,
1038
+ returns a list of the pch files that should be depended upon. The
1039
+ additional wrapping in the return value is for interface compatibility
1040
+ with make.py on Mac, and xcode_emulation.py."""
1041
+ assert arch is None
1042
+ if not self._PchHeader():
1043
+ return []
1044
+ pch_ext = os.path.splitext(self.pch_source)[1]
1045
+ for source in sources:
1046
+ if _LanguageMatchesForPch(os.path.splitext(source)[1], pch_ext):
1047
+ return [(None, None, self.output_obj)]
1048
+ return []
1049
+
1050
+ def GetPchBuildCommands(self, arch):
1051
+ """Not used on Windows as there are no additional build steps required
1052
+ (instead, existing steps are modified in GetFlagsModifications below)."""
1053
+ return []
1054
+
1055
+ def GetFlagsModifications(
1056
+ self, input, output, implicit, command, cflags_c, cflags_cc, expand_special
1057
+ ):
1058
+ """Get the modified cflags and implicit dependencies that should be used
1059
+ for the pch compilation step."""
1060
+ if input == self.pch_source:
1061
+ pch_output = ["/Yc" + self._PchHeader()]
1062
+ if command == "cxx":
1063
+ return (
1064
+ [("cflags_cc", map(expand_special, cflags_cc + pch_output))],
1065
+ self.output_obj,
1066
+ [],
1067
+ )
1068
+ elif command == "cc":
1069
+ return (
1070
+ [("cflags_c", map(expand_special, cflags_c + pch_output))],
1071
+ self.output_obj,
1072
+ [],
1073
+ )
1074
+ return [], output, implicit
1075
+
1076
+
1077
+ vs_version = None
1078
+
1079
+
1080
+ def GetVSVersion(generator_flags):
1081
+ global vs_version
1082
+ if not vs_version:
1083
+ vs_version = gyp.MSVSVersion.SelectVisualStudioVersion(
1084
+ generator_flags.get("msvs_version", "auto"), allow_fallback=False
1085
+ )
1086
+ return vs_version
1087
+
1088
+
1089
+ def _GetVsvarsSetupArgs(generator_flags, arch):
1090
+ vs = GetVSVersion(generator_flags)
1091
+ return vs.SetupScript()
1092
+
1093
+
1094
+ def ExpandMacros(string, expansions):
1095
+ """Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv
1096
+ for the canonical way to retrieve a suitable dict."""
1097
+ if "$" in string:
1098
+ for old, new in expansions.items():
1099
+ assert "$(" not in new, new
1100
+ string = string.replace(old, new)
1101
+ return string
1102
+
1103
+
1104
+ def _ExtractImportantEnvironment(output_of_set):
1105
+ """Extracts environment variables required for the toolchain to run from
1106
+ a textual dump output by the cmd.exe 'set' command."""
1107
+ envvars_to_save = (
1108
+ "goma_.*", # TODO(scottmg): This is ugly, but needed for goma.
1109
+ "include",
1110
+ "lib",
1111
+ "libpath",
1112
+ "path",
1113
+ "pathext",
1114
+ "systemroot",
1115
+ "temp",
1116
+ "tmp",
1117
+ )
1118
+ env = {}
1119
+ # This occasionally happens and leads to misleading SYSTEMROOT error messages
1120
+ # if not caught here.
1121
+ if output_of_set.count("=") == 0:
1122
+ raise Exception("Invalid output_of_set. Value is:\n%s" % output_of_set)
1123
+ for line in output_of_set.splitlines():
1124
+ for envvar in envvars_to_save:
1125
+ if re.match(envvar + "=", line.lower()):
1126
+ var, setting = line.split("=", 1)
1127
+ if envvar == "path":
1128
+ # Our own rules (for running gyp-win-tool) and other actions in
1129
+ # Chromium rely on python being in the path. Add the path to this
1130
+ # python here so that if it's not in the path when ninja is run
1131
+ # later, python will still be found.
1132
+ setting = os.path.dirname(sys.executable) + os.pathsep + setting
1133
+ env[var.upper()] = setting
1134
+ break
1135
+ for required in ("SYSTEMROOT", "TEMP", "TMP"):
1136
+ if required not in env:
1137
+ raise Exception(
1138
+ 'Environment variable "%s" '
1139
+ "required to be set to valid path" % required
1140
+ )
1141
+ return env
1142
+
1143
+
1144
+ def _FormatAsEnvironmentBlock(envvar_dict):
1145
+ """Format as an 'environment block' directly suitable for CreateProcess.
1146
+ Briefly this is a list of key=value\0, terminated by an additional \0. See
1147
+ CreateProcess documentation for more details."""
1148
+ block = ""
1149
+ nul = "\0"
1150
+ for key, value in envvar_dict.items():
1151
+ block += key + "=" + value + nul
1152
+ block += nul
1153
+ return block
1154
+
1155
+
1156
+ def _ExtractCLPath(output_of_where):
1157
+ """Gets the path to cl.exe based on the output of calling the environment
1158
+ setup batch file, followed by the equivalent of `where`."""
1159
+ # Take the first line, as that's the first found in the PATH.
1160
+ for line in output_of_where.strip().splitlines():
1161
+ if line.startswith("LOC:"):
1162
+ return line[len("LOC:") :].strip()
1163
+
1164
+
1165
+ def GenerateEnvironmentFiles(
1166
+ toplevel_build_dir, generator_flags, system_includes, open_out
1167
+ ):
1168
+ """It's not sufficient to have the absolute path to the compiler, linker,
1169
+ etc. on Windows, as those tools rely on .dlls being in the PATH. We also
1170
+ need to support both x86 and x64 compilers within the same build (to support
1171
+ msvs_target_platform hackery). Different architectures require a different
1172
+ compiler binary, and different supporting environment variables (INCLUDE,
1173
+ LIB, LIBPATH). So, we extract the environment here, wrap all invocations
1174
+ of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which
1175
+ sets up the environment, and then we do not prefix the compiler with
1176
+ an absolute path, instead preferring something like "cl.exe" in the rule
1177
+ which will then run whichever the environment setup has put in the path.
1178
+ When the following procedure to generate environment files does not
1179
+ meet your requirement (e.g. for custom toolchains), you can pass
1180
+ "-G ninja_use_custom_environment_files" to the gyp to suppress file
1181
+ generation and use custom environment files prepared by yourself."""
1182
+ archs = ("x86", "x64")
1183
+ if generator_flags.get("ninja_use_custom_environment_files", 0):
1184
+ cl_paths = {}
1185
+ for arch in archs:
1186
+ cl_paths[arch] = "cl.exe"
1187
+ return cl_paths
1188
+ vs = GetVSVersion(generator_flags)
1189
+ cl_paths = {}
1190
+ for arch in archs:
1191
+ # Extract environment variables for subprocesses.
1192
+ args = vs.SetupScript(arch)
1193
+ args.extend(("&&", "set"))
1194
+ popen = subprocess.Popen(
1195
+ args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
1196
+ )
1197
+ variables = popen.communicate()[0].decode("utf-8")
1198
+ if popen.returncode != 0:
1199
+ raise Exception('"%s" failed with error %d' % (args, popen.returncode))
1200
+ env = _ExtractImportantEnvironment(variables)
1201
+
1202
+ # Inject system includes from gyp files into INCLUDE.
1203
+ if system_includes:
1204
+ system_includes = system_includes | OrderedSet(
1205
+ env.get("INCLUDE", "").split(";")
1206
+ )
1207
+ env["INCLUDE"] = ";".join(system_includes)
1208
+
1209
+ env_block = _FormatAsEnvironmentBlock(env)
1210
+ f = open_out(os.path.join(toplevel_build_dir, "environment." + arch), "w")
1211
+ f.write(env_block)
1212
+ f.close()
1213
+
1214
+ # Find cl.exe location for this architecture.
1215
+ args = vs.SetupScript(arch)
1216
+ args.extend(
1217
+ ("&&", "for", "%i", "in", "(cl.exe)", "do", "@echo", "LOC:%~$PATH:i")
1218
+ )
1219
+ popen = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
1220
+ output = popen.communicate()[0].decode("utf-8")
1221
+ cl_paths[arch] = _ExtractCLPath(output)
1222
+ return cl_paths
1223
+
1224
+
1225
+ def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja):
1226
+ """Emulate behavior of msvs_error_on_missing_sources present in the msvs
1227
+ generator: Check that all regular source files, i.e. not created at run time,
1228
+ exist on disk. Missing files cause needless recompilation when building via
1229
+ VS, and we want this check to match for people/bots that build using ninja,
1230
+ so they're not surprised when the VS build fails."""
1231
+ if int(generator_flags.get("msvs_error_on_missing_sources", 0)):
1232
+ no_specials = filter(lambda x: "$" not in x, sources)
1233
+ relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials]
1234
+ missing = [x for x in relative if not os.path.exists(x)]
1235
+ if missing:
1236
+ # They'll look like out\Release\..\..\stuff\things.cc, so normalize the
1237
+ # path for a slightly less crazy looking output.
1238
+ cleaned_up = [os.path.normpath(x) for x in missing]
1239
+ raise Exception("Missing input files:\n%s" % "\n".join(cleaned_up))
1240
+
1241
+
1242
+ # Sets some values in default_variables, which are required for many
1243
+ # generators, run on Windows.
1244
+ def CalculateCommonVariables(default_variables, params):
1245
+ generator_flags = params.get("generator_flags", {})
1246
+
1247
+ # Set a variable so conditions can be based on msvs_version.
1248
+ msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags)
1249
+ default_variables["MSVS_VERSION"] = msvs_version.ShortName()
1250
+
1251
+ # To determine processor word size on Windows, in addition to checking
1252
+ # PROCESSOR_ARCHITECTURE (which reflects the word size of the current
1253
+ # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which
1254
+ # contains the actual word size of the system when running thru WOW64).
1255
+ if "64" in os.environ.get("PROCESSOR_ARCHITECTURE", "") or "64" in os.environ.get(
1256
+ "PROCESSOR_ARCHITEW6432", ""
1257
+ ):
1258
+ default_variables["MSVS_OS_BITS"] = 64
1259
+ else:
1260
+ default_variables["MSVS_OS_BITS"] = 32