clang_configuration.bzl 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. # Exceptions. See /LICENSE for license information.
  3. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. """Starlark repository rules to configure Clang (and LLVM) toolchain for Bazel.
  5. These rules should be run from the `WORKSPACE` file to substitute appropriate
  6. configured values into a `clang_detected_variables.bzl` file that can be used
  7. by the actual toolchain configuration.
  8. """
  9. def _run(repository_ctx, cmd):
  10. """Runs the provided `cmd`, checks for failure, and returns the result."""
  11. exec_result = repository_ctx.execute(cmd)
  12. if exec_result.return_code != 0:
  13. fail("Unable to run command successfully: %s" % str(cmd))
  14. return exec_result
  15. def _clang_version(version_output):
  16. """Returns version information, or a (None, "unknown") tuple if not found.
  17. Returns both the major version number (14) and the full version number for
  18. caching.
  19. """
  20. clang_version = None
  21. clang_version_for_cache = "unknown"
  22. version_prefix = "clang version "
  23. version_start = version_output.find(version_prefix)
  24. if version_start == -1:
  25. # No version
  26. return (clang_version, clang_version_for_cache)
  27. version_start += len(version_prefix)
  28. # Find the newline.
  29. version_newline = version_output.find("\n", version_start)
  30. if version_newline == -1:
  31. return (clang_version, clang_version_for_cache)
  32. clang_version_for_cache = version_output[version_start:version_newline]
  33. # Find a dot to indicate something like 'clang version 14.0.6', and grab the
  34. # major version.
  35. version_dot = version_output.find(".", version_start)
  36. if version_dot != -1 and version_dot < version_newline:
  37. clang_version = int(version_output[version_start:version_dot])
  38. return (clang_version, clang_version_for_cache)
  39. def _detect_system_clang(repository_ctx):
  40. """Detects whether the system-provided clang can be used.
  41. Returns a tuple of (is_clang, environment).
  42. """
  43. # If the user provides an explicit `CC` environment variable, use that as
  44. # the compiler. This should point at the `clang` executable to use.
  45. cc = repository_ctx.os.environ.get("CC")
  46. cc_path = None
  47. if cc:
  48. cc_path = repository_ctx.path(cc)
  49. if not cc_path.exists:
  50. cc_path = repository_ctx.which(cc)
  51. if not cc_path:
  52. cc_path = repository_ctx.which("clang")
  53. if not cc_path:
  54. fail("Cannot find clang or CC (%s); either correct your path or set the CC environment variable" % cc)
  55. version_output = _run(repository_ctx, [cc_path, "--version"]).stdout
  56. if "clang" not in version_output:
  57. fail("Searching for clang or CC (%s), and found (%s), which is not a Clang compiler" % (cc, cc_path))
  58. clang_version, clang_version_for_cache = _clang_version(version_output)
  59. return (cc_path, clang_version, clang_version_for_cache)
  60. def _compute_clang_resource_dir(repository_ctx, clang):
  61. """Runs the `clang` binary to get its resource dir."""
  62. output = _run(
  63. repository_ctx,
  64. [clang, "-no-canonical-prefixes", "--print-resource-dir"],
  65. ).stdout
  66. # The only line printed is this path.
  67. return output.splitlines()[0]
  68. def _compute_mac_os_sysroot(repository_ctx):
  69. """Runs `xcrun` to extract the correct sysroot."""
  70. xcrun = repository_ctx.which("xcrun")
  71. if not xcrun:
  72. fail("`xcrun` not found: is Xcode installed?")
  73. output = _run(repository_ctx, [xcrun, "--show-sdk-path"]).stdout
  74. return output.splitlines()[0]
  75. def _compute_clang_cpp_include_search_paths(repository_ctx, clang, sysroot):
  76. """Runs the `clang` binary and extracts the include search paths.
  77. Returns the resulting paths as a list of strings.
  78. """
  79. # Create an empty temp file for Clang to use
  80. if repository_ctx.os.name.lower().startswith("windows"):
  81. repository_ctx.file("_temp", "")
  82. # Read in an empty input file. If we are building from
  83. # Windows, then we create an empty temp file. Clang
  84. # on Windows does not like it when you pass a non-existent file.
  85. if repository_ctx.os.name.lower().startswith("windows"):
  86. repository_ctx.file("_temp", "")
  87. input_file = repository_ctx.path("_temp")
  88. else:
  89. input_file = "/dev/null"
  90. # The only way to get this out of Clang currently is to parse the verbose
  91. # output of the compiler when it is compiling C++ code.
  92. cmd = [
  93. clang,
  94. # Avoid canonicalizing away symlinks.
  95. "-no-canonical-prefixes",
  96. # Extract verbose output.
  97. "-v",
  98. # Just parse the input, don't generate outputs.
  99. "-fsyntax-only",
  100. # Force the language to be C++.
  101. "-x",
  102. "c++",
  103. # Read in an empty input file.
  104. input_file,
  105. # Always use libc++.
  106. "-stdlib=libc++",
  107. ]
  108. # We need to use a sysroot to correctly represent a run on macOS.
  109. if repository_ctx.os.name.lower().startswith("mac os"):
  110. if not sysroot:
  111. fail("Must provide a sysroot on macOS!")
  112. cmd.append("--sysroot=" + sysroot)
  113. # Note that verbose output is on stderr, not stdout!
  114. output = _run(repository_ctx, cmd).stderr.splitlines()
  115. # Return the list of directories printed for system headers. These are the
  116. # only ones that Bazel needs us to manually provide. We find these by
  117. # searching for a begin and end marker. We also have to strip off a leading
  118. # space from each path.
  119. include_begin = output.index("#include <...> search starts here:") + 1
  120. include_end = output.index("End of search list.", include_begin)
  121. # Suffix present on framework paths.
  122. framework_suffix = " (framework directory)"
  123. return [
  124. repository_ctx.path(s.lstrip(" ").removesuffix(framework_suffix))
  125. for s in output[include_begin:include_end]
  126. ]
  127. def _configure_clang_toolchain_impl(repository_ctx):
  128. # First just symlink in the untemplated parts of the toolchain repo.
  129. repository_ctx.symlink(repository_ctx.attr._clang_toolchain_build, "BUILD")
  130. repository_ctx.symlink(
  131. repository_ctx.attr._clang_cc_toolchain_config,
  132. "cc_toolchain_config.bzl",
  133. )
  134. # Find a Clang C++ compiler, and where it lives. We need to walk symlinks
  135. # here as the other LLVM tools may not be symlinked into the PATH even if
  136. # `clang` is. We also insist on finding the basename of `clang++` as that is
  137. # important for C vs. C++ compiles.
  138. (clang, clang_version, clang_version_for_cache) = _detect_system_clang(
  139. repository_ctx,
  140. )
  141. clang = clang.realpath.dirname.get_child("clang++")
  142. # Compute the various directories used by Clang.
  143. resource_dir = _compute_clang_resource_dir(repository_ctx, clang)
  144. sysroot_dir = None
  145. if repository_ctx.os.name.lower().startswith("mac os"):
  146. sysroot_dir = _compute_mac_os_sysroot(repository_ctx)
  147. include_dirs = _compute_clang_cpp_include_search_paths(
  148. repository_ctx,
  149. clang,
  150. sysroot_dir,
  151. )
  152. # We expect that the LLVM binutils live adjacent to llvm-ar.
  153. # First look for llvm-ar adjacent to clang, so that if found,
  154. # it is most likely to match the same version as clang.
  155. # Otherwise, try PATH.
  156. arpath = clang.dirname.get_child("llvm-ar")
  157. if not arpath.exists:
  158. arpath = repository_ctx.which("llvm-ar")
  159. if not arpath:
  160. fail("`llvm-ar` not found in PATH or adjacent to clang")
  161. # By default Windows uses '\' in its paths. These will be
  162. # interpreted as escape characters and fail the build, thus
  163. # we must manually replace the backslashes with '/'
  164. if repository_ctx.os.name.lower().startswith("windows"):
  165. resource_dir = resource_dir.replace("\\", "/")
  166. include_dirs = [str(s).replace("\\", "/") for s in include_dirs]
  167. repository_ctx.template(
  168. "clang_detected_variables.bzl",
  169. repository_ctx.attr._clang_detected_variables_template,
  170. substitutions = {
  171. "{LLVM_BINDIR}": str(arpath.dirname),
  172. "{CLANG_BINDIR}": str(clang.dirname),
  173. "{CLANG_VERSION}": str(clang_version),
  174. "{CLANG_VERSION_FOR_CACHE}": clang_version_for_cache.replace('"', "_").replace("\\", "_"),
  175. "{CLANG_RESOURCE_DIR}": resource_dir,
  176. "{CLANG_INCLUDE_DIRS_LIST}": str(
  177. [str(path) for path in include_dirs],
  178. ),
  179. "{SYSROOT}": str(sysroot_dir),
  180. },
  181. executable = False,
  182. )
  183. configure_clang_toolchain = repository_rule(
  184. implementation = _configure_clang_toolchain_impl,
  185. configure = True,
  186. local = True,
  187. attrs = {
  188. "_clang_toolchain_build": attr.label(
  189. default = Label("//bazel/cc_toolchains:clang_toolchain.BUILD"),
  190. allow_single_file = True,
  191. ),
  192. "_clang_cc_toolchain_config": attr.label(
  193. default = Label(
  194. "//bazel/cc_toolchains:clang_cc_toolchain_config.bzl",
  195. ),
  196. allow_single_file = True,
  197. ),
  198. "_clang_detected_variables_template": attr.label(
  199. default = Label(
  200. "//bazel/cc_toolchains:clang_detected_variables.tpl.bzl",
  201. ),
  202. allow_single_file = True,
  203. ),
  204. },
  205. environ = ["CC"],
  206. )