Debian Codegraph @

build/gn_processor.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import argparse
6 import json
7 import os
8 import subprocess
9 import sys
10 import tempfile
11 from collections import defaultdict, deque
12 from concurrent.futures import ProcessPoolExecutor, as_completed
13 from copy import deepcopy
14 from pathlib import Path
15 from shutil import which
16
17 import mozpack.path as mozpath
18 from mozbuild.bootstrap import bootstrap_toolchain
19 from mozbuild.dirutils import mkdir
20 from mozbuild.frontend.sandbox import alphabetical_sorted
21
22 license_header = """# This Source Code Form is subject to the terms of the Mozilla Public
23 # License, v. 2.0. If a copy of the MPL was not distributed with this
24 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
25 """
26
27 generated_header = """
28 ### This moz.build was AUTOMATICALLY GENERATED from a GN config, ###
29 ### DO NOT edit it by hand. ###
30 """
31
32
33 class MozbuildWriter:
34 def __init__(self, fh):
35 self._fh = fh
36 self.indent = ""
37 self._indent_increment = 4
38
39 # We need to correlate a small amount of state here to figure out
40 # which library template to use ("Library()" or "SharedLibrary()")
41 self._library_name = None
42 self._shared_library = None
43
44 def mb_serialize(self, v):
45 if isinstance(v, list):
46 if len(v) <= 1:
47 return repr(v)
48 # Pretty print a list
49 raw = json.dumps(v, indent=self._indent_increment)
50 # Add the indent of the current indentation level
51 return raw.replace("\n", "\n" + self.indent)
52 if isinstance(v, bool):
53 return repr(v)
54 return '"%s"' % v
55
56 def finalize(self):
57 if self._library_name:
58 self.write("\n")
59 if self._shared_library:
60 self.write_ln(
61 "SharedLibrary(%s)" % self.mb_serialize(self._library_name)
62 )
63 else:
64 self.write_ln("Library(%s)" % self.mb_serialize(self._library_name))
65
66 def write(self, content):
67 self._fh.write(content)
68
69 def write_ln(self, line):
70 self.write(self.indent)
71 self.write(line)
72 self.write("\n")
73
74 def write_attrs(self, context_attrs):
75 for k in sorted(context_attrs.keys()):
76 v = context_attrs[k]
77 if isinstance(v, (list, set)):
78 self.write_mozbuild_list(k, v)
79 elif isinstance(v, dict):
80 self.write_mozbuild_dict(k, v)
81 else:
82 self.write_mozbuild_value(k, v)
83
84 def write_mozbuild_list(self, key, value):
85 if value:
86 self.write("\n")
87 self.write(self.indent + key)
88 self.write(" += [\n " + self.indent)
89 self.write(
90 (",\n " + self.indent).join(
91 alphabetical_sorted(self.mb_serialize(v) for v in value)
92 )
93 )
94 self.write("\n")
95 self.write_ln("]")
96
97 def write_mozbuild_value(self, key, value):
98 if value:
99 if key == "LIBRARY_NAME":
100 self._library_name = value
101 elif key == "FORCE_SHARED_LIB":
102 self._shared_library = True
103 else:
104 self.write("\n")
105 self.write_ln("%s = %s" % (key, self.mb_serialize(value)))
106 self.write("\n")
107
108 def write_mozbuild_dict(self, key, value):
109 # Templates we need to use instead of certain values.
110 replacements = (
111 (
112 ("COMPILE_FLAGS", '"WARNINGS_AS_ERRORS"', "[]"),
113 "AllowCompilerWarnings()",
114 ),
115 )
116 if value:
117 self.write("\n")
118 if key == "GeneratedFile":
119 self.write_ln("GeneratedFile(")
120 self.indent += " " * self._indent_increment
121 for o in value["outputs"]:
122 self.write_ln("%s," % (self.mb_serialize(o)))
123 for k, v in sorted(value.items()):
124 if k == "outputs":
125 continue
126 self.write_ln("%s=%s," % (k, self.mb_serialize(v)))
127 self.indent = self.indent[self._indent_increment :]
128 self.write_ln(")")
129 return
130 for k in sorted(value.keys()):
131 v = value[k]
132 subst_vals = key, self.mb_serialize(k), self.mb_serialize(v)
133 wrote_ln = False
134 for flags, tmpl in replacements:
135 if subst_vals == flags:
136 self.write_ln(tmpl)
137 wrote_ln = True
138
139 if not wrote_ln:
140 self.write_ln("%s[%s] = %s" % subst_vals)
141
142 def write_condition(self, values):
143 def mk_condition(k, v):
144 if not v:
145 return 'not CONFIG["%s"]' % k
146 return 'CONFIG["%s"] == %s' % (k, self.mb_serialize(v))
147
148 self.write("\n")
149 self.write("if ")
150 self.write(
151 " and ".join(mk_condition(k, values[k]) for k in sorted(values.keys()))
152 )
153 self.write(":\n")
154 self.indent += " " * self._indent_increment
155
156 def terminate_condition(self):
157 assert len(self.indent) >= self._indent_increment
158 self.indent = self.indent[self._indent_increment :]
159
160
161 def find_deps(all_targets, target):
162 all_deps = set()
163 queue = deque([target])
164 while queue:
165 item = queue.popleft()
166 all_deps.add(item)
167 for dep in all_targets[item]["deps"]:
168 if dep not in all_deps:
169 queue.append(dep)
170 return all_deps
171
172
173 def filter_gn_config(path, gn_result, sandbox_vars, input_vars, gn_target):
174 gen_path = path / "gen"
175 # Translates the raw output of gn into just what we'll need to generate a
176 # mozbuild configuration.
177 gn_out = {"targets": {}, "sandbox_vars": sandbox_vars}
178
179 cpus = {
180 "arm64": "aarch64",
181 "x64": "x86_64",
182 "mipsel": "mips32",
183 "mips64el": "mips64",
184 "loong64": "loongarch64",
185 }
186 oses = {
187 "android": "Android",
188 "linux": "Linux",
189 "mac": "Darwin",
190 "openbsd": "OpenBSD",
191 "win": "WINNT",
192 }
193
194 mozbuild_args = {
195 "MOZ_DEBUG": "1" if input_vars.get("is_debug") else None,
196 "OS_TARGET": oses[input_vars["target_os"]],
197 "TARGET_CPU": cpus.get(input_vars["target_cpu"], input_vars["target_cpu"]),
198 }
199 if "use_x11" in input_vars:
200 mozbuild_args["MOZ_X11"] = "1" if input_vars["use_x11"] else None
201
202 gn_out["mozbuild_args"] = mozbuild_args
203 all_deps = find_deps(gn_result["targets"], gn_target)
204
205 for target_fullname in all_deps:
206 raw_spec = gn_result["targets"][target_fullname]
207
208 if raw_spec["type"] == "action":
209 # Special handling for the action type to avoid putting empty
210 # arrays of args, script and outputs on all other types in `spec`.
211 spec = {}
212 for spec_attr in (
213 "type",
214 "args",
215 "script",
216 "outputs",
217 ):
218 spec[spec_attr] = raw_spec.get(spec_attr, [])
219 if spec_attr == "outputs":
220 # Rebase outputs from an absolute path in the temp dir to a
221 # path relative to the target dir.
222 spec[spec_attr] = [
223 mozpath.relpath(d, path) for d in spec[spec_attr]
224 ]
225 gn_out["targets"][target_fullname] = spec
226
227 # TODO: 'executable' will need to be handled here at some point as well.
228 if raw_spec["type"] not in ("static_library", "shared_library", "source_set"):
229 continue
230
231 spec = {}
232 for spec_attr in (
233 "type",
234 "sources",
235 "defines",
236 "include_dirs",
237 "cflags",
238 "cflags_c",
239 "cflags_cc",
240 "cflags_objc",
241 "cflags_objcc",
242 "deps",
243 "libs",
244 ):
245 spec[spec_attr] = raw_spec.get(spec_attr, [])
246 if spec_attr == "defines":
247 spec[spec_attr] = [
248 d
249 for d in spec[spec_attr]
250 if "CR_XCODE_VERSION" not in d
251 and "CR_SYSROOT_HASH" not in d
252 and "_FORTIFY_SOURCE" not in d
253 ]
254 if spec_attr == "include_dirs":
255 # Rebase outputs from an absolute path in the temp dir to a path
256 # relative to the target dir.
257 spec[spec_attr] = [
258 d if gen_path != Path(d) else "!//gen" for d in spec[spec_attr]
259 ]
260
261 gn_out["targets"][target_fullname] = spec
262
263 return gn_out
264
265
266 def process_gn_config(
267 gn_config, topsrcdir, srcdir, non_unified_sources, sandbox_vars, mozilla_flags
268 ):
269 # Translates a json gn config into attributes that can be used to write out
270 # moz.build files for this configuration.
271
272 # Much of this code is based on similar functionality in `gyp_reader.py`.
273
274 mozbuild_attrs = {"mozbuild_args": gn_config.get("mozbuild_args", None), "dirs": {}}
275
276 targets = gn_config["targets"]
277
278 project_relsrcdir = mozpath.relpath(srcdir, topsrcdir)
279
280 non_unified_sources = set([mozpath.normpath(s) for s in non_unified_sources])
281
282 def target_info(fullname):
283 path, name = target_fullname.split(":")
284 # Stripping '//' gives us a path relative to the project root,
285 # adding a suffix avoids name collisions with libraries already
286 # in the tree (like "webrtc").
287 return path.lstrip("//"), name + "_gn"
288
289 def resolve_path(path):
290 # GN will have resolved all these paths relative to the root of the
291 # project indicated by "//".
292 if path.startswith("//"):
293 path = path[2:]
294 if not path.startswith("/"):
295 path = "/%s/%s" % (project_relsrcdir, path)
296 return path
297
298 # Process all targets from the given gn project and its dependencies.
299 for target_fullname, spec in targets.items():
300 target_path, target_name = target_info(target_fullname)
301 context_attrs = {}
302
303 # Remove leading 'lib' from the target_name if any, and use as
304 # library name.
305 name = target_name
306 if spec["type"] in ("static_library", "shared_library", "source_set", "action"):
307 if name.startswith("lib"):
308 name = name[3:]
309 context_attrs["LIBRARY_NAME"] = str(name)
310 else:
311 raise Exception(
312 "The following GN target type is not currently "
313 'consumed by moz.build: "%s". It may need to be '
314 "added, or you may need to re-run the "
315 "`GnConfigGen` step." % spec["type"]
316 )
317
318 if spec["type"] == "shared_library":
319 context_attrs["FORCE_SHARED_LIB"] = True
320
321 if spec["type"] == "action" and "script" in spec:
322 flags = [
323 resolve_path(spec["script"]),
324 resolve_path(""),
325 ] + spec.get("args", [])
326 context_attrs["GeneratedFile"] = {
327 "script": "/python/mozbuild/mozbuild/action/file_generate_wrapper.py",
328 "entry_point": "action",
329 "outputs": [resolve_path(f) for f in spec["outputs"]],
330 "flags": flags,
331 }
332
333 sources = []
334 unified_sources = []
335 extensions = set()
336 use_defines_in_asflags = False
337
338 for f in spec.get("sources", []):
339 f = f.lstrip("//")
340 ext = mozpath.splitext(f)[-1]
341 extensions.add(ext)
342 src = "%s/%s" % (project_relsrcdir, f)
343 if ext == ".h" or ext == ".inc":
344 continue
345 elif ext == ".def":
346 context_attrs["SYMBOLS_FILE"] = src
347 elif ext != ".S" and src not in non_unified_sources:
348 unified_sources.append("/%s" % src)
349 else:
350 sources.append("/%s" % src)
351 # The Mozilla build system doesn't use DEFINES for building
352 # ASFILES.
353 if ext == ".s":
354 use_defines_in_asflags = True
355
356 context_attrs["SOURCES"] = sources
357 context_attrs["UNIFIED_SOURCES"] = unified_sources
358
359 context_attrs["DEFINES"] = {}
360 for define in spec.get("defines", []):
361 if "=" in define:
362 name, value = define.split("=", 1)
363 context_attrs["DEFINES"][name] = value
364 else:
365 context_attrs["DEFINES"][define] = True
366
367 context_attrs["LOCAL_INCLUDES"] = []
368 for include in spec.get("include_dirs", []):
369 if include.startswith("!"):
370 include = "!" + resolve_path(include[1:])
371 else:
372 include = resolve_path(include)
373 # moz.build expects all LOCAL_INCLUDES to exist, so ensure they do.
374 resolved = mozpath.abspath(mozpath.join(topsrcdir, include[1:]))
375 if not os.path.exists(resolved):
376 # GN files may refer to include dirs that are outside of the
377 # tree or we simply didn't vendor. Print a warning in this case.
378 if not resolved.endswith("gn-output/gen"):
379 print(
380 "Included path: '%s' does not exist, dropping include from GN "
381 "configuration." % resolved,
382 file=sys.stderr,
383 )
384 continue
385 if include in context_attrs["LOCAL_INCLUDES"]:
386 continue
387 context_attrs["LOCAL_INCLUDES"] += [include]
388
389 context_attrs["ASFLAGS"] = spec.get("asflags_mozilla", [])
390 if use_defines_in_asflags and context_attrs["DEFINES"]:
391 context_attrs["ASFLAGS"] += ["-D" + d for d in context_attrs["DEFINES"]]
392 suffix_map = {
393 ".c": ("CFLAGS", ["cflags", "cflags_c"]),
394 ".cpp": ("CXXFLAGS", ["cflags", "cflags_cc"]),
395 ".cc": ("CXXFLAGS", ["cflags", "cflags_cc"]),
396 ".m": ("CMFLAGS", ["cflags", "cflags_objc"]),
397 ".mm": ("CMMFLAGS", ["cflags", "cflags_objcc"]),
398 }
399 variables = (suffix_map[e] for e in extensions if e in suffix_map)
400 for var, flag_keys in variables:
401 flags = [
402 _f for _k in flag_keys for _f in spec.get(_k, []) if _f in mozilla_flags
403 ]
404 for f in flags:
405 # the result may be a string or a list.
406 if isinstance(f, str):
407 context_attrs.setdefault(var, []).append(f)
408 else:
409 context_attrs.setdefault(var, []).extend(f)
410
411 context_attrs["OS_LIBS"] = []
412 for lib in spec.get("libs", []):
413 lib_name = os.path.splitext(lib)[0]
414 if lib.endswith(".framework"):
415 context_attrs["OS_LIBS"] += ["-framework " + lib_name]
416 else:
417 context_attrs["OS_LIBS"] += [lib_name]
418
419 # Add some features to all contexts. Put here in case LOCAL_INCLUDES
420 # order matters.
421 context_attrs["LOCAL_INCLUDES"] += [
422 "!/ipc/ipdl/_ipdlheaders",
423 "/ipc/chromium/src",
424 "/tools/profiler/public",
425 ]
426 # These get set via VC project file settings for normal GYP builds.
427 # TODO: Determine if these defines are needed for GN builds.
428 if gn_config["mozbuild_args"]["OS_TARGET"] == "WINNT":
429 context_attrs["DEFINES"]["UNICODE"] = True
430 context_attrs["DEFINES"]["_UNICODE"] = True
431
432 context_attrs["COMPILE_FLAGS"] = {"OS_INCLUDES": []}
433
434 for key, value in sandbox_vars.items():
435 if context_attrs.get(key) and isinstance(context_attrs[key], list):
436 # If we have a key from sandbox_vars that's also been
437 # populated here we use the value from sandbox_vars as our
438 # basis rather than overriding outright.
439 context_attrs[key] = value + context_attrs[key]
440 elif context_attrs.get(key) and isinstance(context_attrs[key], dict):
441 context_attrs[key].update(value)
442 else:
443 context_attrs[key] = value
444
445 target_relsrcdir = mozpath.join(project_relsrcdir, target_path, target_name)
446 mozbuild_attrs["dirs"][target_relsrcdir] = context_attrs
447
448 return mozbuild_attrs
449
450
451 def find_common_attrs(config_attributes):
452 # Returns the intersection of the given configs and prunes the inputs
453 # to no longer contain these common attributes.
454
455 common_attrs = deepcopy(config_attributes[0])
456
457 def make_intersection(reference, input_attrs):
458 # Modifies `reference` so that after calling this function it only
459 # contains parts it had in common with in `input_attrs`.
460
461 for k, input_value in input_attrs.items():
462 # Anything in `input_attrs` must match what's already in
463 # `reference`.
464 common_value = reference.get(k)
465 if common_value:
466 if isinstance(input_value, list):
467 reference[k] = [
468 i
469 for i in common_value
470 if input_value.count(i) == common_value.count(i)
471 ]
472 elif isinstance(input_value, dict):
473 reference[k] = {
474 key: value
475 for key, value in common_value.items()
476 if key in input_value and value == input_value[key]
477 }
478 elif input_value != common_value:
479 del reference[k]
480 elif k in reference:
481 del reference[k]
482
483 # Additionally, any keys in `reference` that aren't in `input_attrs`
484 # must be deleted.
485 for k in set(reference.keys()) - set(input_attrs.keys()):
486 del reference[k]
487
488 def make_difference(reference, input_attrs):
489 # Modifies `input_attrs` so that after calling this function it contains
490 # no parts it has in common with in `reference`.
491 for k, input_value in list(input_attrs.items()):
492 common_value = reference.get(k)
493 if common_value:
494 if isinstance(input_value, list):
495 input_attrs[k] = [
496 i
497 for i in input_value
498 if common_value.count(i) != input_value.count(i)
499 ]
500 elif isinstance(input_value, dict):
501 input_attrs[k] = {
502 key: value
503 for key, value in input_value.items()
504 if key not in common_value
505 }
506 else:
507 del input_attrs[k]
508
509 for config_attr_set in config_attributes[1:]:
510 make_intersection(common_attrs, config_attr_set)
511
512 for config_attr_set in config_attributes:
513 make_difference(common_attrs, config_attr_set)
514
515 return common_attrs
516
517
518 def write_mozbuild(topsrcdir, write_mozbuild_variables, relsrcdir, configs):
519 target_srcdir = mozpath.join(topsrcdir, relsrcdir)
520 mkdir(target_srcdir)
521
522 target_mozbuild = mozpath.join(target_srcdir, "moz.build")
523 with open(target_mozbuild, "w") as fh:
524 mb = MozbuildWriter(fh)
525 mb.write(license_header)
526 mb.write("\n")
527 mb.write(generated_header)
528
529 try:
530 if relsrcdir in write_mozbuild_variables["INCLUDE_TK_CFLAGS_DIRS"]:
531 mb.write('if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":\n')
532 mb.write(' CXXFLAGS += CONFIG["MOZ_GTK3_CFLAGS"]\n')
533 except KeyError:
534 pass
535 try:
536 if relsrcdir in write_mozbuild_variables["INCLUDE_SYSTEM_GBM_HANDLING"]:
537 mb.write('CXXFLAGS += CONFIG["MOZ_GBM_CFLAGS"]\n')
538 mb.write('if not CONFIG["MOZ_SYSTEM_GBM"]:\n')
539 mb.write(' LOCAL_INCLUDES += [ "/third_party/gbm/gbm/" ]\n')
540 except KeyError:
541 pass
542 try:
543 if relsrcdir in write_mozbuild_variables["INCLUDE_SYSTEM_LIBDRM_HANDLING"]:
544 mb.write('CXXFLAGS += CONFIG["MOZ_LIBDRM_CFLAGS"]\n')
545 mb.write('if not CONFIG["MOZ_SYSTEM_LIBDRM"]:\n')
546 mb.write(' LOCAL_INCLUDES += [ "/third_party/drm/drm/",\n')
547 mb.write(' "/third_party/drm/drm/include/",\n')
548 mb.write(
549 ' "/third_party/drm/drm/include/libdrm" ]\n'
550 )
551 except KeyError:
552 pass
553 try:
554 if (
555 relsrcdir
556 in write_mozbuild_variables["INCLUDE_SYSTEM_PIPEWIRE_HANDLING"]
557 ):
558 mb.write('CXXFLAGS += CONFIG["MOZ_PIPEWIRE_CFLAGS"]\n')
559 mb.write('if not CONFIG["MOZ_SYSTEM_PIPEWIRE"]:\n')
560 mb.write(' LOCAL_INCLUDES += [ "/third_party/pipewire/" ]\n')
561 except KeyError:
562 pass
563 try:
564 if relsrcdir in write_mozbuild_variables["INCLUDE_SYSTEM_LIBVPX_HANDLING"]:
565 mb.write('if not CONFIG["MOZ_SYSTEM_LIBVPX"]:\n')
566 mb.write(' LOCAL_INCLUDES += [ "/media/libvpx/libvpx/" ]\n')
567 mb.write(' CXXFLAGS += CONFIG["MOZ_LIBVPX_CFLAGS"]\n')
568 except KeyError:
569 pass
570 try:
571 if relsrcdir in write_mozbuild_variables["INCLUDE_SYSTEM_DAV1D_HANDLING"]:
572 mb.write('if CONFIG["MOZ_SYSTEM_AV1"]:\n')
573 mb.write(' CXXFLAGS += CONFIG["MOZ_SYSTEM_DAV1D_CFLAGS"]\n')
574 mb.write(' CXXFLAGS += CONFIG["MOZ_SYSTEM_LIBAOM_CFLAGS"]\n')
575 except KeyError:
576 pass
577
578 all_args = [args for args, _ in configs]
579
580 # Start with attributes that will be a part of the mozconfig
581 # for every configuration, then factor by other potentially useful
582 # combinations.
583 # FIXME: this is a time-bomb. See bug 1775202.
584 for attrs in (
585 (),
586 ("MOZ_DEBUG",),
587 ("OS_TARGET",),
588 ("TARGET_CPU",),
589 ("MOZ_DEBUG", "OS_TARGET"),
590 ("OS_TARGET", "MOZ_X11"),
591 ("OS_TARGET", "TARGET_CPU"),
592 ("OS_TARGET", "TARGET_CPU", "MOZ_X11"),
593 ("OS_TARGET", "TARGET_CPU", "MOZ_DEBUG"),
594 ("OS_TARGET", "TARGET_CPU", "MOZ_DEBUG", "MOZ_X11"),
595 ):
596 conditions = set()
597 for args in all_args:
598 cond = tuple((k, args.get(k) or "") for k in attrs)
599 conditions.add(cond)
600
601 for cond in sorted(conditions):
602 common_attrs = find_common_attrs(
603 [
604 attrs
605 for args, attrs in configs
606 if all((args.get(k) or "") == v for k, v in cond)
607 ]
608 )
609 if any(common_attrs.values()):
610 if cond:
611 mb.write_condition(dict(cond))
612 mb.write_attrs(common_attrs)
613 if cond:
614 mb.terminate_condition()
615
616 mb.finalize()
617 return target_mozbuild
618
619
620 def write_mozbuild_files(
621 topsrcdir,
622 srcdir,
623 all_mozbuild_results,
624 write_mozbuild_variables,
625 ):
626 # Translate {config -> {dirs -> build info}} into
627 # {dirs -> [(config, build_info)]}
628 configs_by_dir = defaultdict(list)
629 for config_attrs in all_mozbuild_results:
630 mozbuild_args = config_attrs["mozbuild_args"]
631 dirs = config_attrs["dirs"]
632 for d, build_data in dirs.items():
633 configs_by_dir[d].append((mozbuild_args, build_data))
634
635 mozbuilds = set()
636 # threading this section did not produce noticeable speed gains
637 for relsrcdir, configs in sorted(configs_by_dir.items()):
638 mozbuilds.add(
639 write_mozbuild(topsrcdir, write_mozbuild_variables, relsrcdir, configs)
640 )
641
642 # write the project moz.build file
643 dirs_mozbuild = mozpath.join(srcdir, "moz.build")
644 mozbuilds.add(dirs_mozbuild)
645 with open(dirs_mozbuild, "w") as fh:
646 mb = MozbuildWriter(fh)
647 mb.write(license_header)
648 mb.write("\n")
649 mb.write(generated_header)
650
651 # Not every srcdir is present for every config, which needs to be
652 # reflected in the generated root moz.build.
653 dirs_by_config = {
654 tuple(v["mozbuild_args"].items()): set(v["dirs"].keys())
655 for v in all_mozbuild_results
656 }
657
658 for attrs in (
659 (),
660 ("OS_TARGET",),
661 ("OS_TARGET", "TARGET_CPU"),
662 ("OS_TARGET", "TARGET_CPU", "MOZ_X11"),
663 ):
664 conditions = set()
665 for args in dirs_by_config.keys():
666 cond = tuple((k, dict(args).get(k) or "") for k in attrs)
667 conditions.add(cond)
668
669 for cond in sorted(conditions):
670 common_dirs = None
671 for args, dir_set in dirs_by_config.items():
672 if all((dict(args).get(k) or "") == v for k, v in cond):
673 if common_dirs is None:
674 common_dirs = deepcopy(dir_set)
675 else:
676 common_dirs &= dir_set
677
678 for args, dir_set in dirs_by_config.items():
679 if all(dict(args).get(k) == v for k, v in cond):
680 dir_set -= common_dirs
681
682 if common_dirs:
683 if cond:
684 mb.write_condition(dict(cond))
685 mb.write_mozbuild_list("DIRS", ["/%s" % d for d in common_dirs])
686 if cond:
687 mb.terminate_condition()
688
689 # Remove possibly stale moz.builds
690 for root, dirs, files in os.walk(srcdir):
691 if "moz.build" in files:
692 file = os.path.join(root, "moz.build")
693 if file not in mozbuilds:
694 os.unlink(file)
695
696
697 def generate_gn_config(
698 topsrcdir,
699 build_root_dir,
700 target_dir,
701 gn_binary,
702 input_variables,
703 sandbox_variables,
704 gn_target,
705 moz_build_flag,
706 non_unified_sources,
707 mozilla_flags,
708 ):
709 def str_for_arg(v):
710 if v in (True, False):
711 return str(v).lower()
712 return '"%s"' % v
713
714 build_root_dir = topsrcdir / build_root_dir
715 srcdir = build_root_dir / target_dir
716
717 input_variables = input_variables.copy()
718 input_variables.update(
719 {
720 f"{moz_build_flag}": True,
721 "concurrent_links": 1,
722 "action_pool_depth": 1,
723 }
724 )
725
726 if input_variables["target_os"] == "win":
727 input_variables.update(
728 {
729 "visual_studio_path": "/",
730 "visual_studio_version": 2015,
731 "wdk_path": "/",
732 }
733 )
734 if input_variables["target_os"] == "mac":
735 input_variables.update(
736 {
737 "mac_sdk_path": "/",
738 "enable_wmax_tokens": False,
739 }
740 )
741
742 gn_args = "--args=%s" % " ".join(
743 ["%s=%s" % (k, str_for_arg(v)) for k, v in input_variables.items()]
744 )
745 with tempfile.TemporaryDirectory() as tempdir:
746 # On Mac, `tempdir` starts with /var which is a symlink to /private/var.
747 # We resolve the symlinks in `tempdir` here so later usage with
748 # relpath() does not lead to unexpected results, should it be used
749 # together with another path that has symlinks resolved.
750 resolved_tempdir = Path(tempdir).resolve()
751 gen_args = [
752 gn_binary,
753 "gen",
754 str(resolved_tempdir),
755 gn_args,
756 "--ide=json",
757 "--root=./", # must find the google build directory in this directory
758 f"--dotfile={target_dir}/.gn",
759 ]
760 print('Running "%s"' % " ".join(gen_args), file=sys.stderr)
761 subprocess.check_call(gen_args, cwd=build_root_dir, stderr=subprocess.STDOUT)
762
763 gn_config_file = resolved_tempdir / "project.json"
764 with open(gn_config_file) as fh:
765 raw_json = fh.read()
766 raw_json = raw_json.replace(f"{target_dir}/", "")
767 raw_json = raw_json.replace(f"{target_dir}:", ":")
768 gn_config = json.loads(raw_json)
769 gn_config = filter_gn_config(
770 resolved_tempdir,
771 gn_config,
772 sandbox_variables,
773 input_variables,
774 gn_target,
775 )
776 gn_config = process_gn_config(
777 gn_config,
778 topsrcdir,
779 srcdir,
780 non_unified_sources,
781 gn_config["sandbox_vars"],
782 mozilla_flags,
783 )
784 return gn_config
785
786
787 def main():
788 parser = argparse.ArgumentParser()
789 parser.add_argument("config", help="configuration in json format")
790 args = parser.parse_args()
791
792 gn_binary = bootstrap_toolchain("gn/gn") or which("gn")
793 if not gn_binary:
794 raise Exception("The GN program must be present to generate GN configs.")
795
796 with open(args.config) as fh:
797 config = json.load(fh)
798
799 topsrcdir = Path(__file__).parent.parent.resolve()
800
801 vars_set = []
802 for is_debug in (True, False):
803 for target_os in ("android", "linux", "mac", "openbsd", "win"):
804 target_cpus = ["x64"]
805 if target_os in ("android", "linux", "mac", "win", "openbsd"):
806 target_cpus.append("arm64")
807 if target_os in ("android", "linux"):
808 target_cpus.append("arm")
809 if target_os in ("android", "linux", "win"):
810 target_cpus.append("x86")
811 if target_os in ("linux", "openbsd"):
812 target_cpus.append("riscv64")
813 if target_os == "linux":
814 target_cpus.extend(["loong64", "ppc64", "mipsel", "mips64el"])
815 for target_cpu in target_cpus:
816 vars = {
817 "host_cpu": "x64",
818 "is_debug": is_debug,
819 "target_cpu": target_cpu,
820 "target_os": target_os,
821 }
822 if target_os == "linux":
823 for use_x11 in (True, False):
824 vars["use_x11"] = use_x11
825 vars_set.append(vars.copy())
826 else:
827 if target_os == "openbsd":
828 vars["use_x11"] = True
829 vars_set.append(vars)
830
831 gn_configs = []
832 NUM_WORKERS = 5
833 with ProcessPoolExecutor(max_workers=NUM_WORKERS) as executor:
834 # Submit tasks to the executor
835 futures = {
836 executor.submit(
837 generate_gn_config,
838 topsrcdir,
839 config["build_root_dir"],
840 config["target_dir"],
841 gn_binary,
842 vars,
843 config["gn_sandbox_variables"],
844 config["gn_target"],
845 config["moz_build_flag"],
846 config["non_unified_sources"],
847 config["mozilla_flags"],
848 ): vars
849 for vars in vars_set
850 }
851
852 # Process completed tasks as they finish
853 for future in as_completed(futures):
854 try:
855 gn_configs.append(future.result())
856 except Exception as e:
857 print(f"[Task] Task failed with exception: {e}")
858
859 print("All generation tasks have been processed.")
860
861 print("Writing moz.build files")
862 write_mozbuild_files(
863 topsrcdir,
864 topsrcdir / config["build_root_dir"] / config["target_dir"],
865 gn_configs,
866 config["write_mozbuild_variables"],
867 )
868
869
870 if __name__ == "__main__":
871 main()