clang_configuration.bzl 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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.realpath, 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_bsd_sysroot(repository_ctx):
  76. """Look around for sysroot. Return root (/) if nothing found."""
  77. # Try it-just-works for CMake users.
  78. default = "/"
  79. sysroot = repository_ctx.os.environ.get("CMAKE_SYSROOT", default)
  80. sysroot_path = repository_ctx.path(sysroot)
  81. if sysroot_path.exists:
  82. return sysroot_path.realpath
  83. return default
  84. def _compute_clang_cpp_include_search_paths(repository_ctx, clang, sysroot):
  85. """Runs the `clang` binary and extracts the include search paths.
  86. Returns the resulting paths as a list of strings.
  87. """
  88. # Create an empty temp file for Clang to use
  89. if repository_ctx.os.name.lower().startswith("windows"):
  90. repository_ctx.file("_temp", "")
  91. # Read in an empty input file. If we are building from
  92. # Windows, then we create an empty temp file. Clang
  93. # on Windows does not like it when you pass a non-existent file.
  94. if repository_ctx.os.name.lower().startswith("windows"):
  95. repository_ctx.file("_temp", "")
  96. input_file = repository_ctx.path("_temp")
  97. else:
  98. input_file = "/dev/null"
  99. # The only way to get this out of Clang currently is to parse the verbose
  100. # output of the compiler when it is compiling C++ code.
  101. cmd = [
  102. clang,
  103. # Avoid canonicalizing away symlinks.
  104. "-no-canonical-prefixes",
  105. # Extract verbose output.
  106. "-v",
  107. # Just parse the input, don't generate outputs.
  108. "-fsyntax-only",
  109. # Force the language to be C++.
  110. "-x",
  111. "c++",
  112. # Read in an empty input file.
  113. input_file,
  114. # Always use libc++.
  115. "-stdlib=libc++",
  116. ]
  117. # We need to use a sysroot to correctly represent a run on macOS.
  118. if repository_ctx.os.name.lower().startswith("mac os"):
  119. if not sysroot:
  120. fail("Must provide a sysroot on macOS!")
  121. cmd.append("--sysroot=" + sysroot)
  122. # Note that verbose output is on stderr, not stdout!
  123. output = _run(repository_ctx, cmd).stderr.splitlines()
  124. # Return the list of directories printed for system headers. These are the
  125. # only ones that Bazel needs us to manually provide. We find these by
  126. # searching for a begin and end marker. We also have to strip off a leading
  127. # space from each path.
  128. include_begin = output.index("#include <...> search starts here:") + 1
  129. include_end = output.index("End of search list.", include_begin)
  130. # Suffix present on framework paths.
  131. framework_suffix = " (framework directory)"
  132. return [
  133. repository_ctx.path(s.lstrip(" ").removesuffix(framework_suffix))
  134. for s in output[include_begin:include_end]
  135. ]
  136. def _configure_clang_toolchain_impl(repository_ctx):
  137. # First just symlink in the untemplated parts of the toolchain repo.
  138. repository_ctx.symlink(repository_ctx.attr._clang_toolchain_build, "BUILD")
  139. repository_ctx.symlink(
  140. repository_ctx.attr._clang_cc_toolchain_config,
  141. "cc_toolchain_config.bzl",
  142. )
  143. # Find a Clang C++ compiler, and where it lives. We need to walk symlinks
  144. # here as the other LLVM tools may not be symlinked into the PATH even if
  145. # `clang` is. We also insist on finding the basename of `clang++` as that is
  146. # important for C vs. C++ compiles.
  147. (clang, clang_version, clang_version_for_cache) = _detect_system_clang(
  148. repository_ctx,
  149. )
  150. clang_cpp = clang.dirname.get_child("clang++")
  151. # Compute the various directories used by Clang.
  152. resource_dir = _compute_clang_resource_dir(repository_ctx, clang_cpp)
  153. sysroot_dir = None
  154. if repository_ctx.os.name.lower().startswith("mac os"):
  155. sysroot_dir = _compute_mac_os_sysroot(repository_ctx)
  156. if repository_ctx.os.name == "freebsd":
  157. sysroot_dir = _compute_bsd_sysroot(repository_ctx)
  158. include_dirs = _compute_clang_cpp_include_search_paths(
  159. repository_ctx,
  160. clang_cpp,
  161. sysroot_dir,
  162. )
  163. # We expect that the LLVM binutils live adjacent to llvm-ar.
  164. # First look for llvm-ar adjacent to clang, so that if found,
  165. # it is most likely to match the same version as clang.
  166. # Otherwise, try PATH.
  167. ar_path = clang.dirname.get_child("llvm-ar")
  168. if not ar_path.exists:
  169. ar_path = repository_ctx.which("llvm-ar")
  170. if not ar_path:
  171. fail("`llvm-ar` not found in PATH or adjacent to clang")
  172. # By default Windows uses '\' in its paths. These will be
  173. # interpreted as escape characters and fail the build, thus
  174. # we must manually replace the backslashes with '/'
  175. if repository_ctx.os.name.lower().startswith("windows"):
  176. resource_dir = resource_dir.replace("\\", "/")
  177. include_dirs = [str(s).replace("\\", "/") for s in include_dirs]
  178. repository_ctx.template(
  179. "clang_detected_variables.bzl",
  180. repository_ctx.attr._clang_detected_variables_template,
  181. substitutions = {
  182. "{LLVM_BINDIR}": str(ar_path.dirname),
  183. "{LLVM_SYMBOLIZER}": str(ar_path.dirname.get_child("llvm-symbolizer")),
  184. "{CLANG_BINDIR}": str(clang.dirname),
  185. "{CLANG_VERSION}": str(clang_version),
  186. "{CLANG_VERSION_FOR_CACHE}": clang_version_for_cache.replace('"', "_").replace("\\", "_"),
  187. "{CLANG_RESOURCE_DIR}": resource_dir,
  188. "{CLANG_INCLUDE_DIRS_LIST}": str(
  189. [str(path) for path in include_dirs],
  190. ),
  191. "{SYSROOT}": str(sysroot_dir),
  192. },
  193. executable = False,
  194. )
  195. configure_clang_toolchain = repository_rule(
  196. implementation = _configure_clang_toolchain_impl,
  197. configure = True,
  198. local = True,
  199. attrs = {
  200. "_clang_toolchain_build": attr.label(
  201. default = Label("//bazel/cc_toolchains:clang_toolchain.BUILD"),
  202. allow_single_file = True,
  203. ),
  204. "_clang_cc_toolchain_config": attr.label(
  205. default = Label(
  206. "//bazel/cc_toolchains:clang_cc_toolchain_config.bzl",
  207. ),
  208. allow_single_file = True,
  209. ),
  210. "_clang_detected_variables_template": attr.label(
  211. default = Label(
  212. "//bazel/cc_toolchains:clang_detected_variables.tpl.bzl",
  213. ),
  214. allow_single_file = True,
  215. ),
  216. },
  217. environ = ["CC"],
  218. )