build.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. use std::{
  2. env,
  3. ffi::OsString,
  4. fs,
  5. io::{BufRead as _, BufReader},
  6. path::PathBuf,
  7. process::{Child, Command, Output, Stdio},
  8. };
  9. use cargo_metadata::{
  10. Artifact, CompilerMessage, Message, Metadata, MetadataCommand, Package, Target,
  11. };
  12. use xtask::{exec, AYA_BUILD_INTEGRATION_BPF, LIBBPF_DIR};
  13. /// This crate has a runtime dependency on artifacts produced by the `integration-ebpf` crate. This
  14. /// would be better expressed as one or more [artifact-dependencies][bindeps] but issues such as:
  15. /// * https://github.com/rust-lang/cargo/issues/12374
  16. /// * https://github.com/rust-lang/cargo/issues/12375
  17. /// * https://github.com/rust-lang/cargo/issues/12385
  18. /// prevent their use for the time being.
  19. ///
  20. /// This file, along with the xtask crate, allows analysis tools such as `cargo check`, `cargo
  21. /// clippy`, and even `cargo build` to work as users expect. Prior to this file's existence, this
  22. /// crate's undeclared dependency on artifacts from `integration-ebpf` would cause build (and `cargo check`,
  23. /// and `cargo clippy`) failures until the user ran certain other commands in the workspace. Conversely,
  24. /// those same tools (e.g. cargo test --no-run) would produce stale results if run naively because
  25. /// they'd make use of artifacts from a previous build of `integration-ebpf`.
  26. ///
  27. /// Note that this solution is imperfect: in particular it has to balance correctness with
  28. /// performance; an environment variable is used to replace true builds of `integration-ebpf` with
  29. /// stubs to preserve the property that code generation and linking (in `integration-ebpf`) do not
  30. /// occur on metadata-only actions such as `cargo check` or `cargo clippy` of this crate. This means
  31. /// that naively attempting to `cargo test --no-run` this crate will produce binaries that fail at
  32. /// runtime because the stubs are inadequate for actually running the tests.
  33. ///
  34. /// [bindeps]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html?highlight=feature#artifact-dependencies
  35. fn main() {
  36. println!("cargo:rerun-if-env-changed={}", AYA_BUILD_INTEGRATION_BPF);
  37. let build_integration_bpf = env::var(AYA_BUILD_INTEGRATION_BPF)
  38. .as_deref()
  39. .map(str::parse)
  40. .map(Result::unwrap)
  41. .unwrap_or_default();
  42. let Metadata { packages, .. } = MetadataCommand::new().no_deps().exec().unwrap();
  43. let integration_ebpf_package = packages
  44. .into_iter()
  45. .find(|Package { name, .. }| name == "integration-ebpf")
  46. .unwrap();
  47. let manifest_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
  48. let manifest_dir = PathBuf::from(manifest_dir);
  49. let out_dir = env::var_os("OUT_DIR").unwrap();
  50. let out_dir = PathBuf::from(out_dir);
  51. let endian = env::var_os("CARGO_CFG_TARGET_ENDIAN").unwrap();
  52. let target = if endian == "big" {
  53. "bpfeb"
  54. } else if endian == "little" {
  55. "bpfel"
  56. } else {
  57. panic!("unsupported endian={:?}", endian)
  58. };
  59. const C_BPF: &[(&str, bool)] = &[
  60. ("ext.bpf.c", false),
  61. ("main.bpf.c", false),
  62. ("multimap-btf.bpf.c", false),
  63. ("reloc.bpf.c", true),
  64. ("text_64_64_reloc.c", false),
  65. ];
  66. if build_integration_bpf {
  67. let libbpf_dir = manifest_dir
  68. .parent()
  69. .unwrap()
  70. .parent()
  71. .unwrap()
  72. .join(LIBBPF_DIR);
  73. println!("cargo:rerun-if-changed={}", libbpf_dir.to_str().unwrap());
  74. let libbpf_headers_dir = out_dir.join("libbpf_headers");
  75. let mut includedir = OsString::new();
  76. includedir.push("INCLUDEDIR=");
  77. includedir.push(&libbpf_headers_dir);
  78. exec(
  79. Command::new("make")
  80. .arg("-C")
  81. .arg(libbpf_dir.join("src"))
  82. .arg(includedir)
  83. .arg("install_headers"),
  84. )
  85. .unwrap();
  86. let bpf_dir = manifest_dir.join("bpf");
  87. let mut target_arch = OsString::new();
  88. target_arch.push("-D__TARGET_ARCH_");
  89. let arch = env::var_os("CARGO_CFG_TARGET_ARCH").unwrap();
  90. if arch == "x86_64" {
  91. target_arch.push("x86");
  92. } else if arch == "aarch64" {
  93. target_arch.push("arm64");
  94. } else {
  95. target_arch.push(&arch);
  96. };
  97. // NB: libbpf's documentation suggests that vmlinux.h be generated by running `bpftool btf
  98. // dump file /sys/kernel/btf/vmlinux format c`; this allows CO-RE to work.
  99. //
  100. // However in our tests we do not make use of kernel data structures, and so any vmlinux.h
  101. // which defines the constants we need (e.g. `__u8`, `__u64`, `BPF_MAP_TYPE_ARRAY`,
  102. // `BPF_ANY`, `XDP_PASS`, `XDP_DROP`, etc.) will suffice. Since we already have a libbpf
  103. // submodule which happens to include such a file, we use it.
  104. let libbpf_vmlinux_dir = libbpf_dir.join(".github/actions/build-selftests");
  105. let clang = || {
  106. let mut cmd = Command::new("clang");
  107. cmd.arg("-nostdlibinc")
  108. .arg("-I")
  109. .arg(&libbpf_headers_dir)
  110. .arg("-I")
  111. .arg(&libbpf_vmlinux_dir)
  112. .args(["-g", "-O2", "-target", target, "-c"])
  113. .arg(&target_arch);
  114. cmd
  115. };
  116. for (src, build_btf) in C_BPF {
  117. let dst = out_dir.join(src).with_extension("o");
  118. let src = bpf_dir.join(src);
  119. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  120. exec(clang().arg(&src).arg("-o").arg(&dst)).unwrap();
  121. if *build_btf {
  122. let mut cmd = clang();
  123. let mut child = cmd
  124. .arg("-DTARGET")
  125. .arg(&src)
  126. .args(["-o", "-"])
  127. .stdout(Stdio::piped())
  128. .spawn()
  129. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  130. let Child { stdout, .. } = &mut child;
  131. let stdout = stdout.take().unwrap();
  132. let dst = dst.with_extension("target.o");
  133. let mut output = OsString::new();
  134. output.push(".BTF=");
  135. output.push(dst);
  136. exec(
  137. // NB: objcopy doesn't support reading from stdin, so we have to use llvm-objcopy.
  138. Command::new("llvm-objcopy")
  139. .arg("--dump-section")
  140. .arg(output)
  141. .arg("-")
  142. .stdin(stdout),
  143. )
  144. .unwrap();
  145. let output = child
  146. .wait_with_output()
  147. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  148. let Output { status, .. } = &output;
  149. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {output:?}");
  150. }
  151. }
  152. let target = format!("{target}-unknown-none");
  153. let Package { manifest_path, .. } = integration_ebpf_package;
  154. let integration_ebpf_dir = manifest_path.parent().unwrap();
  155. // We have a build-dependency on `integration-ebpf`, so cargo will automatically rebuild us
  156. // if `integration-ebpf`'s *library* target or any of its dependencies change. Since we
  157. // depend on `integration-ebpf`'s *binary* targets, that only gets us half of the way. This
  158. // stanza ensures cargo will rebuild us on changes to the binaries too, which gets us the
  159. // rest of the way.
  160. println!("cargo:rerun-if-changed={}", integration_ebpf_dir.as_str());
  161. let mut cmd = Command::new("cargo");
  162. cmd.args([
  163. "build",
  164. "-Z",
  165. "build-std=core",
  166. "--bins",
  167. "--message-format=json",
  168. "--release",
  169. "--target",
  170. &target,
  171. ]);
  172. cmd.env("CARGO_CFG_BPF_TARGET_ARCH", arch);
  173. // Workaround to make sure that the rust-toolchain.toml is respected.
  174. for key in ["RUSTUP_TOOLCHAIN", "RUSTC"] {
  175. cmd.env_remove(key);
  176. }
  177. cmd.current_dir(integration_ebpf_dir);
  178. // Workaround for https://github.com/rust-lang/cargo/issues/6412 where cargo flocks itself.
  179. let ebpf_target_dir = out_dir.join("integration-ebpf");
  180. cmd.arg("--target-dir").arg(&ebpf_target_dir);
  181. let mut child = cmd
  182. .stdout(Stdio::piped())
  183. .stderr(Stdio::piped())
  184. .spawn()
  185. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  186. let Child { stdout, stderr, .. } = &mut child;
  187. // Trampoline stdout to cargo warnings.
  188. let stderr = stderr.take().unwrap();
  189. let stderr = BufReader::new(stderr);
  190. let stderr = std::thread::spawn(move || {
  191. for line in stderr.lines() {
  192. let line = line.unwrap();
  193. println!("cargo:warning={line}");
  194. }
  195. });
  196. let stdout = stdout.take().unwrap();
  197. let stdout = BufReader::new(stdout);
  198. let mut executables = Vec::new();
  199. for message in Message::parse_stream(stdout) {
  200. #[allow(clippy::collapsible_match)]
  201. match message.expect("valid JSON") {
  202. Message::CompilerArtifact(Artifact {
  203. executable,
  204. target: Target { name, .. },
  205. ..
  206. }) => {
  207. if let Some(executable) = executable {
  208. executables.push((name, executable.into_std_path_buf()));
  209. }
  210. }
  211. Message::CompilerMessage(CompilerMessage { message, .. }) => {
  212. println!("cargo:warning={message}");
  213. }
  214. Message::TextLine(line) => {
  215. println!("cargo:warning={line}");
  216. }
  217. _ => {}
  218. }
  219. }
  220. let status = child
  221. .wait()
  222. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  223. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {status:?}");
  224. stderr.join().map_err(std::panic::resume_unwind).unwrap();
  225. for (name, binary) in executables {
  226. let dst = out_dir.join(name);
  227. let _: u64 = fs::copy(&binary, &dst)
  228. .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}"));
  229. }
  230. } else {
  231. for (src, build_btf) in C_BPF {
  232. let dst = out_dir.join(src).with_extension("o");
  233. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  234. if *build_btf {
  235. let dst = dst.with_extension("target.o");
  236. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  237. }
  238. }
  239. let Package { targets, .. } = integration_ebpf_package;
  240. for Target { name, kind, .. } in targets {
  241. if *kind != ["bin"] {
  242. continue;
  243. }
  244. let dst = out_dir.join(name);
  245. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  246. }
  247. }
  248. }