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,2965 @@
1
+ # Copyright (c) 2013 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
+ import collections
7
+ import copy
8
+ import hashlib
9
+ import json
10
+ import multiprocessing
11
+ import os.path
12
+ import re
13
+ import shutil
14
+ import signal
15
+ import subprocess
16
+ import sys
17
+ from io import StringIO
18
+
19
+ import gyp
20
+ import gyp.common
21
+ import gyp.msvs_emulation
22
+ import gyp.xcode_emulation
23
+ from gyp import MSVSUtil, ninja_syntax
24
+ from gyp.common import GetEnvironFallback
25
+
26
+ generator_default_variables = {
27
+ "EXECUTABLE_PREFIX": "",
28
+ "EXECUTABLE_SUFFIX": "",
29
+ "STATIC_LIB_PREFIX": "lib",
30
+ "STATIC_LIB_SUFFIX": ".a",
31
+ "SHARED_LIB_PREFIX": "lib",
32
+ # Gyp expects the following variables to be expandable by the build
33
+ # system to the appropriate locations. Ninja prefers paths to be
34
+ # known at gyp time. To resolve this, introduce special
35
+ # variables starting with $! and $| (which begin with a $ so gyp knows it
36
+ # should be treated specially, but is otherwise an invalid
37
+ # ninja/shell variable) that are passed to gyp here but expanded
38
+ # before writing out into the target .ninja files; see
39
+ # ExpandSpecial.
40
+ # $! is used for variables that represent a path and that can only appear at
41
+ # the start of a string, while $| is used for variables that can appear
42
+ # anywhere in a string.
43
+ "INTERMEDIATE_DIR": "$!INTERMEDIATE_DIR",
44
+ "SHARED_INTERMEDIATE_DIR": "$!PRODUCT_DIR/gen",
45
+ "PRODUCT_DIR": "$!PRODUCT_DIR",
46
+ "CONFIGURATION_NAME": "$|CONFIGURATION_NAME",
47
+ # Special variables that may be used by gyp 'rule' targets.
48
+ # We generate definitions for these variables on the fly when processing a
49
+ # rule.
50
+ "RULE_INPUT_ROOT": "${root}",
51
+ "RULE_INPUT_DIRNAME": "${dirname}",
52
+ "RULE_INPUT_PATH": "${source}",
53
+ "RULE_INPUT_EXT": "${ext}",
54
+ "RULE_INPUT_NAME": "${name}",
55
+ }
56
+
57
+ # Placates pylint.
58
+ generator_additional_non_configuration_keys = []
59
+ generator_additional_path_sections = []
60
+ generator_extra_sources_for_rules = []
61
+ generator_filelist_paths = None
62
+
63
+ generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()
64
+
65
+
66
+ def StripPrefix(arg, prefix):
67
+ if arg.startswith(prefix):
68
+ return arg[len(prefix) :]
69
+ return arg
70
+
71
+
72
+ def QuoteShellArgument(arg, flavor):
73
+ """Quote a string such that it will be interpreted as a single argument
74
+ by the shell."""
75
+ # Rather than attempting to enumerate the bad shell characters, just
76
+ # allow common OK ones and quote anything else.
77
+ if re.match(r"^[a-zA-Z0-9_=.\\/-]+$", arg):
78
+ return arg # No quoting necessary.
79
+ if flavor == "win":
80
+ return gyp.msvs_emulation.QuoteForRspFile(arg)
81
+ return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
82
+
83
+
84
+ def Define(d, flavor):
85
+ """Takes a preprocessor define and returns a -D parameter that's ninja- and
86
+ shell-escaped."""
87
+ if flavor == "win":
88
+ # cl.exe replaces literal # characters with = in preprocessor definitions for
89
+ # some reason. Octal-encode to work around that.
90
+ d = d.replace("#", "\\%03o" % ord("#"))
91
+ return QuoteShellArgument(ninja_syntax.escape("-D" + d), flavor)
92
+
93
+
94
+ def AddArch(output, arch):
95
+ """Adds an arch string to an output path."""
96
+ output, extension = os.path.splitext(output)
97
+ return f"{output}.{arch}{extension}"
98
+
99
+
100
+ class Target:
101
+ """Target represents the paths used within a single gyp target.
102
+
103
+ Conceptually, building a single target A is a series of steps:
104
+
105
+ 1) actions/rules/copies generates source/resources/etc.
106
+ 2) compiles generates .o files
107
+ 3) link generates a binary (library/executable)
108
+ 4) bundle merges the above in a mac bundle
109
+
110
+ (Any of these steps can be optional.)
111
+
112
+ From a build ordering perspective, a dependent target B could just
113
+ depend on the last output of this series of steps.
114
+
115
+ But some dependent commands sometimes need to reach inside the box.
116
+ For example, when linking B it needs to get the path to the static
117
+ library generated by A.
118
+
119
+ This object stores those paths. To keep things simple, member
120
+ variables only store concrete paths to single files, while methods
121
+ compute derived values like "the last output of the target".
122
+ """
123
+
124
+ def __init__(self, type):
125
+ # Gyp type ("static_library", etc.) of this target.
126
+ self.type = type
127
+ # File representing whether any input dependencies necessary for
128
+ # dependent actions have completed.
129
+ self.preaction_stamp = None
130
+ # File representing whether any input dependencies necessary for
131
+ # dependent compiles have completed.
132
+ self.precompile_stamp = None
133
+ # File representing the completion of actions/rules/copies, if any.
134
+ self.actions_stamp = None
135
+ # Path to the output of the link step, if any.
136
+ self.binary = None
137
+ # Path to the file representing the completion of building the bundle,
138
+ # if any.
139
+ self.bundle = None
140
+ # On Windows, incremental linking requires linking against all the .objs
141
+ # that compose a .lib (rather than the .lib itself). That list is stored
142
+ # here. In this case, we also need to save the compile_deps for the target,
143
+ # so that the target that directly depends on the .objs can also depend
144
+ # on those.
145
+ self.component_objs = None
146
+ self.compile_deps = None
147
+ # Windows only. The import .lib is the output of a build step, but
148
+ # because dependents only link against the lib (not both the lib and the
149
+ # dll) we keep track of the import library here.
150
+ self.import_lib = None
151
+ # Track if this target contains any C++ files, to decide if gcc or g++
152
+ # should be used for linking.
153
+ self.uses_cpp = False
154
+
155
+ def Linkable(self):
156
+ """Return true if this is a target that can be linked against."""
157
+ return self.type in ("static_library", "shared_library")
158
+
159
+ def UsesToc(self, flavor):
160
+ """Return true if the target should produce a restat rule based on a TOC
161
+ file."""
162
+ # For bundles, the .TOC should be produced for the binary, not for
163
+ # FinalOutput(). But the naive approach would put the TOC file into the
164
+ # bundle, so don't do this for bundles for now.
165
+ if flavor == "win" or self.bundle:
166
+ return False
167
+ return self.type in ("shared_library", "loadable_module")
168
+
169
+ def PreActionInput(self, flavor):
170
+ """Return the path, if any, that should be used as a dependency of
171
+ any dependent action step."""
172
+ if self.UsesToc(flavor):
173
+ return self.FinalOutput() + ".TOC"
174
+ return self.FinalOutput() or self.preaction_stamp
175
+
176
+ def PreCompileInput(self):
177
+ """Return the path, if any, that should be used as a dependency of
178
+ any dependent compile step."""
179
+ return self.actions_stamp or self.precompile_stamp
180
+
181
+ def FinalOutput(self):
182
+ """Return the last output of the target, which depends on all prior
183
+ steps."""
184
+ return self.bundle or self.binary or self.actions_stamp
185
+
186
+
187
+ # A small discourse on paths as used within the Ninja build:
188
+ # All files we produce (both at gyp and at build time) appear in the
189
+ # build directory (e.g. out/Debug).
190
+ #
191
+ # Paths within a given .gyp file are always relative to the directory
192
+ # containing the .gyp file. Call these "gyp paths". This includes
193
+ # sources as well as the starting directory a given gyp rule/action
194
+ # expects to be run from. We call the path from the source root to
195
+ # the gyp file the "base directory" within the per-.gyp-file
196
+ # NinjaWriter code.
197
+ #
198
+ # All paths as written into the .ninja files are relative to the build
199
+ # directory. Call these paths "ninja paths".
200
+ #
201
+ # We translate between these two notions of paths with two helper
202
+ # functions:
203
+ #
204
+ # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file)
205
+ # into the equivalent ninja path.
206
+ #
207
+ # - GypPathToUniqueOutput translates a gyp path into a ninja path to write
208
+ # an output file; the result can be namespaced such that it is unique
209
+ # to the input file name as well as the output target name.
210
+
211
+
212
+ class NinjaWriter:
213
+ def __init__(
214
+ self,
215
+ hash_for_rules,
216
+ target_outputs,
217
+ base_dir,
218
+ build_dir,
219
+ output_file,
220
+ toplevel_build,
221
+ output_file_name,
222
+ flavor,
223
+ toplevel_dir=None,
224
+ ):
225
+ """
226
+ base_dir: path from source root to directory containing this gyp file,
227
+ by gyp semantics, all input paths are relative to this
228
+ build_dir: path from source root to build output
229
+ toplevel_dir: path to the toplevel directory
230
+ """
231
+
232
+ self.hash_for_rules = hash_for_rules
233
+ self.target_outputs = target_outputs
234
+ self.base_dir = base_dir
235
+ self.build_dir = build_dir
236
+ self.ninja = ninja_syntax.Writer(output_file)
237
+ self.toplevel_build = toplevel_build
238
+ self.output_file_name = output_file_name
239
+
240
+ self.flavor = flavor
241
+ self.abs_build_dir = None
242
+ if toplevel_dir is not None:
243
+ self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir))
244
+ self.obj_ext = ".obj" if flavor == "win" else ".o"
245
+ if flavor == "win":
246
+ # See docstring of msvs_emulation.GenerateEnvironmentFiles().
247
+ self.win_env = {}
248
+ for arch in ("x86", "x64"):
249
+ self.win_env[arch] = "environment." + arch
250
+
251
+ # Relative path from build output dir to base dir.
252
+ build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir)
253
+ self.build_to_base = os.path.join(build_to_top, base_dir)
254
+ # Relative path from base dir to build dir.
255
+ base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir)
256
+ self.base_to_build = os.path.join(base_to_top, build_dir)
257
+
258
+ def ExpandSpecial(self, path, product_dir=None):
259
+ """Expand specials like $!PRODUCT_DIR in |path|.
260
+
261
+ If |product_dir| is None, assumes the cwd is already the product
262
+ dir. Otherwise, |product_dir| is the relative path to the product
263
+ dir.
264
+ """
265
+
266
+ PRODUCT_DIR = "$!PRODUCT_DIR"
267
+ if PRODUCT_DIR in path:
268
+ if product_dir:
269
+ path = path.replace(PRODUCT_DIR, product_dir)
270
+ else:
271
+ path = path.replace(PRODUCT_DIR + "/", "")
272
+ path = path.replace(PRODUCT_DIR + "\\", "")
273
+ path = path.replace(PRODUCT_DIR, ".")
274
+
275
+ INTERMEDIATE_DIR = "$!INTERMEDIATE_DIR"
276
+ if INTERMEDIATE_DIR in path:
277
+ int_dir = self.GypPathToUniqueOutput("gen")
278
+ # GypPathToUniqueOutput generates a path relative to the product dir,
279
+ # so insert product_dir in front if it is provided.
280
+ path = path.replace(
281
+ INTERMEDIATE_DIR, os.path.join(product_dir or "", int_dir)
282
+ )
283
+
284
+ CONFIGURATION_NAME = "$|CONFIGURATION_NAME"
285
+ path = path.replace(CONFIGURATION_NAME, self.config_name)
286
+
287
+ return path
288
+
289
+ def ExpandRuleVariables(self, path, root, dirname, source, ext, name):
290
+ if self.flavor == "win":
291
+ path = self.msvs_settings.ConvertVSMacros(path, config=self.config_name)
292
+ path = path.replace(generator_default_variables["RULE_INPUT_ROOT"], root)
293
+ path = path.replace(generator_default_variables["RULE_INPUT_DIRNAME"], dirname)
294
+ path = path.replace(generator_default_variables["RULE_INPUT_PATH"], source)
295
+ path = path.replace(generator_default_variables["RULE_INPUT_EXT"], ext)
296
+ path = path.replace(generator_default_variables["RULE_INPUT_NAME"], name)
297
+ return path
298
+
299
+ def GypPathToNinja(self, path, env=None):
300
+ """Translate a gyp path to a ninja path, optionally expanding environment
301
+ variable references in |path| with |env|.
302
+
303
+ See the above discourse on path conversions."""
304
+ if env:
305
+ if self.flavor == "mac":
306
+ path = gyp.xcode_emulation.ExpandEnvVars(path, env)
307
+ elif self.flavor == "win":
308
+ path = gyp.msvs_emulation.ExpandMacros(path, env)
309
+ if path.startswith("$!"):
310
+ expanded = self.ExpandSpecial(path)
311
+ if self.flavor == "win":
312
+ expanded = os.path.normpath(expanded)
313
+ return expanded
314
+ if "$|" in path:
315
+ path = self.ExpandSpecial(path)
316
+ assert "$" not in path, path
317
+ return os.path.normpath(os.path.join(self.build_to_base, path))
318
+
319
+ def GypPathToUniqueOutput(self, path, qualified=True):
320
+ """Translate a gyp path to a ninja path for writing output.
321
+
322
+ If qualified is True, qualify the resulting filename with the name
323
+ of the target. This is necessary when e.g. compiling the same
324
+ path twice for two separate output targets.
325
+
326
+ See the above discourse on path conversions."""
327
+
328
+ path = self.ExpandSpecial(path)
329
+ assert not path.startswith("$"), path
330
+
331
+ # Translate the path following this scheme:
332
+ # Input: foo/bar.gyp, target targ, references baz/out.o
333
+ # Output: obj/foo/baz/targ.out.o (if qualified)
334
+ # obj/foo/baz/out.o (otherwise)
335
+ # (and obj.host instead of obj for cross-compiles)
336
+ #
337
+ # Why this scheme and not some other one?
338
+ # 1) for a given input, you can compute all derived outputs by matching
339
+ # its path, even if the input is brought via a gyp file with '..'.
340
+ # 2) simple files like libraries and stamps have a simple filename.
341
+
342
+ obj = "obj"
343
+ if self.toolset != "target":
344
+ obj += "." + self.toolset
345
+
346
+ path_dir, path_basename = os.path.split(path)
347
+ assert not os.path.isabs(path_dir), (
348
+ "'%s' can not be absolute path (see crbug.com/462153)." % path_dir
349
+ )
350
+
351
+ if qualified:
352
+ path_basename = self.name + "." + path_basename
353
+ return os.path.normpath(
354
+ os.path.join(obj, self.base_dir, path_dir, path_basename)
355
+ )
356
+
357
+ def WriteCollapsedDependencies(self, name, targets, order_only=None):
358
+ """Given a list of targets, return a path for a single file
359
+ representing the result of building all the targets or None.
360
+
361
+ Uses a stamp file if necessary."""
362
+
363
+ assert targets == [item for item in targets if item], targets
364
+ if len(targets) == 0:
365
+ assert not order_only
366
+ return None
367
+ if len(targets) > 1 or order_only:
368
+ stamp = self.GypPathToUniqueOutput(name + ".stamp")
369
+ targets = self.ninja.build(stamp, "stamp", targets, order_only=order_only)
370
+ self.ninja.newline()
371
+ return targets[0]
372
+
373
+ def _SubninjaNameForArch(self, arch):
374
+ output_file_base = os.path.splitext(self.output_file_name)[0]
375
+ return f"{output_file_base}.{arch}.ninja"
376
+
377
+ def WriteSpec(self, spec, config_name, generator_flags):
378
+ """The main entry point for NinjaWriter: write the build rules for a spec.
379
+
380
+ Returns a Target object, which represents the output paths for this spec.
381
+ Returns None if there are no outputs (e.g. a settings-only 'none' type
382
+ target)."""
383
+
384
+ self.config_name = config_name
385
+ self.name = spec["target_name"]
386
+ self.toolset = spec["toolset"]
387
+ config = spec["configurations"][config_name]
388
+ self.target = Target(spec["type"])
389
+ self.is_standalone_static_library = bool(
390
+ spec.get("standalone_static_library", 0)
391
+ )
392
+
393
+ self.target_rpath = generator_flags.get("target_rpath", r"\$$ORIGIN/lib/")
394
+
395
+ self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec)
396
+ self.xcode_settings = self.msvs_settings = None
397
+ if self.flavor == "mac":
398
+ self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
399
+ mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None)
400
+ if mac_toolchain_dir:
401
+ self.xcode_settings.mac_toolchain_dir = mac_toolchain_dir
402
+
403
+ if self.flavor == "win":
404
+ self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags)
405
+ arch = self.msvs_settings.GetArch(config_name)
406
+ self.ninja.variable("arch", self.win_env[arch])
407
+ self.ninja.variable("cc", "$cl_" + arch)
408
+ self.ninja.variable("cxx", "$cl_" + arch)
409
+ self.ninja.variable("cc_host", "$cl_" + arch)
410
+ self.ninja.variable("cxx_host", "$cl_" + arch)
411
+ self.ninja.variable("asm", "$ml_" + arch)
412
+
413
+ if self.flavor == "mac":
414
+ self.archs = self.xcode_settings.GetActiveArchs(config_name)
415
+ if len(self.archs) > 1:
416
+ self.arch_subninjas = {
417
+ arch: ninja_syntax.Writer(
418
+ OpenOutput(
419
+ os.path.join(
420
+ self.toplevel_build, self._SubninjaNameForArch(arch)
421
+ ),
422
+ "w",
423
+ )
424
+ )
425
+ for arch in self.archs
426
+ }
427
+
428
+ # Compute predepends for all rules.
429
+ # actions_depends is the dependencies this target depends on before running
430
+ # any of its action/rule/copy steps.
431
+ # compile_depends is the dependencies this target depends on before running
432
+ # any of its compile steps.
433
+ actions_depends = []
434
+ compile_depends = []
435
+ # TODO(evan): it is rather confusing which things are lists and which
436
+ # are strings. Fix these.
437
+ if "dependencies" in spec:
438
+ for dep in spec["dependencies"]:
439
+ if dep in self.target_outputs:
440
+ target = self.target_outputs[dep]
441
+ actions_depends.append(target.PreActionInput(self.flavor))
442
+ compile_depends.append(target.PreCompileInput())
443
+ if target.uses_cpp:
444
+ self.target.uses_cpp = True
445
+ actions_depends = [item for item in actions_depends if item]
446
+ compile_depends = [item for item in compile_depends if item]
447
+ actions_depends = self.WriteCollapsedDependencies(
448
+ "actions_depends", actions_depends
449
+ )
450
+ compile_depends = self.WriteCollapsedDependencies(
451
+ "compile_depends", compile_depends
452
+ )
453
+ self.target.preaction_stamp = actions_depends
454
+ self.target.precompile_stamp = compile_depends
455
+
456
+ # Write out actions, rules, and copies. These must happen before we
457
+ # compile any sources, so compute a list of predependencies for sources
458
+ # while we do it.
459
+ extra_sources = []
460
+ mac_bundle_depends = []
461
+ self.target.actions_stamp = self.WriteActionsRulesCopies(
462
+ spec, extra_sources, actions_depends, mac_bundle_depends
463
+ )
464
+
465
+ # If we have actions/rules/copies, we depend directly on those, but
466
+ # otherwise we depend on dependent target's actions/rules/copies etc.
467
+ # We never need to explicitly depend on previous target's link steps,
468
+ # because no compile ever depends on them.
469
+ compile_depends_stamp = self.target.actions_stamp or compile_depends
470
+
471
+ # Write out the compilation steps, if any.
472
+ link_deps = []
473
+ try:
474
+ sources = extra_sources + spec.get("sources", [])
475
+ except TypeError:
476
+ print("extra_sources: ", str(extra_sources))
477
+ print('spec.get("sources"): ', str(spec.get("sources")))
478
+ raise
479
+ if sources:
480
+ if self.flavor == "mac" and len(self.archs) > 1:
481
+ # Write subninja file containing compile and link commands scoped to
482
+ # a single arch if a fat binary is being built.
483
+ for arch in self.archs:
484
+ self.ninja.subninja(self._SubninjaNameForArch(arch))
485
+
486
+ pch = None
487
+ if self.flavor == "win":
488
+ gyp.msvs_emulation.VerifyMissingSources(
489
+ sources, self.abs_build_dir, generator_flags, self.GypPathToNinja
490
+ )
491
+ pch = gyp.msvs_emulation.PrecompiledHeader(
492
+ self.msvs_settings,
493
+ config_name,
494
+ self.GypPathToNinja,
495
+ self.GypPathToUniqueOutput,
496
+ self.obj_ext,
497
+ )
498
+ else:
499
+ pch = gyp.xcode_emulation.MacPrefixHeader(
500
+ self.xcode_settings,
501
+ self.GypPathToNinja,
502
+ lambda path, lang: self.GypPathToUniqueOutput(path + "-" + lang),
503
+ )
504
+ link_deps = self.WriteSources(
505
+ self.ninja,
506
+ config_name,
507
+ config,
508
+ sources,
509
+ compile_depends_stamp,
510
+ pch,
511
+ spec,
512
+ )
513
+ # Some actions/rules output 'sources' that are already object files.
514
+ obj_outputs = [f for f in sources if f.endswith(self.obj_ext)]
515
+ if obj_outputs:
516
+ if self.flavor != "mac" or len(self.archs) == 1:
517
+ link_deps += [self.GypPathToNinja(o) for o in obj_outputs]
518
+ else:
519
+ print(
520
+ "Warning: Actions/rules writing object files don't work with "
521
+ "multiarch targets, dropping. (target %s)" % spec["target_name"]
522
+ )
523
+ elif self.flavor == "mac" and len(self.archs) > 1:
524
+ link_deps = collections.defaultdict(list)
525
+
526
+ compile_deps = self.target.actions_stamp or actions_depends
527
+ if self.flavor == "win" and self.target.type == "static_library":
528
+ self.target.component_objs = link_deps
529
+ self.target.compile_deps = compile_deps
530
+
531
+ # Write out a link step, if needed.
532
+ output = None
533
+ is_empty_bundle = not link_deps and not mac_bundle_depends
534
+ if link_deps or self.target.actions_stamp or actions_depends:
535
+ output = self.WriteTarget(
536
+ spec, config_name, config, link_deps, compile_deps
537
+ )
538
+ if self.is_mac_bundle:
539
+ mac_bundle_depends.append(output)
540
+
541
+ # Bundle all of the above together, if needed.
542
+ if self.is_mac_bundle:
543
+ output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle)
544
+
545
+ if not output:
546
+ return None
547
+
548
+ assert self.target.FinalOutput(), output
549
+ return self.target
550
+
551
+ def _WinIdlRule(self, source, prebuild, outputs):
552
+ """Handle the implicit VS .idl rule for one source file. Fills |outputs|
553
+ with files that are generated."""
554
+ outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData(
555
+ source, self.config_name
556
+ )
557
+ outdir = self.GypPathToNinja(outdir)
558
+
559
+ def fix_path(path, rel=None):
560
+ path = os.path.join(outdir, path)
561
+ dirname, basename = os.path.split(source)
562
+ root, ext = os.path.splitext(basename)
563
+ path = self.ExpandRuleVariables(path, root, dirname, source, ext, basename)
564
+ if rel:
565
+ path = os.path.relpath(path, rel)
566
+ return path
567
+
568
+ vars = [(name, fix_path(value, outdir)) for name, value in vars]
569
+ output = [fix_path(p) for p in output]
570
+ vars.append(("outdir", outdir))
571
+ vars.append(("idlflags", flags))
572
+ input = self.GypPathToNinja(source)
573
+ self.ninja.build(output, "idl", input, variables=vars, order_only=prebuild)
574
+ outputs.extend(output)
575
+
576
+ def WriteWinIdlFiles(self, spec, prebuild):
577
+ """Writes rules to match MSVS's implicit idl handling."""
578
+ assert self.flavor == "win"
579
+ if self.msvs_settings.HasExplicitIdlRulesOrActions(spec):
580
+ return []
581
+ outputs = []
582
+ for source in filter(lambda x: x.endswith(".idl"), spec["sources"]):
583
+ self._WinIdlRule(source, prebuild, outputs)
584
+ return outputs
585
+
586
+ def WriteActionsRulesCopies(
587
+ self, spec, extra_sources, prebuild, mac_bundle_depends
588
+ ):
589
+ """Write out the Actions, Rules, and Copies steps. Return a path
590
+ representing the outputs of these steps."""
591
+ outputs = []
592
+ if self.is_mac_bundle:
593
+ mac_bundle_resources = spec.get("mac_bundle_resources", [])[:]
594
+ else:
595
+ mac_bundle_resources = []
596
+ extra_mac_bundle_resources = []
597
+
598
+ if "actions" in spec:
599
+ outputs += self.WriteActions(
600
+ spec["actions"], extra_sources, prebuild, extra_mac_bundle_resources
601
+ )
602
+ if "rules" in spec:
603
+ outputs += self.WriteRules(
604
+ spec["rules"],
605
+ extra_sources,
606
+ prebuild,
607
+ mac_bundle_resources,
608
+ extra_mac_bundle_resources,
609
+ )
610
+ if "copies" in spec:
611
+ outputs += self.WriteCopies(spec["copies"], prebuild, mac_bundle_depends)
612
+
613
+ if "sources" in spec and self.flavor == "win":
614
+ outputs += self.WriteWinIdlFiles(spec, prebuild)
615
+
616
+ if self.xcode_settings and self.xcode_settings.IsIosFramework():
617
+ self.WriteiOSFrameworkHeaders(spec, outputs, prebuild)
618
+
619
+ stamp = self.WriteCollapsedDependencies("actions_rules_copies", outputs)
620
+
621
+ if self.is_mac_bundle:
622
+ xcassets = self.WriteMacBundleResources(
623
+ extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends
624
+ )
625
+ partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends)
626
+ self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends)
627
+
628
+ return stamp
629
+
630
+ def GenerateDescription(self, verb, message, fallback):
631
+ """Generate and return a description of a build step.
632
+
633
+ |verb| is the short summary, e.g. ACTION or RULE.
634
+ |message| is a hand-written description, or None if not available.
635
+ |fallback| is the gyp-level name of the step, usable as a fallback.
636
+ """
637
+ if self.toolset != "target":
638
+ verb += "(%s)" % self.toolset
639
+ if message:
640
+ return f"{verb} {self.ExpandSpecial(message)}"
641
+ else:
642
+ return f"{verb} {self.name}: {fallback}"
643
+
644
+ def WriteActions(
645
+ self, actions, extra_sources, prebuild, extra_mac_bundle_resources
646
+ ):
647
+ # Actions cd into the base directory.
648
+ env = self.GetToolchainEnv()
649
+ all_outputs = []
650
+ for action in actions:
651
+ # First write out a rule for the action.
652
+ name = "{}_{}".format(action["action_name"], self.hash_for_rules)
653
+ description = self.GenerateDescription(
654
+ "ACTION", action.get("message", None), name
655
+ )
656
+ win_shell_flags = (
657
+ self.msvs_settings.GetRuleShellFlags(action)
658
+ if self.flavor == "win"
659
+ else None
660
+ )
661
+ args = action["action"]
662
+ depfile = action.get("depfile", None)
663
+ if depfile:
664
+ depfile = self.ExpandSpecial(depfile, self.base_to_build)
665
+ pool = "console" if int(action.get("ninja_use_console", 0)) else None
666
+ rule_name, _ = self.WriteNewNinjaRule(
667
+ name, args, description, win_shell_flags, env, pool, depfile=depfile
668
+ )
669
+
670
+ inputs = [self.GypPathToNinja(i, env) for i in action["inputs"]]
671
+ if int(action.get("process_outputs_as_sources", False)):
672
+ extra_sources += action["outputs"]
673
+ if int(action.get("process_outputs_as_mac_bundle_resources", False)):
674
+ extra_mac_bundle_resources += action["outputs"]
675
+ outputs = [self.GypPathToNinja(o, env) for o in action["outputs"]]
676
+
677
+ # Then write out an edge using the rule.
678
+ self.ninja.build(outputs, rule_name, inputs, order_only=prebuild)
679
+ all_outputs += outputs
680
+
681
+ self.ninja.newline()
682
+
683
+ return all_outputs
684
+
685
+ def WriteRules(
686
+ self,
687
+ rules,
688
+ extra_sources,
689
+ prebuild,
690
+ mac_bundle_resources,
691
+ extra_mac_bundle_resources,
692
+ ):
693
+ env = self.GetToolchainEnv()
694
+ all_outputs = []
695
+ for rule in rules:
696
+ # Skip a rule with no action and no inputs.
697
+ if "action" not in rule and not rule.get("rule_sources", []):
698
+ continue
699
+
700
+ # First write out a rule for the rule action.
701
+ name = "{}_{}".format(rule["rule_name"], self.hash_for_rules)
702
+
703
+ args = rule["action"]
704
+ description = self.GenerateDescription(
705
+ "RULE",
706
+ rule.get("message", None),
707
+ ("%s " + generator_default_variables["RULE_INPUT_PATH"]) % name,
708
+ )
709
+ win_shell_flags = (
710
+ self.msvs_settings.GetRuleShellFlags(rule)
711
+ if self.flavor == "win"
712
+ else None
713
+ )
714
+ pool = "console" if int(rule.get("ninja_use_console", 0)) else None
715
+ rule_name, args = self.WriteNewNinjaRule(
716
+ name, args, description, win_shell_flags, env, pool
717
+ )
718
+
719
+ # TODO: if the command references the outputs directly, we should
720
+ # simplify it to just use $out.
721
+
722
+ # Rules can potentially make use of some special variables which
723
+ # must vary per source file.
724
+ # Compute the list of variables we'll need to provide.
725
+ special_locals = ("source", "root", "dirname", "ext", "name")
726
+ needed_variables = {"source"}
727
+ for argument in args:
728
+ for var in special_locals:
729
+ if "${%s}" % var in argument:
730
+ needed_variables.add(var)
731
+ needed_variables = sorted(needed_variables)
732
+
733
+ def cygwin_munge(path):
734
+ # pylint: disable=cell-var-from-loop
735
+ if win_shell_flags and win_shell_flags.cygwin:
736
+ return path.replace("\\", "/")
737
+ return path
738
+
739
+ inputs = [self.GypPathToNinja(i, env) for i in rule.get("inputs", [])]
740
+
741
+ # If there are n source files matching the rule, and m additional rule
742
+ # inputs, then adding 'inputs' to each build edge written below will
743
+ # write m * n inputs. Collapsing reduces this to m + n.
744
+ sources = rule.get("rule_sources", [])
745
+ num_inputs = len(inputs)
746
+ if prebuild:
747
+ num_inputs += 1
748
+ if num_inputs > 2 and len(sources) > 2:
749
+ inputs = [
750
+ self.WriteCollapsedDependencies(
751
+ rule["rule_name"], inputs, order_only=prebuild
752
+ )
753
+ ]
754
+ prebuild = []
755
+
756
+ # For each source file, write an edge that generates all the outputs.
757
+ for source in sources:
758
+ source = os.path.normpath(source)
759
+ dirname, basename = os.path.split(source)
760
+ root, ext = os.path.splitext(basename)
761
+
762
+ # Gather the list of inputs and outputs, expanding $vars if possible.
763
+ outputs = [
764
+ self.ExpandRuleVariables(o, root, dirname, source, ext, basename)
765
+ for o in rule["outputs"]
766
+ ]
767
+
768
+ if int(rule.get("process_outputs_as_sources", False)):
769
+ extra_sources += outputs
770
+
771
+ was_mac_bundle_resource = source in mac_bundle_resources
772
+ if was_mac_bundle_resource or int(
773
+ rule.get("process_outputs_as_mac_bundle_resources", False)
774
+ ):
775
+ extra_mac_bundle_resources += outputs
776
+ # Note: This is n_resources * n_outputs_in_rule.
777
+ # Put to-be-removed items in a set and
778
+ # remove them all in a single pass
779
+ # if this becomes a performance issue.
780
+ if was_mac_bundle_resource:
781
+ mac_bundle_resources.remove(source)
782
+
783
+ extra_bindings = []
784
+ for var in needed_variables:
785
+ if var == "root":
786
+ extra_bindings.append(("root", cygwin_munge(root)))
787
+ elif var == "dirname":
788
+ # '$dirname' is a parameter to the rule action, which means
789
+ # it shouldn't be converted to a Ninja path. But we don't
790
+ # want $!PRODUCT_DIR in there either.
791
+ dirname_expanded = self.ExpandSpecial(
792
+ dirname, self.base_to_build
793
+ )
794
+ extra_bindings.append(
795
+ ("dirname", cygwin_munge(dirname_expanded))
796
+ )
797
+ elif var == "source":
798
+ # '$source' is a parameter to the rule action, which means
799
+ # it shouldn't be converted to a Ninja path. But we don't
800
+ # want $!PRODUCT_DIR in there either.
801
+ source_expanded = self.ExpandSpecial(source, self.base_to_build)
802
+ extra_bindings.append(("source", cygwin_munge(source_expanded)))
803
+ elif var == "ext":
804
+ extra_bindings.append(("ext", ext))
805
+ elif var == "name":
806
+ extra_bindings.append(("name", cygwin_munge(basename)))
807
+ else:
808
+ assert var is None, repr(var)
809
+
810
+ outputs = [self.GypPathToNinja(o, env) for o in outputs]
811
+ if self.flavor == "win":
812
+ # WriteNewNinjaRule uses unique_name to create a rsp file on win.
813
+ extra_bindings.append(
814
+ ("unique_name", hashlib.md5(outputs[0]).hexdigest())
815
+ )
816
+
817
+ self.ninja.build(
818
+ outputs,
819
+ rule_name,
820
+ self.GypPathToNinja(source),
821
+ implicit=inputs,
822
+ order_only=prebuild,
823
+ variables=extra_bindings,
824
+ )
825
+
826
+ all_outputs.extend(outputs)
827
+
828
+ return all_outputs
829
+
830
+ def WriteCopies(self, copies, prebuild, mac_bundle_depends):
831
+ outputs = []
832
+ if self.xcode_settings:
833
+ extra_env = self.xcode_settings.GetPerTargetSettings()
834
+ env = self.GetToolchainEnv(additional_settings=extra_env)
835
+ else:
836
+ env = self.GetToolchainEnv()
837
+ for to_copy in copies:
838
+ for path in to_copy["files"]:
839
+ # Normalize the path so trailing slashes don't confuse us.
840
+ path = os.path.normpath(path)
841
+ basename = os.path.split(path)[1]
842
+ src = self.GypPathToNinja(path, env)
843
+ dst = self.GypPathToNinja(
844
+ os.path.join(to_copy["destination"], basename), env
845
+ )
846
+ outputs += self.ninja.build(dst, "copy", src, order_only=prebuild)
847
+ if self.is_mac_bundle:
848
+ # gyp has mac_bundle_resources to copy things into a bundle's
849
+ # Resources folder, but there's no built-in way to copy files
850
+ # to other places in the bundle.
851
+ # Hence, some targets use copies for this.
852
+ # Check if this file is copied into the current bundle,
853
+ # and if so add it to the bundle depends so
854
+ # that dependent targets get rebuilt if the copy input changes.
855
+ if dst.startswith(
856
+ self.xcode_settings.GetBundleContentsFolderPath()
857
+ ):
858
+ mac_bundle_depends.append(dst)
859
+
860
+ return outputs
861
+
862
+ def WriteiOSFrameworkHeaders(self, spec, outputs, prebuild):
863
+ """Prebuild steps to generate hmap files and copy headers to destination."""
864
+ framework = self.ComputeMacBundleOutput()
865
+ all_sources = spec["sources"]
866
+ copy_headers = spec["mac_framework_headers"]
867
+ output = self.GypPathToUniqueOutput("headers.hmap")
868
+ self.xcode_settings.header_map_path = output
869
+ all_headers = map(
870
+ self.GypPathToNinja, filter(lambda x: x.endswith(".h"), all_sources)
871
+ )
872
+ variables = [
873
+ ("framework", framework),
874
+ ("copy_headers", map(self.GypPathToNinja, copy_headers)),
875
+ ]
876
+ outputs.extend(
877
+ self.ninja.build(
878
+ output,
879
+ "compile_ios_framework_headers",
880
+ all_headers,
881
+ variables=variables,
882
+ order_only=prebuild,
883
+ )
884
+ )
885
+
886
+ def WriteMacBundleResources(self, resources, bundle_depends):
887
+ """Writes ninja edges for 'mac_bundle_resources'."""
888
+ xcassets = []
889
+
890
+ extra_env = self.xcode_settings.GetPerTargetSettings()
891
+ env = self.GetSortedXcodeEnv(additional_settings=extra_env)
892
+ env = self.ComputeExportEnvString(env)
893
+ isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
894
+
895
+ for output, res in gyp.xcode_emulation.GetMacBundleResources(
896
+ generator_default_variables["PRODUCT_DIR"],
897
+ self.xcode_settings,
898
+ map(self.GypPathToNinja, resources),
899
+ ):
900
+ output = self.ExpandSpecial(output)
901
+ if os.path.splitext(output)[-1] != ".xcassets":
902
+ self.ninja.build(
903
+ output,
904
+ "mac_tool",
905
+ res,
906
+ variables=[
907
+ ("mactool_cmd", "copy-bundle-resource"),
908
+ ("env", env),
909
+ ("binary", isBinary),
910
+ ],
911
+ )
912
+ bundle_depends.append(output)
913
+ else:
914
+ xcassets.append(res)
915
+ return xcassets
916
+
917
+ def WriteMacXCassets(self, xcassets, bundle_depends):
918
+ """Writes ninja edges for 'mac_bundle_resources' .xcassets files.
919
+
920
+ This add an invocation of 'actool' via the 'mac_tool.py' helper script.
921
+ It assumes that the assets catalogs define at least one imageset and
922
+ thus an Assets.car file will be generated in the application resources
923
+ directory. If this is not the case, then the build will probably be done
924
+ at each invocation of ninja."""
925
+ if not xcassets:
926
+ return
927
+
928
+ extra_arguments = {}
929
+ settings_to_arg = {
930
+ "XCASSETS_APP_ICON": "app-icon",
931
+ "XCASSETS_LAUNCH_IMAGE": "launch-image",
932
+ }
933
+ settings = self.xcode_settings.xcode_settings[self.config_name]
934
+ for settings_key, arg_name in settings_to_arg.items():
935
+ value = settings.get(settings_key)
936
+ if value:
937
+ extra_arguments[arg_name] = value
938
+
939
+ partial_info_plist = None
940
+ if extra_arguments:
941
+ partial_info_plist = self.GypPathToUniqueOutput(
942
+ "assetcatalog_generated_info.plist"
943
+ )
944
+ extra_arguments["output-partial-info-plist"] = partial_info_plist
945
+
946
+ outputs = []
947
+ outputs.append(
948
+ os.path.join(self.xcode_settings.GetBundleResourceFolder(), "Assets.car")
949
+ )
950
+ if partial_info_plist:
951
+ outputs.append(partial_info_plist)
952
+
953
+ keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor)
954
+ extra_env = self.xcode_settings.GetPerTargetSettings()
955
+ env = self.GetSortedXcodeEnv(additional_settings=extra_env)
956
+ env = self.ComputeExportEnvString(env)
957
+
958
+ bundle_depends.extend(
959
+ self.ninja.build(
960
+ outputs,
961
+ "compile_xcassets",
962
+ xcassets,
963
+ variables=[("env", env), ("keys", keys)],
964
+ )
965
+ )
966
+ return partial_info_plist
967
+
968
+ def WriteMacInfoPlist(self, partial_info_plist, bundle_depends):
969
+ """Write build rules for bundle Info.plist files."""
970
+ info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
971
+ generator_default_variables["PRODUCT_DIR"],
972
+ self.xcode_settings,
973
+ self.GypPathToNinja,
974
+ )
975
+ if not info_plist:
976
+ return
977
+ out = self.ExpandSpecial(out)
978
+ if defines:
979
+ # Create an intermediate file to store preprocessed results.
980
+ intermediate_plist = self.GypPathToUniqueOutput(
981
+ os.path.basename(info_plist)
982
+ )
983
+ defines = " ".join([Define(d, self.flavor) for d in defines])
984
+ info_plist = self.ninja.build(
985
+ intermediate_plist,
986
+ "preprocess_infoplist",
987
+ info_plist,
988
+ variables=[("defines", defines)],
989
+ )
990
+
991
+ env = self.GetSortedXcodeEnv(additional_settings=extra_env)
992
+ env = self.ComputeExportEnvString(env)
993
+
994
+ if partial_info_plist:
995
+ intermediate_plist = self.GypPathToUniqueOutput("merged_info.plist")
996
+ info_plist = self.ninja.build(
997
+ intermediate_plist, "merge_infoplist", [partial_info_plist, info_plist]
998
+ )
999
+
1000
+ keys = self.xcode_settings.GetExtraPlistItems(self.config_name)
1001
+ keys = QuoteShellArgument(json.dumps(keys), self.flavor)
1002
+ isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
1003
+ self.ninja.build(
1004
+ out,
1005
+ "copy_infoplist",
1006
+ info_plist,
1007
+ variables=[("env", env), ("keys", keys), ("binary", isBinary)],
1008
+ )
1009
+ bundle_depends.append(out)
1010
+
1011
+ def WriteSources(
1012
+ self,
1013
+ ninja_file,
1014
+ config_name,
1015
+ config,
1016
+ sources,
1017
+ predepends,
1018
+ precompiled_header,
1019
+ spec,
1020
+ ):
1021
+ """Write build rules to compile all of |sources|."""
1022
+ if self.toolset == "host":
1023
+ self.ninja.variable("ar", "$ar_host")
1024
+ self.ninja.variable("cc", "$cc_host")
1025
+ self.ninja.variable("cxx", "$cxx_host")
1026
+ self.ninja.variable("ld", "$ld_host")
1027
+ self.ninja.variable("ldxx", "$ldxx_host")
1028
+ self.ninja.variable("nm", "$nm_host")
1029
+ self.ninja.variable("readelf", "$readelf_host")
1030
+
1031
+ if self.flavor != "mac" or len(self.archs) == 1:
1032
+ return self.WriteSourcesForArch(
1033
+ self.ninja,
1034
+ config_name,
1035
+ config,
1036
+ sources,
1037
+ predepends,
1038
+ precompiled_header,
1039
+ spec,
1040
+ )
1041
+ else:
1042
+ return {
1043
+ arch: self.WriteSourcesForArch(
1044
+ self.arch_subninjas[arch],
1045
+ config_name,
1046
+ config,
1047
+ sources,
1048
+ predepends,
1049
+ precompiled_header,
1050
+ spec,
1051
+ arch=arch,
1052
+ )
1053
+ for arch in self.archs
1054
+ }
1055
+
1056
+ def WriteSourcesForArch(
1057
+ self,
1058
+ ninja_file,
1059
+ config_name,
1060
+ config,
1061
+ sources,
1062
+ predepends,
1063
+ precompiled_header,
1064
+ spec,
1065
+ arch=None,
1066
+ ):
1067
+ """Write build rules to compile all of |sources|."""
1068
+
1069
+ extra_defines = []
1070
+ if self.flavor == "mac":
1071
+ cflags = self.xcode_settings.GetCflags(config_name, arch=arch)
1072
+ cflags_c = self.xcode_settings.GetCflagsC(config_name)
1073
+ cflags_cc = self.xcode_settings.GetCflagsCC(config_name)
1074
+ cflags_objc = ["$cflags_c"] + self.xcode_settings.GetCflagsObjC(config_name)
1075
+ cflags_objcc = ["$cflags_cc"] + self.xcode_settings.GetCflagsObjCC(
1076
+ config_name
1077
+ )
1078
+ elif self.flavor == "win":
1079
+ asmflags = self.msvs_settings.GetAsmflags(config_name)
1080
+ cflags = self.msvs_settings.GetCflags(config_name)
1081
+ cflags_c = self.msvs_settings.GetCflagsC(config_name)
1082
+ cflags_cc = self.msvs_settings.GetCflagsCC(config_name)
1083
+ extra_defines = self.msvs_settings.GetComputedDefines(config_name)
1084
+ # See comment at cc_command for why there's two .pdb files.
1085
+ pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName(
1086
+ config_name, self.ExpandSpecial
1087
+ )
1088
+ if not pdbpath_c:
1089
+ obj = "obj"
1090
+ if self.toolset != "target":
1091
+ obj += "." + self.toolset
1092
+ pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name))
1093
+ pdbpath_c = pdbpath + ".c.pdb"
1094
+ pdbpath_cc = pdbpath + ".cc.pdb"
1095
+ self.WriteVariableList(ninja_file, "pdbname_c", [pdbpath_c])
1096
+ self.WriteVariableList(ninja_file, "pdbname_cc", [pdbpath_cc])
1097
+ self.WriteVariableList(ninja_file, "pchprefix", [self.name])
1098
+ else:
1099
+ cflags = config.get("cflags", [])
1100
+ cflags_c = config.get("cflags_c", [])
1101
+ cflags_cc = config.get("cflags_cc", [])
1102
+
1103
+ # Respect environment variables related to build, but target-specific
1104
+ # flags can still override them.
1105
+ if self.toolset == "target":
1106
+ cflags_c = (
1107
+ os.environ.get("CPPFLAGS", "").split()
1108
+ + os.environ.get("CFLAGS", "").split()
1109
+ + cflags_c
1110
+ )
1111
+ cflags_cc = (
1112
+ os.environ.get("CPPFLAGS", "").split()
1113
+ + os.environ.get("CXXFLAGS", "").split()
1114
+ + cflags_cc
1115
+ )
1116
+ elif self.toolset == "host":
1117
+ cflags_c = (
1118
+ os.environ.get("CPPFLAGS_host", "").split()
1119
+ + os.environ.get("CFLAGS_host", "").split()
1120
+ + cflags_c
1121
+ )
1122
+ cflags_cc = (
1123
+ os.environ.get("CPPFLAGS_host", "").split()
1124
+ + os.environ.get("CXXFLAGS_host", "").split()
1125
+ + cflags_cc
1126
+ )
1127
+
1128
+ defines = config.get("defines", []) + extra_defines
1129
+ self.WriteVariableList(
1130
+ ninja_file, "defines", [Define(d, self.flavor) for d in defines]
1131
+ )
1132
+ if self.flavor == "win":
1133
+ self.WriteVariableList(
1134
+ ninja_file, "asmflags", map(self.ExpandSpecial, asmflags)
1135
+ )
1136
+ self.WriteVariableList(
1137
+ ninja_file,
1138
+ "rcflags",
1139
+ [
1140
+ QuoteShellArgument(self.ExpandSpecial(f), self.flavor)
1141
+ for f in self.msvs_settings.GetRcflags(
1142
+ config_name, self.GypPathToNinja
1143
+ )
1144
+ ],
1145
+ )
1146
+
1147
+ include_dirs = config.get("include_dirs", [])
1148
+
1149
+ env = self.GetToolchainEnv()
1150
+ if self.flavor == "win":
1151
+ include_dirs = self.msvs_settings.AdjustIncludeDirs(
1152
+ include_dirs, config_name
1153
+ )
1154
+ self.WriteVariableList(
1155
+ ninja_file,
1156
+ "includes",
1157
+ [
1158
+ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor)
1159
+ for i in include_dirs
1160
+ ],
1161
+ )
1162
+
1163
+ if self.flavor == "win":
1164
+ midl_include_dirs = config.get("midl_include_dirs", [])
1165
+ midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs(
1166
+ midl_include_dirs, config_name
1167
+ )
1168
+ self.WriteVariableList(
1169
+ ninja_file,
1170
+ "midl_includes",
1171
+ [
1172
+ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor)
1173
+ for i in midl_include_dirs
1174
+ ],
1175
+ )
1176
+
1177
+ pch_commands = precompiled_header.GetPchBuildCommands(arch)
1178
+ if self.flavor == "mac":
1179
+ # Most targets use no precompiled headers, so only write these if needed.
1180
+ for ext, var in [
1181
+ ("c", "cflags_pch_c"),
1182
+ ("cc", "cflags_pch_cc"),
1183
+ ("m", "cflags_pch_objc"),
1184
+ ("mm", "cflags_pch_objcc"),
1185
+ ]:
1186
+ include = precompiled_header.GetInclude(ext, arch)
1187
+ if include:
1188
+ ninja_file.variable(var, include)
1189
+
1190
+ arflags = config.get("arflags", [])
1191
+
1192
+ self.WriteVariableList(ninja_file, "cflags", map(self.ExpandSpecial, cflags))
1193
+ self.WriteVariableList(
1194
+ ninja_file, "cflags_c", map(self.ExpandSpecial, cflags_c)
1195
+ )
1196
+ self.WriteVariableList(
1197
+ ninja_file, "cflags_cc", map(self.ExpandSpecial, cflags_cc)
1198
+ )
1199
+ if self.flavor == "mac":
1200
+ self.WriteVariableList(
1201
+ ninja_file, "cflags_objc", map(self.ExpandSpecial, cflags_objc)
1202
+ )
1203
+ self.WriteVariableList(
1204
+ ninja_file, "cflags_objcc", map(self.ExpandSpecial, cflags_objcc)
1205
+ )
1206
+ self.WriteVariableList(ninja_file, "arflags", map(self.ExpandSpecial, arflags))
1207
+ ninja_file.newline()
1208
+ outputs = []
1209
+ has_rc_source = False
1210
+ for source in sources:
1211
+ filename, ext = os.path.splitext(source)
1212
+ ext = ext[1:]
1213
+ obj_ext = self.obj_ext
1214
+ if ext in ("cc", "cpp", "cxx"):
1215
+ command = "cxx"
1216
+ self.target.uses_cpp = True
1217
+ elif ext == "c" or (ext == "S" and self.flavor != "win"):
1218
+ command = "cc"
1219
+ elif ext == "s" and self.flavor != "win": # Doesn't generate .o.d files.
1220
+ command = "cc_s"
1221
+ elif (
1222
+ self.flavor == "win"
1223
+ and ext in ("asm", "S")
1224
+ and not self.msvs_settings.HasExplicitAsmRules(spec)
1225
+ ):
1226
+ command = "asm"
1227
+ # Add the _asm suffix as msvs is capable of handling .cc and
1228
+ # .asm files of the same name without collision.
1229
+ obj_ext = "_asm.obj"
1230
+ elif self.flavor == "mac" and ext == "m":
1231
+ command = "objc"
1232
+ elif self.flavor == "mac" and ext == "mm":
1233
+ command = "objcxx"
1234
+ self.target.uses_cpp = True
1235
+ elif self.flavor == "win" and ext == "rc":
1236
+ command = "rc"
1237
+ obj_ext = ".res"
1238
+ has_rc_source = True
1239
+ else:
1240
+ # Ignore unhandled extensions.
1241
+ continue
1242
+ input = self.GypPathToNinja(source)
1243
+ output = self.GypPathToUniqueOutput(filename + obj_ext)
1244
+ if arch is not None:
1245
+ output = AddArch(output, arch)
1246
+ implicit = precompiled_header.GetObjDependencies([input], [output], arch)
1247
+ variables = []
1248
+ if self.flavor == "win":
1249
+ variables, output, implicit = precompiled_header.GetFlagsModifications(
1250
+ input,
1251
+ output,
1252
+ implicit,
1253
+ command,
1254
+ cflags_c,
1255
+ cflags_cc,
1256
+ self.ExpandSpecial,
1257
+ )
1258
+ ninja_file.build(
1259
+ output,
1260
+ command,
1261
+ input,
1262
+ implicit=[gch for _, _, gch in implicit],
1263
+ order_only=predepends,
1264
+ variables=variables,
1265
+ )
1266
+ outputs.append(output)
1267
+
1268
+ if has_rc_source:
1269
+ resource_include_dirs = config.get("resource_include_dirs", include_dirs)
1270
+ self.WriteVariableList(
1271
+ ninja_file,
1272
+ "resource_includes",
1273
+ [
1274
+ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor)
1275
+ for i in resource_include_dirs
1276
+ ],
1277
+ )
1278
+
1279
+ self.WritePchTargets(ninja_file, pch_commands)
1280
+
1281
+ ninja_file.newline()
1282
+ return outputs
1283
+
1284
+ def WritePchTargets(self, ninja_file, pch_commands):
1285
+ """Writes ninja rules to compile prefix headers."""
1286
+ if not pch_commands:
1287
+ return
1288
+
1289
+ for gch, lang_flag, lang, input in pch_commands:
1290
+ var_name = {
1291
+ "c": "cflags_pch_c",
1292
+ "cc": "cflags_pch_cc",
1293
+ "m": "cflags_pch_objc",
1294
+ "mm": "cflags_pch_objcc",
1295
+ }[lang]
1296
+
1297
+ map = {
1298
+ "c": "cc",
1299
+ "cc": "cxx",
1300
+ "m": "objc",
1301
+ "mm": "objcxx",
1302
+ }
1303
+ cmd = map.get(lang)
1304
+ ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)])
1305
+
1306
+ def WriteLink(self, spec, config_name, config, link_deps, compile_deps):
1307
+ """Write out a link step. Fills out target.binary. """
1308
+ if self.flavor != "mac" or len(self.archs) == 1:
1309
+ return self.WriteLinkForArch(
1310
+ self.ninja, spec, config_name, config, link_deps, compile_deps
1311
+ )
1312
+ else:
1313
+ output = self.ComputeOutput(spec)
1314
+ inputs = [
1315
+ self.WriteLinkForArch(
1316
+ self.arch_subninjas[arch],
1317
+ spec,
1318
+ config_name,
1319
+ config,
1320
+ link_deps[arch],
1321
+ compile_deps,
1322
+ arch=arch,
1323
+ )
1324
+ for arch in self.archs
1325
+ ]
1326
+ extra_bindings = []
1327
+ build_output = output
1328
+ if not self.is_mac_bundle:
1329
+ self.AppendPostbuildVariable(extra_bindings, spec, output, output)
1330
+
1331
+ # TODO(yyanagisawa): more work needed to fix:
1332
+ # https://code.google.com/p/gyp/issues/detail?id=411
1333
+ if (
1334
+ spec["type"] in ("shared_library", "loadable_module")
1335
+ and not self.is_mac_bundle
1336
+ ):
1337
+ extra_bindings.append(("lib", output))
1338
+ self.ninja.build(
1339
+ [output, output + ".TOC"],
1340
+ "solipo",
1341
+ inputs,
1342
+ variables=extra_bindings,
1343
+ )
1344
+ else:
1345
+ self.ninja.build(build_output, "lipo", inputs, variables=extra_bindings)
1346
+ return output
1347
+
1348
+ def WriteLinkForArch(
1349
+ self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None
1350
+ ):
1351
+ """Write out a link step. Fills out target.binary. """
1352
+ command = {
1353
+ "executable": "link",
1354
+ "loadable_module": "solink_module",
1355
+ "shared_library": "solink",
1356
+ }[spec["type"]]
1357
+ command_suffix = ""
1358
+
1359
+ implicit_deps = set()
1360
+ solibs = set()
1361
+ order_deps = set()
1362
+
1363
+ if compile_deps:
1364
+ # Normally, the compiles of the target already depend on compile_deps,
1365
+ # but a shared_library target might have no sources and only link together
1366
+ # a few static_library deps, so the link step also needs to depend
1367
+ # on compile_deps to make sure actions in the shared_library target
1368
+ # get run before the link.
1369
+ order_deps.add(compile_deps)
1370
+
1371
+ if "dependencies" in spec:
1372
+ # Two kinds of dependencies:
1373
+ # - Linkable dependencies (like a .a or a .so): add them to the link line.
1374
+ # - Non-linkable dependencies (like a rule that generates a file
1375
+ # and writes a stamp file): add them to implicit_deps
1376
+ extra_link_deps = set()
1377
+ for dep in spec["dependencies"]:
1378
+ target = self.target_outputs.get(dep)
1379
+ if not target:
1380
+ continue
1381
+ linkable = target.Linkable()
1382
+ if linkable:
1383
+ new_deps = []
1384
+ if (
1385
+ self.flavor == "win"
1386
+ and target.component_objs
1387
+ and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)
1388
+ ):
1389
+ new_deps = target.component_objs
1390
+ if target.compile_deps:
1391
+ order_deps.add(target.compile_deps)
1392
+ elif self.flavor == "win" and target.import_lib:
1393
+ new_deps = [target.import_lib]
1394
+ elif target.UsesToc(self.flavor):
1395
+ solibs.add(target.binary)
1396
+ implicit_deps.add(target.binary + ".TOC")
1397
+ else:
1398
+ new_deps = [target.binary]
1399
+ for new_dep in new_deps:
1400
+ if new_dep not in extra_link_deps:
1401
+ extra_link_deps.add(new_dep)
1402
+ link_deps.append(new_dep)
1403
+
1404
+ final_output = target.FinalOutput()
1405
+ if not linkable or final_output != target.binary:
1406
+ implicit_deps.add(final_output)
1407
+
1408
+ extra_bindings = []
1409
+ if self.target.uses_cpp and self.flavor != "win":
1410
+ extra_bindings.append(("ld", "$ldxx"))
1411
+
1412
+ output = self.ComputeOutput(spec, arch)
1413
+ if arch is None and not self.is_mac_bundle:
1414
+ self.AppendPostbuildVariable(extra_bindings, spec, output, output)
1415
+
1416
+ is_executable = spec["type"] == "executable"
1417
+ # The ldflags config key is not used on mac or win. On those platforms
1418
+ # linker flags are set via xcode_settings and msvs_settings, respectively.
1419
+ if self.toolset == "target":
1420
+ env_ldflags = os.environ.get("LDFLAGS", "").split()
1421
+ elif self.toolset == "host":
1422
+ env_ldflags = os.environ.get("LDFLAGS_host", "").split()
1423
+
1424
+ if self.flavor == "mac":
1425
+ ldflags = self.xcode_settings.GetLdflags(
1426
+ config_name,
1427
+ self.ExpandSpecial(generator_default_variables["PRODUCT_DIR"]),
1428
+ self.GypPathToNinja,
1429
+ arch,
1430
+ )
1431
+ ldflags = env_ldflags + ldflags
1432
+ elif self.flavor == "win":
1433
+ manifest_base_name = self.GypPathToUniqueOutput(
1434
+ self.ComputeOutputFileName(spec)
1435
+ )
1436
+ (
1437
+ ldflags,
1438
+ intermediate_manifest,
1439
+ manifest_files,
1440
+ ) = self.msvs_settings.GetLdflags(
1441
+ config_name,
1442
+ self.GypPathToNinja,
1443
+ self.ExpandSpecial,
1444
+ manifest_base_name,
1445
+ output,
1446
+ is_executable,
1447
+ self.toplevel_build,
1448
+ )
1449
+ ldflags = env_ldflags + ldflags
1450
+ self.WriteVariableList(ninja_file, "manifests", manifest_files)
1451
+ implicit_deps = implicit_deps.union(manifest_files)
1452
+ if intermediate_manifest:
1453
+ self.WriteVariableList(
1454
+ ninja_file, "intermediatemanifest", [intermediate_manifest]
1455
+ )
1456
+ command_suffix = _GetWinLinkRuleNameSuffix(
1457
+ self.msvs_settings.IsEmbedManifest(config_name)
1458
+ )
1459
+ def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja)
1460
+ if def_file:
1461
+ implicit_deps.add(def_file)
1462
+ else:
1463
+ # Respect environment variables related to build, but target-specific
1464
+ # flags can still override them.
1465
+ ldflags = env_ldflags + config.get("ldflags", [])
1466
+ if is_executable and solibs:
1467
+ rpath = "lib/"
1468
+ if self.toolset != "target":
1469
+ rpath += self.toolset
1470
+ ldflags.append(r"-Wl,-rpath=\$$ORIGIN/%s" % rpath)
1471
+ else:
1472
+ ldflags.append("-Wl,-rpath=%s" % self.target_rpath)
1473
+ ldflags.append("-Wl,-rpath-link=%s" % rpath)
1474
+ self.WriteVariableList(ninja_file, "ldflags", map(self.ExpandSpecial, ldflags))
1475
+
1476
+ library_dirs = config.get("library_dirs", [])
1477
+ if self.flavor == "win":
1478
+ library_dirs = [
1479
+ self.msvs_settings.ConvertVSMacros(library_dir, config_name)
1480
+ for library_dir in library_dirs
1481
+ ]
1482
+ library_dirs = [
1483
+ "/LIBPATH:"
1484
+ + QuoteShellArgument(self.GypPathToNinja(library_dir), self.flavor)
1485
+ for library_dir in library_dirs
1486
+ ]
1487
+ else:
1488
+ library_dirs = [
1489
+ QuoteShellArgument("-L" + self.GypPathToNinja(library_dir), self.flavor)
1490
+ for library_dir in library_dirs
1491
+ ]
1492
+
1493
+ libraries = gyp.common.uniquer(
1494
+ map(self.ExpandSpecial, spec.get("libraries", []))
1495
+ )
1496
+ if self.flavor == "mac":
1497
+ libraries = self.xcode_settings.AdjustLibraries(libraries, config_name)
1498
+ elif self.flavor == "win":
1499
+ libraries = self.msvs_settings.AdjustLibraries(libraries)
1500
+
1501
+ self.WriteVariableList(ninja_file, "libs", library_dirs + libraries)
1502
+
1503
+ linked_binary = output
1504
+
1505
+ if command in ("solink", "solink_module"):
1506
+ extra_bindings.append(("soname", os.path.split(output)[1]))
1507
+ extra_bindings.append(("lib", gyp.common.EncodePOSIXShellArgument(output)))
1508
+ if self.flavor != "win":
1509
+ link_file_list = output
1510
+ if self.is_mac_bundle:
1511
+ # 'Dependency Framework.framework/Versions/A/Dependency Framework'
1512
+ # -> 'Dependency Framework.framework.rsp'
1513
+ link_file_list = self.xcode_settings.GetWrapperName()
1514
+ if arch:
1515
+ link_file_list += "." + arch
1516
+ link_file_list += ".rsp"
1517
+ # If an rspfile contains spaces, ninja surrounds the filename with
1518
+ # quotes around it and then passes it to open(), creating a file with
1519
+ # quotes in its name (and when looking for the rsp file, the name
1520
+ # makes it through bash which strips the quotes) :-/
1521
+ link_file_list = link_file_list.replace(" ", "_")
1522
+ extra_bindings.append(
1523
+ (
1524
+ "link_file_list",
1525
+ gyp.common.EncodePOSIXShellArgument(link_file_list),
1526
+ )
1527
+ )
1528
+ if self.flavor == "win":
1529
+ extra_bindings.append(("binary", output))
1530
+ if (
1531
+ "/NOENTRY" not in ldflags
1532
+ and not self.msvs_settings.GetNoImportLibrary(config_name)
1533
+ ):
1534
+ self.target.import_lib = output + ".lib"
1535
+ extra_bindings.append(
1536
+ ("implibflag", "/IMPLIB:%s" % self.target.import_lib)
1537
+ )
1538
+ pdbname = self.msvs_settings.GetPDBName(
1539
+ config_name, self.ExpandSpecial, output + ".pdb"
1540
+ )
1541
+ output = [output, self.target.import_lib]
1542
+ if pdbname:
1543
+ output.append(pdbname)
1544
+ elif not self.is_mac_bundle:
1545
+ output = [output, output + ".TOC"]
1546
+ else:
1547
+ command = command + "_notoc"
1548
+ elif self.flavor == "win":
1549
+ extra_bindings.append(("binary", output))
1550
+ pdbname = self.msvs_settings.GetPDBName(
1551
+ config_name, self.ExpandSpecial, output + ".pdb"
1552
+ )
1553
+ if pdbname:
1554
+ output = [output, pdbname]
1555
+
1556
+ if solibs:
1557
+ extra_bindings.append(
1558
+ ("solibs", gyp.common.EncodePOSIXShellList(sorted(solibs)))
1559
+ )
1560
+
1561
+ ninja_file.build(
1562
+ output,
1563
+ command + command_suffix,
1564
+ link_deps,
1565
+ implicit=sorted(implicit_deps),
1566
+ order_only=list(order_deps),
1567
+ variables=extra_bindings,
1568
+ )
1569
+ return linked_binary
1570
+
1571
+ def WriteTarget(self, spec, config_name, config, link_deps, compile_deps):
1572
+ extra_link_deps = any(
1573
+ self.target_outputs.get(dep).Linkable()
1574
+ for dep in spec.get("dependencies", [])
1575
+ if dep in self.target_outputs
1576
+ )
1577
+ if spec["type"] == "none" or (not link_deps and not extra_link_deps):
1578
+ # TODO(evan): don't call this function for 'none' target types, as
1579
+ # it doesn't do anything, and we fake out a 'binary' with a stamp file.
1580
+ self.target.binary = compile_deps
1581
+ self.target.type = "none"
1582
+ elif spec["type"] == "static_library":
1583
+ self.target.binary = self.ComputeOutput(spec)
1584
+ if (
1585
+ self.flavor not in ("ios", "mac", "netbsd", "openbsd", "win")
1586
+ and not self.is_standalone_static_library
1587
+ ):
1588
+ self.ninja.build(
1589
+ self.target.binary, "alink_thin", link_deps, order_only=compile_deps
1590
+ )
1591
+ else:
1592
+ variables = []
1593
+ if self.xcode_settings:
1594
+ libtool_flags = self.xcode_settings.GetLibtoolflags(config_name)
1595
+ if libtool_flags:
1596
+ variables.append(("libtool_flags", libtool_flags))
1597
+ if self.msvs_settings:
1598
+ libflags = self.msvs_settings.GetLibFlags(
1599
+ config_name, self.GypPathToNinja
1600
+ )
1601
+ variables.append(("libflags", libflags))
1602
+
1603
+ if self.flavor != "mac" or len(self.archs) == 1:
1604
+ self.AppendPostbuildVariable(
1605
+ variables, spec, self.target.binary, self.target.binary
1606
+ )
1607
+ self.ninja.build(
1608
+ self.target.binary,
1609
+ "alink",
1610
+ link_deps,
1611
+ order_only=compile_deps,
1612
+ variables=variables,
1613
+ )
1614
+ else:
1615
+ inputs = []
1616
+ for arch in self.archs:
1617
+ output = self.ComputeOutput(spec, arch)
1618
+ self.arch_subninjas[arch].build(
1619
+ output,
1620
+ "alink",
1621
+ link_deps[arch],
1622
+ order_only=compile_deps,
1623
+ variables=variables,
1624
+ )
1625
+ inputs.append(output)
1626
+ # TODO: It's not clear if
1627
+ # libtool_flags should be passed to the alink
1628
+ # call that combines single-arch .a files into a fat .a file.
1629
+ self.AppendPostbuildVariable(
1630
+ variables, spec, self.target.binary, self.target.binary
1631
+ )
1632
+ self.ninja.build(
1633
+ self.target.binary,
1634
+ "alink",
1635
+ inputs,
1636
+ # FIXME: test proving order_only=compile_deps isn't
1637
+ # needed.
1638
+ variables=variables,
1639
+ )
1640
+ else:
1641
+ self.target.binary = self.WriteLink(
1642
+ spec, config_name, config, link_deps, compile_deps
1643
+ )
1644
+ return self.target.binary
1645
+
1646
+ def WriteMacBundle(self, spec, mac_bundle_depends, is_empty):
1647
+ assert self.is_mac_bundle
1648
+ package_framework = spec["type"] in ("shared_library", "loadable_module")
1649
+ output = self.ComputeMacBundleOutput()
1650
+ if is_empty:
1651
+ output += ".stamp"
1652
+ variables = []
1653
+ self.AppendPostbuildVariable(
1654
+ variables,
1655
+ spec,
1656
+ output,
1657
+ self.target.binary,
1658
+ is_command_start=not package_framework,
1659
+ )
1660
+ if package_framework and not is_empty:
1661
+ if spec["type"] == "shared_library" and self.xcode_settings.isIOS:
1662
+ self.ninja.build(
1663
+ output,
1664
+ "package_ios_framework",
1665
+ mac_bundle_depends,
1666
+ variables=variables,
1667
+ )
1668
+ else:
1669
+ variables.append(("version", self.xcode_settings.GetFrameworkVersion()))
1670
+ self.ninja.build(
1671
+ output, "package_framework", mac_bundle_depends, variables=variables
1672
+ )
1673
+ else:
1674
+ self.ninja.build(output, "stamp", mac_bundle_depends, variables=variables)
1675
+ self.target.bundle = output
1676
+ return output
1677
+
1678
+ def GetToolchainEnv(self, additional_settings=None):
1679
+ """Returns the variables toolchain would set for build steps."""
1680
+ env = self.GetSortedXcodeEnv(additional_settings=additional_settings)
1681
+ if self.flavor == "win":
1682
+ env = self.GetMsvsToolchainEnv(additional_settings=additional_settings)
1683
+ return env
1684
+
1685
+ def GetMsvsToolchainEnv(self, additional_settings=None):
1686
+ """Returns the variables Visual Studio would set for build steps."""
1687
+ return self.msvs_settings.GetVSMacroEnv(
1688
+ "$!PRODUCT_DIR", config=self.config_name
1689
+ )
1690
+
1691
+ def GetSortedXcodeEnv(self, additional_settings=None):
1692
+ """Returns the variables Xcode would set for build steps."""
1693
+ assert self.abs_build_dir
1694
+ abs_build_dir = self.abs_build_dir
1695
+ return gyp.xcode_emulation.GetSortedXcodeEnv(
1696
+ self.xcode_settings,
1697
+ abs_build_dir,
1698
+ os.path.join(abs_build_dir, self.build_to_base),
1699
+ self.config_name,
1700
+ additional_settings,
1701
+ )
1702
+
1703
+ def GetSortedXcodePostbuildEnv(self):
1704
+ """Returns the variables Xcode would set for postbuild steps."""
1705
+ postbuild_settings = {}
1706
+ # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.
1707
+ # TODO(thakis): It would be nice to have some general mechanism instead.
1708
+ strip_save_file = self.xcode_settings.GetPerTargetSetting(
1709
+ "CHROMIUM_STRIP_SAVE_FILE"
1710
+ )
1711
+ if strip_save_file:
1712
+ postbuild_settings["CHROMIUM_STRIP_SAVE_FILE"] = strip_save_file
1713
+ return self.GetSortedXcodeEnv(additional_settings=postbuild_settings)
1714
+
1715
+ def AppendPostbuildVariable(
1716
+ self, variables, spec, output, binary, is_command_start=False
1717
+ ):
1718
+ """Adds a 'postbuild' variable if there is a postbuild for |output|."""
1719
+ postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start)
1720
+ if postbuild:
1721
+ variables.append(("postbuilds", postbuild))
1722
+
1723
+ def GetPostbuildCommand(self, spec, output, output_binary, is_command_start):
1724
+ """Returns a shell command that runs all the postbuilds, and removes
1725
+ |output| if any of them fails. If |is_command_start| is False, then the
1726
+ returned string will start with ' && '."""
1727
+ if not self.xcode_settings or spec["type"] == "none" or not output:
1728
+ return ""
1729
+ output = QuoteShellArgument(output, self.flavor)
1730
+ postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True)
1731
+ if output_binary is not None:
1732
+ postbuilds = self.xcode_settings.AddImplicitPostbuilds(
1733
+ self.config_name,
1734
+ os.path.normpath(os.path.join(self.base_to_build, output)),
1735
+ QuoteShellArgument(
1736
+ os.path.normpath(os.path.join(self.base_to_build, output_binary)),
1737
+ self.flavor,
1738
+ ),
1739
+ postbuilds,
1740
+ quiet=True,
1741
+ )
1742
+
1743
+ if not postbuilds:
1744
+ return ""
1745
+ # Postbuilds expect to be run in the gyp file's directory, so insert an
1746
+ # implicit postbuild to cd to there.
1747
+ postbuilds.insert(
1748
+ 0, gyp.common.EncodePOSIXShellList(["cd", self.build_to_base])
1749
+ )
1750
+ env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv())
1751
+ # G will be non-null if any postbuild fails. Run all postbuilds in a
1752
+ # subshell.
1753
+ commands = (
1754
+ env
1755
+ + " ("
1756
+ + " && ".join([ninja_syntax.escape(command) for command in postbuilds])
1757
+ )
1758
+ command_string = (
1759
+ commands
1760
+ + "); G=$$?; "
1761
+ # Remove the final output if any postbuild failed.
1762
+ "((exit $$G) || rm -rf %s) " % output
1763
+ + "&& exit $$G)"
1764
+ )
1765
+ if is_command_start:
1766
+ return "(" + command_string + " && "
1767
+ else:
1768
+ return "$ && (" + command_string
1769
+
1770
+ def ComputeExportEnvString(self, env):
1771
+ """Given an environment, returns a string looking like
1772
+ 'export FOO=foo; export BAR="${FOO} bar;'
1773
+ that exports |env| to the shell."""
1774
+ export_str = []
1775
+ for k, v in env:
1776
+ export_str.append(
1777
+ "export %s=%s;"
1778
+ % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))
1779
+ )
1780
+ return " ".join(export_str)
1781
+
1782
+ def ComputeMacBundleOutput(self):
1783
+ """Return the 'output' (full output path) to a bundle output directory."""
1784
+ assert self.is_mac_bundle
1785
+ path = generator_default_variables["PRODUCT_DIR"]
1786
+ return self.ExpandSpecial(
1787
+ os.path.join(path, self.xcode_settings.GetWrapperName())
1788
+ )
1789
+
1790
+ def ComputeOutputFileName(self, spec, type=None):
1791
+ """Compute the filename of the final output for the current target."""
1792
+ if not type:
1793
+ type = spec["type"]
1794
+
1795
+ default_variables = copy.copy(generator_default_variables)
1796
+ CalculateVariables(default_variables, {"flavor": self.flavor})
1797
+
1798
+ # Compute filename prefix: the product prefix, or a default for
1799
+ # the product type.
1800
+ DEFAULT_PREFIX = {
1801
+ "loadable_module": default_variables["SHARED_LIB_PREFIX"],
1802
+ "shared_library": default_variables["SHARED_LIB_PREFIX"],
1803
+ "static_library": default_variables["STATIC_LIB_PREFIX"],
1804
+ "executable": default_variables["EXECUTABLE_PREFIX"],
1805
+ }
1806
+ prefix = spec.get("product_prefix", DEFAULT_PREFIX.get(type, ""))
1807
+
1808
+ # Compute filename extension: the product extension, or a default
1809
+ # for the product type.
1810
+ DEFAULT_EXTENSION = {
1811
+ "loadable_module": default_variables["SHARED_LIB_SUFFIX"],
1812
+ "shared_library": default_variables["SHARED_LIB_SUFFIX"],
1813
+ "static_library": default_variables["STATIC_LIB_SUFFIX"],
1814
+ "executable": default_variables["EXECUTABLE_SUFFIX"],
1815
+ }
1816
+ extension = spec.get("product_extension")
1817
+ extension = "." + extension if extension else DEFAULT_EXTENSION.get(type, "")
1818
+
1819
+ if "product_name" in spec:
1820
+ # If we were given an explicit name, use that.
1821
+ target = spec["product_name"]
1822
+ else:
1823
+ # Otherwise, derive a name from the target name.
1824
+ target = spec["target_name"]
1825
+ if prefix == "lib":
1826
+ # Snip out an extra 'lib' from libs if appropriate.
1827
+ target = StripPrefix(target, "lib")
1828
+
1829
+ if type in (
1830
+ "static_library",
1831
+ "loadable_module",
1832
+ "shared_library",
1833
+ "executable",
1834
+ ):
1835
+ return f"{prefix}{target}{extension}"
1836
+ elif type == "none":
1837
+ return "%s.stamp" % target
1838
+ else:
1839
+ raise Exception("Unhandled output type %s" % type)
1840
+
1841
+ def ComputeOutput(self, spec, arch=None):
1842
+ """Compute the path for the final output of the spec."""
1843
+ type = spec["type"]
1844
+
1845
+ if self.flavor == "win":
1846
+ override = self.msvs_settings.GetOutputName(
1847
+ self.config_name, self.ExpandSpecial
1848
+ )
1849
+ if override:
1850
+ return override
1851
+
1852
+ if (
1853
+ arch is None
1854
+ and self.flavor == "mac"
1855
+ and type
1856
+ in ("static_library", "executable", "shared_library", "loadable_module")
1857
+ ):
1858
+ filename = self.xcode_settings.GetExecutablePath()
1859
+ else:
1860
+ filename = self.ComputeOutputFileName(spec, type)
1861
+
1862
+ if arch is None and "product_dir" in spec:
1863
+ path = os.path.join(spec["product_dir"], filename)
1864
+ return self.ExpandSpecial(path)
1865
+
1866
+ # Some products go into the output root, libraries go into shared library
1867
+ # dir, and everything else goes into the normal place.
1868
+ type_in_output_root = ["executable", "loadable_module"]
1869
+ if self.flavor == "mac" and self.toolset == "target":
1870
+ type_in_output_root += ["shared_library", "static_library"]
1871
+ elif self.flavor == "win" and self.toolset == "target":
1872
+ type_in_output_root += ["shared_library"]
1873
+
1874
+ if arch is not None:
1875
+ # Make sure partial executables don't end up in a bundle or the regular
1876
+ # output directory.
1877
+ archdir = "arch"
1878
+ if self.toolset != "target":
1879
+ archdir = os.path.join("arch", "%s" % self.toolset)
1880
+ return os.path.join(archdir, AddArch(filename, arch))
1881
+ elif type in type_in_output_root or self.is_standalone_static_library:
1882
+ return filename
1883
+ elif type == "shared_library":
1884
+ libdir = "lib"
1885
+ if self.toolset != "target":
1886
+ libdir = os.path.join("lib", "%s" % self.toolset)
1887
+ return os.path.join(libdir, filename)
1888
+ else:
1889
+ return self.GypPathToUniqueOutput(filename, qualified=False)
1890
+
1891
+ def WriteVariableList(self, ninja_file, var, values):
1892
+ assert not isinstance(values, str)
1893
+ if values is None:
1894
+ values = []
1895
+ ninja_file.variable(var, " ".join(values))
1896
+
1897
+ def WriteNewNinjaRule(
1898
+ self, name, args, description, win_shell_flags, env, pool, depfile=None
1899
+ ):
1900
+ """Write out a new ninja "rule" statement for a given command.
1901
+
1902
+ Returns the name of the new rule, and a copy of |args| with variables
1903
+ expanded."""
1904
+
1905
+ if self.flavor == "win":
1906
+ args = [
1907
+ self.msvs_settings.ConvertVSMacros(
1908
+ arg, self.base_to_build, config=self.config_name
1909
+ )
1910
+ for arg in args
1911
+ ]
1912
+ description = self.msvs_settings.ConvertVSMacros(
1913
+ description, config=self.config_name
1914
+ )
1915
+ elif self.flavor == "mac":
1916
+ # |env| is an empty list on non-mac.
1917
+ args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args]
1918
+ description = gyp.xcode_emulation.ExpandEnvVars(description, env)
1919
+
1920
+ # TODO: we shouldn't need to qualify names; we do it because
1921
+ # currently the ninja rule namespace is global, but it really
1922
+ # should be scoped to the subninja.
1923
+ rule_name = self.name
1924
+ if self.toolset == "target":
1925
+ rule_name += "." + self.toolset
1926
+ rule_name += "." + name
1927
+ rule_name = re.sub("[^a-zA-Z0-9_]", "_", rule_name)
1928
+
1929
+ # Remove variable references, but not if they refer to the magic rule
1930
+ # variables. This is not quite right, as it also protects these for
1931
+ # actions, not just for rules where they are valid. Good enough.
1932
+ protect = ["${root}", "${dirname}", "${source}", "${ext}", "${name}"]
1933
+ protect = "(?!" + "|".join(map(re.escape, protect)) + ")"
1934
+ description = re.sub(protect + r"\$", "_", description)
1935
+
1936
+ # gyp dictates that commands are run from the base directory.
1937
+ # cd into the directory before running, and adjust paths in
1938
+ # the arguments to point to the proper locations.
1939
+ rspfile = None
1940
+ rspfile_content = None
1941
+ args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args]
1942
+ if self.flavor == "win":
1943
+ rspfile = rule_name + ".$unique_name.rsp"
1944
+ # The cygwin case handles this inside the bash sub-shell.
1945
+ run_in = "" if win_shell_flags.cygwin else " " + self.build_to_base
1946
+ if win_shell_flags.cygwin:
1947
+ rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine(
1948
+ args, self.build_to_base
1949
+ )
1950
+ else:
1951
+ rspfile_content = gyp.msvs_emulation.EncodeRspFileList(
1952
+ args, win_shell_flags.quote)
1953
+ command = (
1954
+ "%s gyp-win-tool action-wrapper $arch " % sys.executable
1955
+ + rspfile
1956
+ + run_in
1957
+ )
1958
+ else:
1959
+ env = self.ComputeExportEnvString(env)
1960
+ command = gyp.common.EncodePOSIXShellList(args)
1961
+ command = "cd %s; " % self.build_to_base + env + command
1962
+
1963
+ # GYP rules/actions express being no-ops by not touching their outputs.
1964
+ # Avoid executing downstream dependencies in this case by specifying
1965
+ # restat=1 to ninja.
1966
+ self.ninja.rule(
1967
+ rule_name,
1968
+ command,
1969
+ description,
1970
+ depfile=depfile,
1971
+ restat=True,
1972
+ pool=pool,
1973
+ rspfile=rspfile,
1974
+ rspfile_content=rspfile_content,
1975
+ )
1976
+ self.ninja.newline()
1977
+
1978
+ return rule_name, args
1979
+
1980
+
1981
+ def CalculateVariables(default_variables, params):
1982
+ """Calculate additional variables for use in the build (called by gyp)."""
1983
+ global generator_additional_non_configuration_keys
1984
+ global generator_additional_path_sections
1985
+ flavor = gyp.common.GetFlavor(params)
1986
+ if flavor == "mac":
1987
+ default_variables.setdefault("OS", "mac")
1988
+ default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib")
1989
+ default_variables.setdefault(
1990
+ "SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"]
1991
+ )
1992
+ default_variables.setdefault(
1993
+ "LIB_DIR", generator_default_variables["PRODUCT_DIR"]
1994
+ )
1995
+
1996
+ # Copy additional generator configuration data from Xcode, which is shared
1997
+ # by the Mac Ninja generator.
1998
+ import gyp.generator.xcode as xcode_generator
1999
+
2000
+ generator_additional_non_configuration_keys = getattr(
2001
+ xcode_generator, "generator_additional_non_configuration_keys", []
2002
+ )
2003
+ generator_additional_path_sections = getattr(
2004
+ xcode_generator, "generator_additional_path_sections", []
2005
+ )
2006
+ global generator_extra_sources_for_rules
2007
+ generator_extra_sources_for_rules = getattr(
2008
+ xcode_generator, "generator_extra_sources_for_rules", []
2009
+ )
2010
+ elif flavor == "win":
2011
+ exts = gyp.MSVSUtil.TARGET_TYPE_EXT
2012
+ default_variables.setdefault("OS", "win")
2013
+ default_variables["EXECUTABLE_SUFFIX"] = "." + exts["executable"]
2014
+ default_variables["STATIC_LIB_PREFIX"] = ""
2015
+ default_variables["STATIC_LIB_SUFFIX"] = "." + exts["static_library"]
2016
+ default_variables["SHARED_LIB_PREFIX"] = ""
2017
+ default_variables["SHARED_LIB_SUFFIX"] = "." + exts["shared_library"]
2018
+
2019
+ # Copy additional generator configuration data from VS, which is shared
2020
+ # by the Windows Ninja generator.
2021
+ import gyp.generator.msvs as msvs_generator
2022
+
2023
+ generator_additional_non_configuration_keys = getattr(
2024
+ msvs_generator, "generator_additional_non_configuration_keys", []
2025
+ )
2026
+ generator_additional_path_sections = getattr(
2027
+ msvs_generator, "generator_additional_path_sections", []
2028
+ )
2029
+
2030
+ gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
2031
+ else:
2032
+ operating_system = flavor
2033
+ if flavor == "android":
2034
+ operating_system = "linux" # Keep this legacy behavior for now.
2035
+ default_variables.setdefault("OS", operating_system)
2036
+ default_variables.setdefault("SHARED_LIB_SUFFIX", ".so")
2037
+ default_variables.setdefault(
2038
+ "SHARED_LIB_DIR", os.path.join("$!PRODUCT_DIR", "lib")
2039
+ )
2040
+ default_variables.setdefault("LIB_DIR", os.path.join("$!PRODUCT_DIR", "obj"))
2041
+
2042
+
2043
+ def ComputeOutputDir(params):
2044
+ """Returns the path from the toplevel_dir to the build output directory."""
2045
+ # generator_dir: relative path from pwd to where make puts build files.
2046
+ # Makes migrating from make to ninja easier, ninja doesn't put anything here.
2047
+ generator_dir = os.path.relpath(params["options"].generator_output or ".")
2048
+
2049
+ # output_dir: relative path from generator_dir to the build directory.
2050
+ output_dir = params.get("generator_flags", {}).get("output_dir", "out")
2051
+
2052
+ # Relative path from source root to our output files. e.g. "out"
2053
+ return os.path.normpath(os.path.join(generator_dir, output_dir))
2054
+
2055
+
2056
+ def CalculateGeneratorInputInfo(params):
2057
+ """Called by __init__ to initialize generator values based on params."""
2058
+ # E.g. "out/gypfiles"
2059
+ toplevel = params["options"].toplevel_dir
2060
+ qualified_out_dir = os.path.normpath(
2061
+ os.path.join(toplevel, ComputeOutputDir(params), "gypfiles")
2062
+ )
2063
+
2064
+ global generator_filelist_paths
2065
+ generator_filelist_paths = {
2066
+ "toplevel": toplevel,
2067
+ "qualified_out_dir": qualified_out_dir,
2068
+ }
2069
+
2070
+
2071
+ def OpenOutput(path, mode="w"):
2072
+ """Open |path| for writing, creating directories if necessary."""
2073
+ gyp.common.EnsureDirExists(path)
2074
+ return open(path, mode)
2075
+
2076
+
2077
+ def CommandWithWrapper(cmd, wrappers, prog):
2078
+ wrapper = wrappers.get(cmd, "")
2079
+ if wrapper:
2080
+ return wrapper + " " + prog
2081
+ return prog
2082
+
2083
+
2084
+ def GetDefaultConcurrentLinks():
2085
+ """Returns a best-guess for a number of concurrent links."""
2086
+ pool_size = int(os.environ.get("GYP_LINK_CONCURRENCY") or 0)
2087
+ if pool_size:
2088
+ return pool_size
2089
+
2090
+ if sys.platform in ("win32", "cygwin"):
2091
+ import ctypes
2092
+
2093
+ class MEMORYSTATUSEX(ctypes.Structure):
2094
+ _fields_ = [
2095
+ ("dwLength", ctypes.c_ulong),
2096
+ ("dwMemoryLoad", ctypes.c_ulong),
2097
+ ("ullTotalPhys", ctypes.c_ulonglong),
2098
+ ("ullAvailPhys", ctypes.c_ulonglong),
2099
+ ("ullTotalPageFile", ctypes.c_ulonglong),
2100
+ ("ullAvailPageFile", ctypes.c_ulonglong),
2101
+ ("ullTotalVirtual", ctypes.c_ulonglong),
2102
+ ("ullAvailVirtual", ctypes.c_ulonglong),
2103
+ ("sullAvailExtendedVirtual", ctypes.c_ulonglong),
2104
+ ]
2105
+
2106
+ stat = MEMORYSTATUSEX()
2107
+ stat.dwLength = ctypes.sizeof(stat)
2108
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
2109
+
2110
+ # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM
2111
+ # on a 64 GiB machine.
2112
+ mem_limit = max(1, stat.ullTotalPhys // (5 * (2 ** 30))) # total / 5GiB
2113
+ hard_cap = max(1, int(os.environ.get("GYP_LINK_CONCURRENCY_MAX") or 2 ** 32))
2114
+ return min(mem_limit, hard_cap)
2115
+ elif sys.platform.startswith("linux"):
2116
+ if os.path.exists("/proc/meminfo"):
2117
+ with open("/proc/meminfo") as meminfo:
2118
+ memtotal_re = re.compile(r"^MemTotal:\s*(\d*)\s*kB")
2119
+ for line in meminfo:
2120
+ match = memtotal_re.match(line)
2121
+ if not match:
2122
+ continue
2123
+ # Allow 8Gb per link on Linux because Gold is quite memory hungry
2124
+ return max(1, int(match.group(1)) // (8 * (2 ** 20)))
2125
+ return 1
2126
+ elif sys.platform == "darwin":
2127
+ try:
2128
+ avail_bytes = int(subprocess.check_output(["sysctl", "-n", "hw.memsize"]))
2129
+ # A static library debug build of Chromium's unit_tests takes ~2.7GB, so
2130
+ # 4GB per ld process allows for some more bloat.
2131
+ return max(1, avail_bytes // (4 * (2 ** 30))) # total / 4GB
2132
+ except subprocess.CalledProcessError:
2133
+ return 1
2134
+ else:
2135
+ # TODO(scottmg): Implement this for other platforms.
2136
+ return 1
2137
+
2138
+
2139
+ def _GetWinLinkRuleNameSuffix(embed_manifest):
2140
+ """Returns the suffix used to select an appropriate linking rule depending on
2141
+ whether the manifest embedding is enabled."""
2142
+ return "_embed" if embed_manifest else ""
2143
+
2144
+
2145
+ def _AddWinLinkRules(master_ninja, embed_manifest):
2146
+ """Adds link rules for Windows platform to |master_ninja|."""
2147
+
2148
+ def FullLinkCommand(ldcmd, out, binary_type):
2149
+ resource_name = {"exe": "1", "dll": "2"}[binary_type]
2150
+ return (
2151
+ "%(python)s gyp-win-tool link-with-manifests $arch %(embed)s "
2152
+ '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" '
2153
+ "$manifests"
2154
+ % {
2155
+ "python": sys.executable,
2156
+ "out": out,
2157
+ "ldcmd": ldcmd,
2158
+ "resname": resource_name,
2159
+ "embed": embed_manifest,
2160
+ }
2161
+ )
2162
+
2163
+ rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest)
2164
+ use_separate_mspdbsrv = int(os.environ.get("GYP_USE_SEPARATE_MSPDBSRV", "0")) != 0
2165
+ dlldesc = "LINK%s(DLL) $binary" % rule_name_suffix.upper()
2166
+ dllcmd = (
2167
+ "%s gyp-win-tool link-wrapper $arch %s "
2168
+ "$ld /nologo $implibflag /DLL /OUT:$binary "
2169
+ "@$binary.rsp" % (sys.executable, use_separate_mspdbsrv)
2170
+ )
2171
+ dllcmd = FullLinkCommand(dllcmd, "$binary", "dll")
2172
+ master_ninja.rule(
2173
+ "solink" + rule_name_suffix,
2174
+ description=dlldesc,
2175
+ command=dllcmd,
2176
+ rspfile="$binary.rsp",
2177
+ rspfile_content="$libs $in_newline $ldflags",
2178
+ restat=True,
2179
+ pool="link_pool",
2180
+ )
2181
+ master_ninja.rule(
2182
+ "solink_module" + rule_name_suffix,
2183
+ description=dlldesc,
2184
+ command=dllcmd,
2185
+ rspfile="$binary.rsp",
2186
+ rspfile_content="$libs $in_newline $ldflags",
2187
+ restat=True,
2188
+ pool="link_pool",
2189
+ )
2190
+ # Note that ldflags goes at the end so that it has the option of
2191
+ # overriding default settings earlier in the command line.
2192
+ exe_cmd = (
2193
+ "%s gyp-win-tool link-wrapper $arch %s "
2194
+ "$ld /nologo /OUT:$binary @$binary.rsp"
2195
+ % (sys.executable, use_separate_mspdbsrv)
2196
+ )
2197
+ exe_cmd = FullLinkCommand(exe_cmd, "$binary", "exe")
2198
+ master_ninja.rule(
2199
+ "link" + rule_name_suffix,
2200
+ description="LINK%s $binary" % rule_name_suffix.upper(),
2201
+ command=exe_cmd,
2202
+ rspfile="$binary.rsp",
2203
+ rspfile_content="$in_newline $libs $ldflags",
2204
+ pool="link_pool",
2205
+ )
2206
+
2207
+
2208
+ def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name):
2209
+ options = params["options"]
2210
+ flavor = gyp.common.GetFlavor(params)
2211
+ generator_flags = params.get("generator_flags", {})
2212
+ generate_compile_commands = generator_flags.get("compile_commands", False)
2213
+
2214
+ # build_dir: relative path from source root to our output files.
2215
+ # e.g. "out/Debug"
2216
+ build_dir = os.path.normpath(os.path.join(ComputeOutputDir(params), config_name))
2217
+
2218
+ toplevel_build = os.path.join(options.toplevel_dir, build_dir)
2219
+
2220
+ master_ninja_file = OpenOutput(os.path.join(toplevel_build, "build.ninja"))
2221
+ master_ninja = ninja_syntax.Writer(master_ninja_file, width=120)
2222
+
2223
+ # Put build-time support tools in out/{config_name}.
2224
+ gyp.common.CopyTool(flavor, toplevel_build, generator_flags)
2225
+
2226
+ # Grab make settings for CC/CXX.
2227
+ # The rules are
2228
+ # - The priority from low to high is gcc/g++, the 'make_global_settings' in
2229
+ # gyp, the environment variable.
2230
+ # - If there is no 'make_global_settings' for CC.host/CXX.host or
2231
+ # 'CC_host'/'CXX_host' environment variable, cc_host/cxx_host should be set
2232
+ # to cc/cxx.
2233
+ if flavor == "win":
2234
+ ar = "lib.exe"
2235
+ # cc and cxx must be set to the correct architecture by overriding with one
2236
+ # of cl_x86 or cl_x64 below.
2237
+ cc = "UNSET"
2238
+ cxx = "UNSET"
2239
+ ld = "link.exe"
2240
+ ld_host = "$ld"
2241
+ else:
2242
+ ar = "ar"
2243
+ cc = "cc"
2244
+ cxx = "c++"
2245
+ ld = "$cc"
2246
+ ldxx = "$cxx"
2247
+ ld_host = "$cc_host"
2248
+ ldxx_host = "$cxx_host"
2249
+
2250
+ ar_host = ar
2251
+ cc_host = None
2252
+ cxx_host = None
2253
+ cc_host_global_setting = None
2254
+ cxx_host_global_setting = None
2255
+ clang_cl = None
2256
+ nm = "nm"
2257
+ nm_host = "nm"
2258
+ readelf = "readelf"
2259
+ readelf_host = "readelf"
2260
+
2261
+ build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
2262
+ make_global_settings = data[build_file].get("make_global_settings", [])
2263
+ build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir)
2264
+ wrappers = {}
2265
+ for key, value in make_global_settings:
2266
+ if key == "AR":
2267
+ ar = os.path.join(build_to_root, value)
2268
+ if key == "AR.host":
2269
+ ar_host = os.path.join(build_to_root, value)
2270
+ if key == "CC":
2271
+ cc = os.path.join(build_to_root, value)
2272
+ if cc.endswith("clang-cl"):
2273
+ clang_cl = cc
2274
+ if key == "CXX":
2275
+ cxx = os.path.join(build_to_root, value)
2276
+ if key == "CC.host":
2277
+ cc_host = os.path.join(build_to_root, value)
2278
+ cc_host_global_setting = value
2279
+ if key == "CXX.host":
2280
+ cxx_host = os.path.join(build_to_root, value)
2281
+ cxx_host_global_setting = value
2282
+ if key == "LD":
2283
+ ld = os.path.join(build_to_root, value)
2284
+ if key == "LD.host":
2285
+ ld_host = os.path.join(build_to_root, value)
2286
+ if key == "LDXX":
2287
+ ldxx = os.path.join(build_to_root, value)
2288
+ if key == "LDXX.host":
2289
+ ldxx_host = os.path.join(build_to_root, value)
2290
+ if key == "NM":
2291
+ nm = os.path.join(build_to_root, value)
2292
+ if key == "NM.host":
2293
+ nm_host = os.path.join(build_to_root, value)
2294
+ if key == "READELF":
2295
+ readelf = os.path.join(build_to_root, value)
2296
+ if key == "READELF.host":
2297
+ readelf_host = os.path.join(build_to_root, value)
2298
+ if key.endswith("_wrapper"):
2299
+ wrappers[key[: -len("_wrapper")]] = os.path.join(build_to_root, value)
2300
+
2301
+ # Support wrappers from environment variables too.
2302
+ for key, value in os.environ.items():
2303
+ if key.lower().endswith("_wrapper"):
2304
+ key_prefix = key[: -len("_wrapper")]
2305
+ key_prefix = re.sub(r"\.HOST$", ".host", key_prefix)
2306
+ wrappers[key_prefix] = os.path.join(build_to_root, value)
2307
+
2308
+ mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None)
2309
+ if mac_toolchain_dir:
2310
+ wrappers["LINK"] = "export DEVELOPER_DIR='%s' &&" % mac_toolchain_dir
2311
+
2312
+ if flavor == "win":
2313
+ configs = [
2314
+ target_dicts[qualified_target]["configurations"][config_name]
2315
+ for qualified_target in target_list
2316
+ ]
2317
+ shared_system_includes = None
2318
+ if not generator_flags.get("ninja_use_custom_environment_files", 0):
2319
+ shared_system_includes = gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes(
2320
+ configs, generator_flags
2321
+ )
2322
+ cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles(
2323
+ toplevel_build, generator_flags, shared_system_includes, OpenOutput
2324
+ )
2325
+ for arch, path in sorted(cl_paths.items()):
2326
+ if clang_cl:
2327
+ # If we have selected clang-cl, use that instead.
2328
+ path = clang_cl
2329
+ command = CommandWithWrapper(
2330
+ "CC", wrappers, QuoteShellArgument(path, "win")
2331
+ )
2332
+ if clang_cl:
2333
+ # Use clang-cl to cross-compile for x86 or x86_64.
2334
+ command += " -m32" if arch == "x86" else " -m64"
2335
+ master_ninja.variable("cl_" + arch, command)
2336
+
2337
+ cc = GetEnvironFallback(["CC_target", "CC"], cc)
2338
+ master_ninja.variable("cc", CommandWithWrapper("CC", wrappers, cc))
2339
+ cxx = GetEnvironFallback(["CXX_target", "CXX"], cxx)
2340
+ master_ninja.variable("cxx", CommandWithWrapper("CXX", wrappers, cxx))
2341
+
2342
+ if flavor == "win":
2343
+ master_ninja.variable("ld", ld)
2344
+ master_ninja.variable("idl", "midl.exe")
2345
+ master_ninja.variable("ar", ar)
2346
+ master_ninja.variable("rc", "rc.exe")
2347
+ master_ninja.variable("ml_x86", "ml.exe")
2348
+ master_ninja.variable("ml_x64", "ml64.exe")
2349
+ master_ninja.variable("mt", "mt.exe")
2350
+ else:
2351
+ master_ninja.variable("ld", CommandWithWrapper("LINK", wrappers, ld))
2352
+ master_ninja.variable("ldxx", CommandWithWrapper("LINK", wrappers, ldxx))
2353
+ master_ninja.variable("ar", GetEnvironFallback(["AR_target", "AR"], ar))
2354
+ if flavor != "mac":
2355
+ # Mac does not use readelf/nm for .TOC generation, so avoiding polluting
2356
+ # the master ninja with extra unused variables.
2357
+ master_ninja.variable("nm", GetEnvironFallback(["NM_target", "NM"], nm))
2358
+ master_ninja.variable(
2359
+ "readelf", GetEnvironFallback(["READELF_target", "READELF"], readelf)
2360
+ )
2361
+
2362
+ if generator_supports_multiple_toolsets:
2363
+ if not cc_host:
2364
+ cc_host = cc
2365
+ if not cxx_host:
2366
+ cxx_host = cxx
2367
+
2368
+ master_ninja.variable("ar_host", GetEnvironFallback(["AR_host"], ar_host))
2369
+ master_ninja.variable("nm_host", GetEnvironFallback(["NM_host"], nm_host))
2370
+ master_ninja.variable(
2371
+ "readelf_host", GetEnvironFallback(["READELF_host"], readelf_host)
2372
+ )
2373
+ cc_host = GetEnvironFallback(["CC_host"], cc_host)
2374
+ cxx_host = GetEnvironFallback(["CXX_host"], cxx_host)
2375
+
2376
+ # The environment variable could be used in 'make_global_settings', like
2377
+ # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here.
2378
+ if "$(CC)" in cc_host and cc_host_global_setting:
2379
+ cc_host = cc_host_global_setting.replace("$(CC)", cc)
2380
+ if "$(CXX)" in cxx_host and cxx_host_global_setting:
2381
+ cxx_host = cxx_host_global_setting.replace("$(CXX)", cxx)
2382
+ master_ninja.variable(
2383
+ "cc_host", CommandWithWrapper("CC.host", wrappers, cc_host)
2384
+ )
2385
+ master_ninja.variable(
2386
+ "cxx_host", CommandWithWrapper("CXX.host", wrappers, cxx_host)
2387
+ )
2388
+ if flavor == "win":
2389
+ master_ninja.variable("ld_host", ld_host)
2390
+ else:
2391
+ master_ninja.variable(
2392
+ "ld_host", CommandWithWrapper("LINK", wrappers, ld_host)
2393
+ )
2394
+ master_ninja.variable(
2395
+ "ldxx_host", CommandWithWrapper("LINK", wrappers, ldxx_host)
2396
+ )
2397
+
2398
+ master_ninja.newline()
2399
+
2400
+ master_ninja.pool("link_pool", depth=GetDefaultConcurrentLinks())
2401
+ master_ninja.newline()
2402
+
2403
+ deps = "msvc" if flavor == "win" else "gcc"
2404
+
2405
+ if flavor != "win":
2406
+ master_ninja.rule(
2407
+ "cc",
2408
+ description="CC $out",
2409
+ command=(
2410
+ "$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c "
2411
+ "$cflags_pch_c -c $in -o $out"
2412
+ ),
2413
+ depfile="$out.d",
2414
+ deps=deps,
2415
+ )
2416
+ master_ninja.rule(
2417
+ "cc_s",
2418
+ description="CC $out",
2419
+ command=(
2420
+ "$cc $defines $includes $cflags $cflags_c "
2421
+ "$cflags_pch_c -c $in -o $out"
2422
+ ),
2423
+ )
2424
+ master_ninja.rule(
2425
+ "cxx",
2426
+ description="CXX $out",
2427
+ command=(
2428
+ "$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc "
2429
+ "$cflags_pch_cc -c $in -o $out"
2430
+ ),
2431
+ depfile="$out.d",
2432
+ deps=deps,
2433
+ )
2434
+ else:
2435
+ # TODO(scottmg) Separate pdb names is a test to see if it works around
2436
+ # http://crbug.com/142362. It seems there's a race between the creation of
2437
+ # the .pdb by the precompiled header step for .cc and the compilation of
2438
+ # .c files. This should be handled by mspdbsrv, but rarely errors out with
2439
+ # c1xx : fatal error C1033: cannot open program database
2440
+ # By making the rules target separate pdb files this might be avoided.
2441
+ cc_command = (
2442
+ "ninja -t msvc -e $arch " + "-- "
2443
+ "$cc /nologo /showIncludes /FC "
2444
+ "@$out.rsp /c $in /Fo$out /Fd$pdbname_c "
2445
+ )
2446
+ cxx_command = (
2447
+ "ninja -t msvc -e $arch " + "-- "
2448
+ "$cxx /nologo /showIncludes /FC "
2449
+ "@$out.rsp /c $in /Fo$out /Fd$pdbname_cc "
2450
+ )
2451
+ master_ninja.rule(
2452
+ "cc",
2453
+ description="CC $out",
2454
+ command=cc_command,
2455
+ rspfile="$out.rsp",
2456
+ rspfile_content="$defines $includes $cflags $cflags_c",
2457
+ deps=deps,
2458
+ )
2459
+ master_ninja.rule(
2460
+ "cxx",
2461
+ description="CXX $out",
2462
+ command=cxx_command,
2463
+ rspfile="$out.rsp",
2464
+ rspfile_content="$defines $includes $cflags $cflags_cc",
2465
+ deps=deps,
2466
+ )
2467
+ master_ninja.rule(
2468
+ "idl",
2469
+ description="IDL $in",
2470
+ command=(
2471
+ "%s gyp-win-tool midl-wrapper $arch $outdir "
2472
+ "$tlb $h $dlldata $iid $proxy $in "
2473
+ "$midl_includes $idlflags" % sys.executable
2474
+ ),
2475
+ )
2476
+ master_ninja.rule(
2477
+ "rc",
2478
+ description="RC $in",
2479
+ # Note: $in must be last otherwise rc.exe complains.
2480
+ command=(
2481
+ "%s gyp-win-tool rc-wrapper "
2482
+ "$arch $rc $defines $resource_includes $rcflags /fo$out $in"
2483
+ % sys.executable
2484
+ ),
2485
+ )
2486
+ master_ninja.rule(
2487
+ "asm",
2488
+ description="ASM $out",
2489
+ command=(
2490
+ "%s gyp-win-tool asm-wrapper "
2491
+ "$arch $asm $defines $includes $asmflags /c /Fo $out $in"
2492
+ % sys.executable
2493
+ ),
2494
+ )
2495
+
2496
+ if flavor not in ("ios", "mac", "win"):
2497
+ master_ninja.rule(
2498
+ "alink",
2499
+ description="AR $out",
2500
+ command="rm -f $out && $ar rcs $arflags $out $in",
2501
+ )
2502
+ master_ninja.rule(
2503
+ "alink_thin",
2504
+ description="AR $out",
2505
+ command="rm -f $out && $ar rcsT $arflags $out $in",
2506
+ )
2507
+
2508
+ # This allows targets that only need to depend on $lib's API to declare an
2509
+ # order-only dependency on $lib.TOC and avoid relinking such downstream
2510
+ # dependencies when $lib changes only in non-public ways.
2511
+ # The resulting string leaves an uninterpolated %{suffix} which
2512
+ # is used in the final substitution below.
2513
+ mtime_preserving_solink_base = (
2514
+ "if [ ! -e $lib -o ! -e $lib.TOC ]; then "
2515
+ "%(solink)s && %(extract_toc)s > $lib.TOC; else "
2516
+ "%(solink)s && %(extract_toc)s > $lib.tmp && "
2517
+ "if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; "
2518
+ "fi; fi"
2519
+ % {
2520
+ "solink": "$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s",
2521
+ "extract_toc": (
2522
+ "{ $readelf -d $lib | grep SONAME ; "
2523
+ "$nm -gD -f p $lib | cut -f1-2 -d' '; }"
2524
+ ),
2525
+ }
2526
+ )
2527
+
2528
+ master_ninja.rule(
2529
+ "solink",
2530
+ description="SOLINK $lib",
2531
+ restat=True,
2532
+ command=mtime_preserving_solink_base
2533
+ % {"suffix": "@$link_file_list"},
2534
+ rspfile="$link_file_list",
2535
+ rspfile_content=(
2536
+ "-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive $libs"
2537
+ ),
2538
+ pool="link_pool",
2539
+ )
2540
+ master_ninja.rule(
2541
+ "solink_module",
2542
+ description="SOLINK(module) $lib",
2543
+ restat=True,
2544
+ command=mtime_preserving_solink_base % {"suffix": "@$link_file_list"},
2545
+ rspfile="$link_file_list",
2546
+ rspfile_content="-Wl,--start-group $in $solibs $libs -Wl,--end-group",
2547
+ pool="link_pool",
2548
+ )
2549
+ master_ninja.rule(
2550
+ "link",
2551
+ description="LINK $out",
2552
+ command=(
2553
+ "$ld $ldflags -o $out "
2554
+ "-Wl,--start-group $in $solibs $libs -Wl,--end-group"
2555
+ ),
2556
+ pool="link_pool",
2557
+ )
2558
+ elif flavor == "win":
2559
+ master_ninja.rule(
2560
+ "alink",
2561
+ description="LIB $out",
2562
+ command=(
2563
+ "%s gyp-win-tool link-wrapper $arch False "
2564
+ "$ar /nologo /ignore:4221 /OUT:$out @$out.rsp" % sys.executable
2565
+ ),
2566
+ rspfile="$out.rsp",
2567
+ rspfile_content="$in_newline $libflags",
2568
+ )
2569
+ _AddWinLinkRules(master_ninja, embed_manifest=True)
2570
+ _AddWinLinkRules(master_ninja, embed_manifest=False)
2571
+ else:
2572
+ master_ninja.rule(
2573
+ "objc",
2574
+ description="OBJC $out",
2575
+ command=(
2576
+ "$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc "
2577
+ "$cflags_pch_objc -c $in -o $out"
2578
+ ),
2579
+ depfile="$out.d",
2580
+ deps=deps,
2581
+ )
2582
+ master_ninja.rule(
2583
+ "objcxx",
2584
+ description="OBJCXX $out",
2585
+ command=(
2586
+ "$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc "
2587
+ "$cflags_pch_objcc -c $in -o $out"
2588
+ ),
2589
+ depfile="$out.d",
2590
+ deps=deps,
2591
+ )
2592
+ master_ninja.rule(
2593
+ "alink",
2594
+ description="LIBTOOL-STATIC $out, POSTBUILDS",
2595
+ command="rm -f $out && "
2596
+ "%s gyp-mac-tool filter-libtool libtool $libtool_flags "
2597
+ "-static -o $out $in"
2598
+ "$postbuilds" % sys.executable,
2599
+ )
2600
+ master_ninja.rule(
2601
+ "lipo",
2602
+ description="LIPO $out, POSTBUILDS",
2603
+ command="rm -f $out && lipo -create $in -output $out$postbuilds",
2604
+ )
2605
+ master_ninja.rule(
2606
+ "solipo",
2607
+ description="SOLIPO $out, POSTBUILDS",
2608
+ command=(
2609
+ "rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&"
2610
+ "%(extract_toc)s > $lib.TOC"
2611
+ % {
2612
+ "extract_toc": "{ otool -l $lib | grep LC_ID_DYLIB -A 5; "
2613
+ "nm -gP $lib | cut -f1-2 -d' ' | grep -v U$$; true; }"
2614
+ }
2615
+ ),
2616
+ )
2617
+
2618
+ # Record the public interface of $lib in $lib.TOC. See the corresponding
2619
+ # comment in the posix section above for details.
2620
+ solink_base = "$ld %(type)s $ldflags -o $lib %(suffix)s"
2621
+ mtime_preserving_solink_base = (
2622
+ "if [ ! -e $lib -o ! -e $lib.TOC ] || "
2623
+ # Always force dependent targets to relink if this library
2624
+ # reexports something. Handling this correctly would require
2625
+ # recursive TOC dumping but this is rare in practice, so punt.
2626
+ "otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then "
2627
+ "%(solink)s && %(extract_toc)s > $lib.TOC; "
2628
+ "else "
2629
+ "%(solink)s && %(extract_toc)s > $lib.tmp && "
2630
+ "if ! cmp -s $lib.tmp $lib.TOC; then "
2631
+ "mv $lib.tmp $lib.TOC ; "
2632
+ "fi; "
2633
+ "fi"
2634
+ % {
2635
+ "solink": solink_base,
2636
+ "extract_toc": "{ otool -l $lib | grep LC_ID_DYLIB -A 5; "
2637
+ "nm -gP $lib | cut -f1-2 -d' ' | grep -v U$$; true; }",
2638
+ }
2639
+ )
2640
+
2641
+ solink_suffix = "@$link_file_list$postbuilds"
2642
+ master_ninja.rule(
2643
+ "solink",
2644
+ description="SOLINK $lib, POSTBUILDS",
2645
+ restat=True,
2646
+ command=mtime_preserving_solink_base
2647
+ % {"suffix": solink_suffix, "type": "-shared"},
2648
+ rspfile="$link_file_list",
2649
+ rspfile_content="$in $solibs $libs",
2650
+ pool="link_pool",
2651
+ )
2652
+ master_ninja.rule(
2653
+ "solink_notoc",
2654
+ description="SOLINK $lib, POSTBUILDS",
2655
+ restat=True,
2656
+ command=solink_base % {"suffix": solink_suffix, "type": "-shared"},
2657
+ rspfile="$link_file_list",
2658
+ rspfile_content="$in $solibs $libs",
2659
+ pool="link_pool",
2660
+ )
2661
+
2662
+ master_ninja.rule(
2663
+ "solink_module",
2664
+ description="SOLINK(module) $lib, POSTBUILDS",
2665
+ restat=True,
2666
+ command=mtime_preserving_solink_base
2667
+ % {"suffix": solink_suffix, "type": "-bundle"},
2668
+ rspfile="$link_file_list",
2669
+ rspfile_content="$in $solibs $libs",
2670
+ pool="link_pool",
2671
+ )
2672
+ master_ninja.rule(
2673
+ "solink_module_notoc",
2674
+ description="SOLINK(module) $lib, POSTBUILDS",
2675
+ restat=True,
2676
+ command=solink_base % {"suffix": solink_suffix, "type": "-bundle"},
2677
+ rspfile="$link_file_list",
2678
+ rspfile_content="$in $solibs $libs",
2679
+ pool="link_pool",
2680
+ )
2681
+
2682
+ master_ninja.rule(
2683
+ "link",
2684
+ description="LINK $out, POSTBUILDS",
2685
+ command=("$ld $ldflags -o $out $in $solibs $libs$postbuilds"),
2686
+ pool="link_pool",
2687
+ )
2688
+ master_ninja.rule(
2689
+ "preprocess_infoplist",
2690
+ description="PREPROCESS INFOPLIST $out",
2691
+ command=(
2692
+ "$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && "
2693
+ "plutil -convert xml1 $out $out"
2694
+ ),
2695
+ )
2696
+ master_ninja.rule(
2697
+ "copy_infoplist",
2698
+ description="COPY INFOPLIST $in",
2699
+ command="$env %s gyp-mac-tool copy-info-plist $in $out $binary $keys"
2700
+ % sys.executable,
2701
+ )
2702
+ master_ninja.rule(
2703
+ "merge_infoplist",
2704
+ description="MERGE INFOPLISTS $in",
2705
+ command="$env %s gyp-mac-tool merge-info-plist $out $in" % sys.executable,
2706
+ )
2707
+ master_ninja.rule(
2708
+ "compile_xcassets",
2709
+ description="COMPILE XCASSETS $in",
2710
+ command="$env %s gyp-mac-tool compile-xcassets $keys $in" % sys.executable,
2711
+ )
2712
+ master_ninja.rule(
2713
+ "compile_ios_framework_headers",
2714
+ description="COMPILE HEADER MAPS AND COPY FRAMEWORK HEADERS $in",
2715
+ command="$env %(python)s gyp-mac-tool compile-ios-framework-header-map "
2716
+ "$out $framework $in && $env %(python)s gyp-mac-tool "
2717
+ "copy-ios-framework-headers $framework $copy_headers"
2718
+ % {'python': sys.executable},
2719
+ )
2720
+ master_ninja.rule(
2721
+ "mac_tool",
2722
+ description="MACTOOL $mactool_cmd $in",
2723
+ command="$env %s gyp-mac-tool $mactool_cmd $in $out $binary"
2724
+ % sys.executable,
2725
+ )
2726
+ master_ninja.rule(
2727
+ "package_framework",
2728
+ description="PACKAGE FRAMEWORK $out, POSTBUILDS",
2729
+ command="%s gyp-mac-tool package-framework $out $version$postbuilds "
2730
+ "&& touch $out" % sys.executable,
2731
+ )
2732
+ master_ninja.rule(
2733
+ "package_ios_framework",
2734
+ description="PACKAGE IOS FRAMEWORK $out, POSTBUILDS",
2735
+ command="%s gyp-mac-tool package-ios-framework $out $postbuilds "
2736
+ "&& touch $out" % sys.executable,
2737
+ )
2738
+ if flavor == "win":
2739
+ master_ninja.rule(
2740
+ "stamp",
2741
+ description="STAMP $out",
2742
+ command="%s gyp-win-tool stamp $out" % sys.executable,
2743
+ )
2744
+ else:
2745
+ master_ninja.rule(
2746
+ "stamp", description="STAMP $out", command="${postbuilds}touch $out"
2747
+ )
2748
+ if flavor == "win":
2749
+ master_ninja.rule(
2750
+ "copy",
2751
+ description="COPY $in $out",
2752
+ command="%s gyp-win-tool recursive-mirror $in $out" % sys.executable,
2753
+ )
2754
+ elif flavor == "zos":
2755
+ master_ninja.rule(
2756
+ "copy",
2757
+ description="COPY $in $out",
2758
+ command="rm -rf $out && cp -fRP $in $out",
2759
+ )
2760
+ else:
2761
+ master_ninja.rule(
2762
+ "copy",
2763
+ description="COPY $in $out",
2764
+ command="ln -f $in $out 2>/dev/null || (rm -rf $out && cp -af $in $out)",
2765
+ )
2766
+ master_ninja.newline()
2767
+
2768
+ all_targets = set()
2769
+ for build_file in params["build_files"]:
2770
+ for target in gyp.common.AllTargets(
2771
+ target_list, target_dicts, os.path.normpath(build_file)
2772
+ ):
2773
+ all_targets.add(target)
2774
+ all_outputs = set()
2775
+
2776
+ # target_outputs is a map from qualified target name to a Target object.
2777
+ target_outputs = {}
2778
+ # target_short_names is a map from target short name to a list of Target
2779
+ # objects.
2780
+ target_short_names = {}
2781
+
2782
+ # short name of targets that were skipped because they didn't contain anything
2783
+ # interesting.
2784
+ # NOTE: there may be overlap between this an non_empty_target_names.
2785
+ empty_target_names = set()
2786
+
2787
+ # Set of non-empty short target names.
2788
+ # NOTE: there may be overlap between this an empty_target_names.
2789
+ non_empty_target_names = set()
2790
+
2791
+ for qualified_target in target_list:
2792
+ # qualified_target is like: third_party/icu/icu.gyp:icui18n#target
2793
+ build_file, name, toolset = gyp.common.ParseQualifiedTarget(qualified_target)
2794
+
2795
+ this_make_global_settings = data[build_file].get("make_global_settings", [])
2796
+ assert make_global_settings == this_make_global_settings, (
2797
+ "make_global_settings needs to be the same for all targets. "
2798
+ f"{this_make_global_settings} vs. {make_global_settings}"
2799
+ )
2800
+
2801
+ spec = target_dicts[qualified_target]
2802
+ if flavor == "mac":
2803
+ gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
2804
+
2805
+ # If build_file is a symlink, we must not follow it because there's a chance
2806
+ # it could point to a path above toplevel_dir, and we cannot correctly deal
2807
+ # with that case at the moment.
2808
+ build_file = gyp.common.RelativePath(build_file, options.toplevel_dir, False)
2809
+
2810
+ qualified_target_for_hash = gyp.common.QualifiedTarget(
2811
+ build_file, name, toolset
2812
+ )
2813
+ qualified_target_for_hash = qualified_target_for_hash.encode("utf-8")
2814
+ hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest()
2815
+
2816
+ base_path = os.path.dirname(build_file)
2817
+ obj = "obj"
2818
+ if toolset != "target":
2819
+ obj += "." + toolset
2820
+ output_file = os.path.join(obj, base_path, name + ".ninja")
2821
+
2822
+ ninja_output = StringIO()
2823
+ writer = NinjaWriter(
2824
+ hash_for_rules,
2825
+ target_outputs,
2826
+ base_path,
2827
+ build_dir,
2828
+ ninja_output,
2829
+ toplevel_build,
2830
+ output_file,
2831
+ flavor,
2832
+ toplevel_dir=options.toplevel_dir,
2833
+ )
2834
+
2835
+ target = writer.WriteSpec(spec, config_name, generator_flags)
2836
+
2837
+ if ninja_output.tell() > 0:
2838
+ # Only create files for ninja files that actually have contents.
2839
+ with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file:
2840
+ ninja_file.write(ninja_output.getvalue())
2841
+ ninja_output.close()
2842
+ master_ninja.subninja(output_file)
2843
+
2844
+ if target:
2845
+ if name != target.FinalOutput() and spec["toolset"] == "target":
2846
+ target_short_names.setdefault(name, []).append(target)
2847
+ target_outputs[qualified_target] = target
2848
+ if qualified_target in all_targets:
2849
+ all_outputs.add(target.FinalOutput())
2850
+ non_empty_target_names.add(name)
2851
+ else:
2852
+ empty_target_names.add(name)
2853
+
2854
+ if target_short_names:
2855
+ # Write a short name to build this target. This benefits both the
2856
+ # "build chrome" case as well as the gyp tests, which expect to be
2857
+ # able to run actions and build libraries by their short name.
2858
+ master_ninja.newline()
2859
+ master_ninja.comment("Short names for targets.")
2860
+ for short_name in sorted(target_short_names):
2861
+ master_ninja.build(
2862
+ short_name,
2863
+ "phony",
2864
+ [x.FinalOutput() for x in target_short_names[short_name]],
2865
+ )
2866
+
2867
+ # Write phony targets for any empty targets that weren't written yet. As
2868
+ # short names are not necessarily unique only do this for short names that
2869
+ # haven't already been output for another target.
2870
+ empty_target_names = empty_target_names - non_empty_target_names
2871
+ if empty_target_names:
2872
+ master_ninja.newline()
2873
+ master_ninja.comment("Empty targets (output for completeness).")
2874
+ for name in sorted(empty_target_names):
2875
+ master_ninja.build(name, "phony")
2876
+
2877
+ if all_outputs:
2878
+ master_ninja.newline()
2879
+ master_ninja.build("all", "phony", sorted(all_outputs))
2880
+ master_ninja.default(generator_flags.get("default_target", "all"))
2881
+
2882
+ master_ninja_file.close()
2883
+
2884
+ if generate_compile_commands:
2885
+ compile_db = GenerateCompileDBWithNinja(toplevel_build)
2886
+ compile_db_file = OpenOutput(
2887
+ os.path.join(toplevel_build, "compile_commands.json")
2888
+ )
2889
+ compile_db_file.write(json.dumps(compile_db, indent=2))
2890
+ compile_db_file.close()
2891
+
2892
+
2893
+ def GenerateCompileDBWithNinja(path, targets=["all"]):
2894
+ """Generates a compile database using ninja.
2895
+
2896
+ Args:
2897
+ path: The build directory to generate a compile database for.
2898
+ targets: Additional targets to pass to ninja.
2899
+
2900
+ Returns:
2901
+ List of the contents of the compile database.
2902
+ """
2903
+ ninja_path = shutil.which("ninja")
2904
+ if ninja_path is None:
2905
+ raise Exception("ninja not found in PATH")
2906
+ json_compile_db = subprocess.check_output(
2907
+ [ninja_path, "-C", path]
2908
+ + targets
2909
+ + ["-t", "compdb", "cc", "cxx", "objc", "objcxx"]
2910
+ )
2911
+ return json.loads(json_compile_db)
2912
+
2913
+
2914
+ def PerformBuild(data, configurations, params):
2915
+ options = params["options"]
2916
+ for config in configurations:
2917
+ builddir = os.path.join(options.toplevel_dir, "out", config)
2918
+ arguments = ["ninja", "-C", builddir]
2919
+ print(f"Building [{config}]: {arguments}")
2920
+ subprocess.check_call(arguments)
2921
+
2922
+
2923
+ def CallGenerateOutputForConfig(arglist):
2924
+ # Ignore the interrupt signal so that the parent process catches it and
2925
+ # kills all multiprocessing children.
2926
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
2927
+
2928
+ (target_list, target_dicts, data, params, config_name) = arglist
2929
+ GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
2930
+
2931
+
2932
+ def GenerateOutput(target_list, target_dicts, data, params):
2933
+ # Update target_dicts for iOS device builds.
2934
+ target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator(
2935
+ target_dicts
2936
+ )
2937
+
2938
+ user_config = params.get("generator_flags", {}).get("config", None)
2939
+ if gyp.common.GetFlavor(params) == "win":
2940
+ target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts)
2941
+ target_list, target_dicts = MSVSUtil.InsertLargePdbShims(
2942
+ target_list, target_dicts, generator_default_variables
2943
+ )
2944
+
2945
+ if user_config:
2946
+ GenerateOutputForConfig(target_list, target_dicts, data, params, user_config)
2947
+ else:
2948
+ config_names = target_dicts[target_list[0]]["configurations"]
2949
+ if params["parallel"]:
2950
+ try:
2951
+ pool = multiprocessing.Pool(len(config_names))
2952
+ arglists = []
2953
+ for config_name in config_names:
2954
+ arglists.append(
2955
+ (target_list, target_dicts, data, params, config_name)
2956
+ )
2957
+ pool.map(CallGenerateOutputForConfig, arglists)
2958
+ except KeyboardInterrupt as e:
2959
+ pool.terminate()
2960
+ raise e
2961
+ else:
2962
+ for config_name in config_names:
2963
+ GenerateOutputForConfig(
2964
+ target_list, target_dicts, data, params, config_name
2965
+ )