build.rs 11 KB

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