Debian Codegraph @

toolchain/mac_toolchain_config.bzl

raw
1 """
2 This file specifies a clang toolchain that can run on a Mac host (with either M1 or Intel CPU).
3
4 Hermetic toolchains still need access to Xcode for sys headers included in Skia's codebase.
5
6 See download_mac_toolchain.bzl for more details on the creation of the toolchain.
7
8 It uses the usr subfolder of the built toolchain as a sysroot
9
10 It follows the example of:
11 - linux_amd64_toolchain_config.bzl
12 """
13
14 # https://github.com/bazelbuild/bazel/blob/master/tools/build_defs/cc/action_names.bzl
15 load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
16
17 # https://github.com/bazelbuild/bazel/blob/master/tools/cpp/cc_toolchain_config_lib.bzl
18 load(
19 "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
20 "action_config",
21 "feature",
22 "flag_group",
23 "flag_set",
24 "tool",
25 "variable_with_value",
26 )
27 load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
28 load(":clang_layering_check.bzl", "make_layering_check_features")
29
30 # The location of the created clang toolchain.
31 EXTERNAL_TOOLCHAIN = "external/+_repo_rules2+clang_mac"
32
33 # Root of our symlinks. These symlinks are created in download_mac_toolchain.bzl
34 XCODE_MACSDK_SYMLINK = EXTERNAL_TOOLCHAIN + "/symlinks/xcode/MacSDK"
35
36 # Must stay in sync with download_mac_toolchain.bzl.
37 CLANG_VER = "22"
38
39 _platform_constraints_to_import = {
40 "@platforms//cpu:arm64": "_arm64_cpu",
41 "@platforms//cpu:x86_64": "_x86_64_cpu",
42 }
43
44 def _mac_toolchain_info(ctx):
45 action_configs = _make_action_configs()
46 features = []
47 features += _make_default_flags(ctx)
48 features += make_layering_check_features()
49 features += _make_diagnostic_flags()
50 features += _make_target_specific_flags(ctx)
51
52 # https://bazel.build/rules/lib/cc_common#create_cc_toolchain_config_info
53 # Note, this rule is defined in Java code, not Starlark
54 # https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/starlarkbuildapi/cpp/CcModuleApi.java
55 return cc_common.create_cc_toolchain_config_info(
56 ctx = ctx,
57 features = features,
58 action_configs = action_configs,
59 builtin_sysroot = EXTERNAL_TOOLCHAIN,
60 cxx_builtin_include_directories = [
61 # https://stackoverflow.com/a/61419490
62 # "If the compiler has --sysroot support, then these paths should use %sysroot%
63 # rather than the include path"
64 # https://bazel.build/rules/lib/cc_common#create_cc_toolchain_config_info.cxx_builtin_include_directories
65 "%sysroot%/symlinks/xcode/MacSDK/System/Library/Frameworks/",
66 ],
67 # If `ctx.attr.cpu` is blank (which is declared as optional below), this config will target
68 # the host CPU. Specifying a target_cpu allows this config to be used for cross compilation.
69 target_cpu = ctx.attr.cpu,
70 # These are required, but do nothing
71 compiler = "",
72 target_libc = "",
73 target_system_name = "",
74 toolchain_identifier = "",
75 )
76
77 def _import_platform_constraints():
78 # In order to "import" constraint values so they can be passed in as parameters to
79 # ctx.target_platform_has_constraint(), we need to list them as a default value on a
80 # private attributes. It doesn't really matter what we call these private attributes,
81 # but to make it easier to read elsewhere, we create a mapping between the "official"
82 # name of the constraints and the private name. Then, we can refer to the official name
83 # without having to remember the secondary name.
84 # https://bazel.build/rules/rules#private_attributes_and_implicit_dependencies
85 # https://github.com/bazelbuild/proposals/blob/91579f36031f768bcf68b18a86b8df8b43cc590b/designs/2019-11-11-target-platform-constraints.md
86 rule_attributes = {}
87 for constraint in _platform_constraints_to_import:
88 private_attr = _platform_constraints_to_import[constraint]
89 rule_attributes[private_attr] = attr.label(default = constraint)
90
91 # Define an optional attribute to allow the target architecture to be explicitly specified (e.g.
92 # when selecting a cross-compilation toolchain).
93 rule_attributes["cpu"] = attr.string(
94 mandatory = False,
95 values = ["arm64", "x64"],
96 )
97 return rule_attributes
98
99 def _has_platform_constraint(ctx, official_constraint_name):
100 # ctx is of type https://bazel.build/rules/lib/ctx
101 # This pattern is from
102 # https://github.com/bazelbuild/proposals/blob/91579f36031f768bcf68b18a86b8df8b43cc590b/designs/2019-11-11-target-platform-constraints.md
103 private_attr = _platform_constraints_to_import[official_constraint_name]
104 constraint = getattr(ctx.attr, private_attr)[platform_common.ConstraintValueInfo]
105 return ctx.target_platform_has_constraint(constraint)
106
107 provide_mac_toolchain_config = rule(
108 attrs = _import_platform_constraints(),
109 provides = [CcToolchainConfigInfo],
110 implementation = _mac_toolchain_info,
111 )
112
113 def _make_action_configs():
114 """
115 This function sets up the tools needed to perform the various compile/link actions.
116
117 Bazel normally restricts us to referring to (and therefore running) executables/scripts
118 that are in this directory (That is EXEC_ROOT/toolchain). However, the executables we want
119 to run are brought in via WORKSPACE.bazel and are located in EXEC_ROOT/external/clang....
120 Therefore, we make use of "trampoline scripts" that will call the binaries from the
121 toolchain directory.
122
123 These action_configs also let us dynamically specify arguments from the Bazel
124 environment if necessary (see cpp_link_static_library_action).
125 """
126
127 # https://cs.opensource.google/bazel/bazel/+/master:tools/cpp/cc_toolchain_config_lib.bzl;l=435;drc=3b9e6f201a9a3465720aad8712ab7bcdeaf2e5da
128 clang_tool = tool(path = "mac_trampolines/clang_trampoline_mac.sh")
129 ar_tool = tool(path = "mac_trampolines/ar_trampoline_mac.sh")
130
131 # https://cs.opensource.google/bazel/bazel/+/master:tools/cpp/cc_toolchain_config_lib.bzl;l=488;drc=3b9e6f201a9a3465720aad8712ab7bcdeaf2e5da
132 assemble_action = action_config(
133 action_name = ACTION_NAMES.assemble,
134 tools = [clang_tool],
135 )
136 c_compile_action = action_config(
137 action_name = ACTION_NAMES.c_compile,
138 tools = [clang_tool],
139 )
140 cpp_compile_action = action_config(
141 action_name = ACTION_NAMES.cpp_compile,
142 tools = [clang_tool],
143 )
144 objc_compile_action = action_config(
145 action_name = ACTION_NAMES.objc_compile,
146 tools = [clang_tool],
147 )
148 objcpp_compile_action = action_config(
149 action_name = ACTION_NAMES.objcpp_compile,
150 tools = [clang_tool],
151 )
152 linkstamp_compile_action = action_config(
153 action_name = ACTION_NAMES.linkstamp_compile,
154 tools = [clang_tool],
155 )
156 preprocess_assemble_action = action_config(
157 action_name = ACTION_NAMES.preprocess_assemble,
158 tools = [clang_tool],
159 )
160
161 cpp_link_dynamic_library_action = action_config(
162 action_name = ACTION_NAMES.cpp_link_dynamic_library,
163 tools = [clang_tool],
164 )
165 cpp_link_executable_action = action_config(
166 action_name = ACTION_NAMES.cpp_link_executable,
167 # Bazel assumes it is talking to clang when building an executable. There are
168 # "-Wl" flags on the command: https://releases.llvm.org/6.0.1/tools/clang/docs/ClangCommandLineReference.html#cmdoption-clang-Wl
169 tools = [clang_tool],
170 )
171 cpp_link_nodeps_dynamic_library_action = action_config(
172 action_name = ACTION_NAMES.cpp_link_nodeps_dynamic_library,
173 tools = [clang_tool],
174 )
175
176 # objc archiver and cpp archiver actions use the same base flags
177 common_archive_flags = [
178 flag_set(
179 flag_groups = [
180 flag_group(
181 # https://llvm.org/docs/CommandGuide/llvm-ar.html
182 # [r]eplace existing files or insert them if they already exist,
183 # [c]reate the file if it doesn't already exist
184 # [s]ymbol table should be added
185 # [D]eterministic timestamps should be used
186 flags = ["rcsD", "%{output_execpath}"],
187 # Despite the name, output_execpath just refers to linker output,
188 # e.g. libFoo.a
189 expand_if_available = "output_execpath",
190 ),
191 ],
192 ),
193 flag_set(
194 flag_groups = [
195 flag_group(
196 iterate_over = "libraries_to_link",
197 flag_groups = [
198 flag_group(
199 flags = ["%{libraries_to_link.name}"],
200 expand_if_equal = variable_with_value(
201 name = "libraries_to_link.type",
202 value = "object_file",
203 ),
204 ),
205 flag_group(
206 flags = ["%{libraries_to_link.object_files}"],
207 iterate_over = "libraries_to_link.object_files",
208 expand_if_equal = variable_with_value(
209 name = "libraries_to_link.type",
210 value = "object_file_group",
211 ),
212 ),
213 ],
214 expand_if_available = "libraries_to_link",
215 ),
216 ],
217 ),
218 flag_set(
219 flag_groups = [
220 flag_group(
221 flags = ["@%{linker_param_file}"],
222 expand_if_available = "linker_param_file",
223 ),
224 ],
225 ),
226 ]
227
228 # This is the same rule as
229 # https://github.com/emscripten-core/emsdk/blob/7f39d100d8cd207094decea907121df72065517e/bazel/emscripten_toolchain/crosstool.bzl#L143
230 # By default, there are no flags or libraries passed to the llvm-ar tool, so
231 # we need to specify them. The variables mentioned by expand_if_available are defined
232 # https://bazel.build/docs/cc-toolchain-config-reference#cctoolchainconfiginfo-build-variables
233 cpp_link_static_library_action = action_config(
234 action_name = ACTION_NAMES.cpp_link_static_library,
235 flag_sets = common_archive_flags,
236 tools = [ar_tool],
237 )
238
239 action_configs = [
240 assemble_action,
241 c_compile_action,
242 cpp_compile_action,
243 cpp_link_dynamic_library_action,
244 cpp_link_executable_action,
245 cpp_link_nodeps_dynamic_library_action,
246 cpp_link_static_library_action,
247 linkstamp_compile_action,
248 objc_compile_action,
249 objcpp_compile_action,
250 preprocess_assemble_action,
251 ]
252 return action_configs
253
254 # In addition to pointing the c and cpp compile actions to our toolchain, we also need to set objc
255 # and objcpp action flags as well. We build .m and .mm files with the objc_library rule, which
256 # will use the default toolchain if not specified here.
257 # https://docs.bazel.build/versions/3.3.0/be/objective-c.html#objc_library
258 #
259 # Note: These values must be kept in sync with those defined in cmake_exporter.go.
260 def _make_default_flags(ctx):
261 """Here we define the flags for certain actions that are always applied.
262
263 For any flag that might be conditionally applied, it should be defined in //bazel/copts.bzl.
264
265 Flags that are set here will be unconditionally applied to everything we compile with
266 this toolchain, even third_party deps.
267
268 """
269 cxx_compile_includes = flag_set(
270 actions = [
271 ACTION_NAMES.c_compile,
272 ACTION_NAMES.cpp_compile,
273 ACTION_NAMES.objc_compile,
274 ACTION_NAMES.objcpp_compile,
275 ],
276 flag_groups = [
277 flag_group(
278 flags = [
279 # THIS ORDER MATTERS GREATLY. If these are in the wrong order, we see errors
280 # like "error: unknown type name 'size_t'". We want the C++ standard library
281 # headers and then the internal clang version to "fulfill" any missing types
282 # before we get to the other includes from the SDK and frameworks
283 "-isystem",
284 XCODE_MACSDK_SYMLINK + "/usr/include/c++/v1",
285 "-isystem",
286 EXTERNAL_TOOLCHAIN + "/lib/clang/" + CLANG_VER + "/include",
287 "-isystem",
288 XCODE_MACSDK_SYMLINK + "/usr/include",
289 # Set the framework path to the Mac SDK framework directory. This has
290 # subfolders like OpenGL.framework
291 # We want -iframework so Clang hides diagnostic warnings from those header
292 # files we include. -F does not hide those.
293 "-iframework",
294 XCODE_MACSDK_SYMLINK + "/System/Library/Frameworks",
295 # We do not want clang to search in absolute paths for files. This makes
296 # Bazel think we are using an outside resource and fail the compile.
297 "-no-canonical-prefixes",
298 ],
299 ),
300 ],
301 )
302
303 cpp_compile_flags = flag_set(
304 actions = [
305 ACTION_NAMES.cpp_compile,
306 ACTION_NAMES.objc_compile,
307 ACTION_NAMES.objcpp_compile,
308 ],
309 flag_groups = [
310 flag_group(
311 flags = [
312 "-std=c++20",
313 ],
314 ),
315 ],
316 )
317
318 # copts and defines appear to not automatically be set
319 # https://bazel.build/docs/cc-toolchain-config-reference#cctoolchainconfiginfo-build-variables
320 # https://github.com/bazelbuild/bazel/blob/5ad4a6126be2bdc53ee7e2457e076c90efe86d56/tools/cpp/cc_toolchain_config_lib.bzl#L200-L209
321 objc_compile_flags = flag_set(
322 actions = [
323 ACTION_NAMES.objc_compile,
324 ACTION_NAMES.objcpp_compile,
325 ],
326 flag_groups = [
327 flag_group(
328 iterate_over = "user_compile_flags",
329 flags = ["%{user_compile_flags}"],
330 ),
331 flag_group(
332 iterate_over = "preprocessor_defines",
333 flags = ["-D%{preprocessor_defines}"],
334 ),
335 ],
336 )
337
338 link_exe_flags = flag_set(
339 actions = [
340 ACTION_NAMES.cpp_link_executable,
341 ACTION_NAMES.cpp_link_dynamic_library,
342 ACTION_NAMES.cpp_link_nodeps_dynamic_library,
343 ],
344 flag_groups = [
345 flag_group(
346 flags = [
347 # lld goes through dynamic library dependencies for dylib and tbh files through
348 # absolute paths (/System/Library/Frameworks). However, the dependencies live in
349 # [Xcode dir]/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks
350 # -Wl tells clang to forward the next flag to the linker.
351 # -syslibroot appends to the beginning of the dylib dependency path.
352 # https://github.com/llvm/llvm-project/blob/d61341768cf0cff7ceeaddecc2f769b5c1b901c4/lld/MachO/InputFiles.cpp#L1418-L1420
353 "-Wl,-syslibroot",
354 XCODE_MACSDK_SYMLINK,
355 # This path is relative to the syslibroot above, and we want lld to look in the
356 # Frameworks symlink that was created in download_mac_toolchain.bzl.
357 "-F/System/Library/Frameworks",
358 "-fuse-ld=lld",
359 "-std=c++20",
360 # Link against gnu libc that's in the Mac SDK.
361 "-lc++",
362 ],
363 ),
364 ],
365 )
366
367 return [feature(
368 "default_flags",
369 enabled = True,
370 flag_sets = [
371 cpp_compile_flags,
372 cxx_compile_includes,
373 link_exe_flags,
374 objc_compile_flags,
375 ],
376 )]
377
378 def _make_diagnostic_flags():
379 """Here we define the flags that can be turned on via features to yield debug info."""
380 cxx_diagnostic = flag_set(
381 actions = [
382 ACTION_NAMES.c_compile,
383 ACTION_NAMES.cpp_compile,
384 ],
385 flag_groups = [
386 flag_group(
387 flags = [
388 "--trace-includes",
389 "-v",
390 ],
391 ),
392 ],
393 )
394
395 link_diagnostic = flag_set(
396 actions = [ACTION_NAMES.cpp_link_executable],
397 flag_groups = [
398 flag_group(
399 flags = [
400 "-Wl,--verbose",
401 "-v",
402 ],
403 ),
404 ],
405 )
406
407 link_search_dirs = flag_set(
408 actions = [ACTION_NAMES.cpp_link_executable],
409 flag_groups = [
410 flag_group(
411 flags = [
412 "--print-search-dirs",
413 ],
414 ),
415 ],
416 )
417 return [
418 # Running a Bazel command with --features diagnostic will cause the compilation and
419 # link steps to be more verbose.
420 feature(
421 "diagnostic",
422 enabled = False,
423 flag_sets = [
424 cxx_diagnostic,
425 link_diagnostic,
426 ],
427 ),
428 feature(
429 "link_diagnostic",
430 enabled = False,
431 flag_sets = [
432 link_diagnostic,
433 ],
434 ),
435 # Running a Bazel command with --features print_search_dirs will cause the link to fail
436 # but directories searched for libraries, etc will be displayed.
437 feature(
438 "print_search_dirs",
439 enabled = False,
440 flag_sets = [
441 link_search_dirs,
442 ],
443 ),
444 ]
445
446 # The parameter is of type https://bazel.build/rules/lib/ctx
447 def _make_target_specific_flags(ctx):
448 m1_mac_target = flag_set(
449 actions = [
450 ACTION_NAMES.assemble,
451 ACTION_NAMES.preprocess_assemble,
452 ACTION_NAMES.c_compile,
453 ACTION_NAMES.cpp_compile,
454 ACTION_NAMES.objc_compile,
455 ACTION_NAMES.objcpp_compile,
456 ACTION_NAMES.cpp_link_executable,
457 ACTION_NAMES.cpp_link_dynamic_library,
458 ],
459 flag_groups = [
460 flag_group(
461 flags = [
462 "--target=arm64-apple-macos12",
463 ],
464 ),
465 ],
466 )
467 intel_mac_target = flag_set(
468 actions = [
469 ACTION_NAMES.assemble,
470 ACTION_NAMES.preprocess_assemble,
471 ACTION_NAMES.c_compile,
472 ACTION_NAMES.cpp_compile,
473 ACTION_NAMES.objc_compile,
474 ACTION_NAMES.objcpp_compile,
475 ACTION_NAMES.cpp_link_executable,
476 ACTION_NAMES.cpp_link_dynamic_library,
477 ],
478 flag_groups = [
479 flag_group(
480 flags = [
481 "--target=x86_64-apple-macos12",
482 ],
483 ),
484 ],
485 )
486
487 target_specific_features = []
488 if _has_platform_constraint(ctx, "@platforms//cpu:arm64"):
489 target_specific_features.append(
490 feature(
491 name = "_m1_mac_target",
492 enabled = True,
493 flag_sets = [m1_mac_target],
494 ),
495 )
496 elif _has_platform_constraint(ctx, "@platforms//cpu:x86_64"):
497 target_specific_features.append(
498 feature(
499 name = "_intel_mac_target",
500 enabled = True,
501 flag_sets = [intel_mac_target],
502 ),
503 )
504
505 return target_specific_features