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. ("variables_reloc.bpf.c", false),
  68. ];
  69. if build_integration_bpf {
  70. let libbpf_dir = manifest_dir
  71. .parent()
  72. .unwrap()
  73. .parent()
  74. .unwrap()
  75. .join(LIBBPF_DIR);
  76. println!("cargo:rerun-if-changed={}", libbpf_dir.to_str().unwrap());
  77. let libbpf_headers_dir = out_dir.join("libbpf_headers");
  78. let mut includedir = OsString::new();
  79. includedir.push("INCLUDEDIR=");
  80. includedir.push(&libbpf_headers_dir);
  81. exec(
  82. Command::new("make")
  83. .arg("-C")
  84. .arg(libbpf_dir.join("src"))
  85. .arg(includedir)
  86. .arg("install_headers"),
  87. )
  88. .unwrap();
  89. let bpf_dir = manifest_dir.join("bpf");
  90. let mut target_arch = OsString::new();
  91. target_arch.push("-D__TARGET_ARCH_");
  92. let arch = env::var_os("CARGO_CFG_TARGET_ARCH").unwrap();
  93. if arch == "x86_64" {
  94. target_arch.push("x86");
  95. } else if arch == "aarch64" {
  96. target_arch.push("arm64");
  97. } else {
  98. target_arch.push(&arch);
  99. };
  100. // NB: libbpf's documentation suggests that vmlinux.h be generated by running `bpftool btf
  101. // dump file /sys/kernel/btf/vmlinux format c`; this allows CO-RE to work.
  102. //
  103. // However in our tests we do not make use of kernel data structures, and so any vmlinux.h
  104. // which defines the constants we need (e.g. `__u8`, `__u64`, `BPF_MAP_TYPE_ARRAY`,
  105. // `BPF_ANY`, `XDP_PASS`, `XDP_DROP`, etc.) will suffice. Since we already have a libbpf
  106. // submodule which happens to include such a file, we use it.
  107. let libbpf_vmlinux_dir = libbpf_dir.join(".github/actions/build-selftests");
  108. let clang = || {
  109. let mut cmd = Command::new("clang");
  110. cmd.arg("-nostdlibinc")
  111. .arg("-I")
  112. .arg(&libbpf_headers_dir)
  113. .arg("-I")
  114. .arg(&libbpf_vmlinux_dir)
  115. .args(["-g", "-O2", "-target", target, "-c"])
  116. .arg(&target_arch);
  117. cmd
  118. };
  119. for (src, build_btf) in C_BPF {
  120. let dst = out_dir.join(src).with_extension("o");
  121. let src = bpf_dir.join(src);
  122. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  123. exec(clang().arg(&src).arg("-o").arg(&dst)).unwrap();
  124. if *build_btf {
  125. let mut cmd = clang();
  126. let mut child = cmd
  127. .arg("-DTARGET")
  128. .arg(&src)
  129. .args(["-o", "-"])
  130. .stdout(Stdio::piped())
  131. .spawn()
  132. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  133. let Child { stdout, .. } = &mut child;
  134. let stdout = stdout.take().unwrap();
  135. let dst = dst.with_extension("target.o");
  136. let mut output = OsString::new();
  137. output.push(".BTF=");
  138. output.push(dst);
  139. exec(
  140. // NB: objcopy doesn't support reading from stdin, so we have to use llvm-objcopy.
  141. Command::new("llvm-objcopy")
  142. .arg("--dump-section")
  143. .arg(output)
  144. .arg("-")
  145. .stdin(stdout),
  146. )
  147. .unwrap();
  148. let output = child
  149. .wait_with_output()
  150. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  151. let Output { status, .. } = &output;
  152. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {output:?}");
  153. }
  154. }
  155. let target = format!("{target}-unknown-none");
  156. let Package { manifest_path, .. } = integration_ebpf_package;
  157. let integration_ebpf_dir = manifest_path.parent().unwrap();
  158. // We have a build-dependency on `integration-ebpf`, so cargo will automatically rebuild us
  159. // if `integration-ebpf`'s *library* target or any of its dependencies change. Since we
  160. // depend on `integration-ebpf`'s *binary* targets, that only gets us half of the way. This
  161. // stanza ensures cargo will rebuild us on changes to the binaries too, which gets us the
  162. // rest of the way.
  163. println!("cargo:rerun-if-changed={}", integration_ebpf_dir.as_str());
  164. let mut cmd = Command::new("cargo");
  165. cmd.args([
  166. "build",
  167. "-Z",
  168. "build-std=core",
  169. "--bins",
  170. "--message-format=json",
  171. "--release",
  172. "--target",
  173. &target,
  174. ]);
  175. cmd.env("CARGO_CFG_BPF_TARGET_ARCH", arch);
  176. // Workaround to make sure that the rust-toolchain.toml is respected.
  177. for key in ["RUSTUP_TOOLCHAIN", "RUSTC"] {
  178. cmd.env_remove(key);
  179. }
  180. cmd.current_dir(integration_ebpf_dir);
  181. // Workaround for https://github.com/rust-lang/cargo/issues/6412 where cargo flocks itself.
  182. let ebpf_target_dir = out_dir.join("integration-ebpf");
  183. cmd.arg("--target-dir").arg(&ebpf_target_dir);
  184. let mut child = cmd
  185. .stdout(Stdio::piped())
  186. .stderr(Stdio::piped())
  187. .spawn()
  188. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  189. let Child { stdout, stderr, .. } = &mut child;
  190. // Trampoline stdout to cargo warnings.
  191. let stderr = stderr.take().unwrap();
  192. let stderr = BufReader::new(stderr);
  193. let stderr = std::thread::spawn(move || {
  194. for line in stderr.lines() {
  195. let line = line.unwrap();
  196. println!("cargo:warning={line}");
  197. }
  198. });
  199. let stdout = stdout.take().unwrap();
  200. let stdout = BufReader::new(stdout);
  201. let mut executables = Vec::new();
  202. for message in Message::parse_stream(stdout) {
  203. #[allow(clippy::collapsible_match)]
  204. match message.expect("valid JSON") {
  205. Message::CompilerArtifact(Artifact {
  206. executable,
  207. target: Target { name, .. },
  208. ..
  209. }) => {
  210. if let Some(executable) = executable {
  211. executables.push((name, executable.into_std_path_buf()));
  212. }
  213. }
  214. Message::CompilerMessage(CompilerMessage { message, .. }) => {
  215. for line in message.rendered.unwrap_or_default().split('\n') {
  216. println!("cargo:warning={line}");
  217. }
  218. }
  219. Message::TextLine(line) => {
  220. println!("cargo:warning={line}");
  221. }
  222. _ => {}
  223. }
  224. }
  225. let status = child
  226. .wait()
  227. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  228. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {status:?}");
  229. stderr.join().map_err(std::panic::resume_unwind).unwrap();
  230. for (name, binary) in executables {
  231. let dst = out_dir.join(name);
  232. let _: u64 = fs::copy(&binary, &dst)
  233. .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}"));
  234. }
  235. } else {
  236. for (src, build_btf) in C_BPF {
  237. let dst = out_dir.join(src).with_extension("o");
  238. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  239. if *build_btf {
  240. let dst = dst.with_extension("target.o");
  241. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  242. }
  243. }
  244. let Package { targets, .. } = integration_ebpf_package;
  245. for Target { name, kind, .. } in targets {
  246. if *kind != ["bin"] {
  247. continue;
  248. }
  249. let dst = out_dir.join(name);
  250. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  251. }
  252. }
  253. }