build.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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, &str)] = &[
  60. ("ext.bpf.c", "ext.bpf.o"),
  61. ("main.bpf.c", "main.bpf.o"),
  62. ("multimap-btf.bpf.c", "multimap-btf.bpf.o"),
  63. ("reloc.bpf.c", "reloc.bpf.o"),
  64. ("text_64_64_reloc.c", "text_64_64_reloc.o"),
  65. ];
  66. let c_bpf = C_BPF.iter().map(|(src, dst)| (src, out_dir.join(dst)));
  67. const C_BTF: &[(&str, &str)] = &[("reloc.btf.c", "reloc.btf.o")];
  68. let c_btf = C_BTF.iter().map(|(src, dst)| (src, out_dir.join(dst)));
  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, dst) in c_bpf {
  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. }
  124. for (src, dst) in c_btf {
  125. let src = bpf_dir.join(src);
  126. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  127. let mut cmd = clang();
  128. let mut child = cmd
  129. .arg(src)
  130. .args(["-o", "-"])
  131. .stdout(Stdio::piped())
  132. .spawn()
  133. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  134. let Child { stdout, .. } = &mut child;
  135. let stdout = stdout.take().unwrap();
  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. 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. // Workaround to make sure that the rust-toolchain.toml is respected.
  175. for key in ["RUSTUP_TOOLCHAIN", "RUSTC"] {
  176. cmd.env_remove(key);
  177. }
  178. cmd.current_dir(integration_ebpf_dir);
  179. // Workaround for https://github.com/rust-lang/cargo/issues/6412 where cargo flocks itself.
  180. let ebpf_target_dir = out_dir.join("integration-ebpf");
  181. cmd.arg("--target-dir").arg(&ebpf_target_dir);
  182. let mut child = cmd
  183. .stdout(Stdio::piped())
  184. .stderr(Stdio::piped())
  185. .spawn()
  186. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  187. let Child { stdout, stderr, .. } = &mut child;
  188. // Trampoline stdout to cargo warnings.
  189. let stderr = stderr.take().unwrap();
  190. let stderr = BufReader::new(stderr);
  191. let stderr = std::thread::spawn(move || {
  192. for line in stderr.lines() {
  193. let line = line.unwrap();
  194. println!("cargo:warning={line}");
  195. }
  196. });
  197. let stdout = stdout.take().unwrap();
  198. let stdout = BufReader::new(stdout);
  199. let mut executables = Vec::new();
  200. for message in Message::parse_stream(stdout) {
  201. #[allow(clippy::collapsible_match)]
  202. match message.expect("valid JSON") {
  203. Message::CompilerArtifact(Artifact {
  204. executable,
  205. target: Target { name, .. },
  206. ..
  207. }) => {
  208. if let Some(executable) = executable {
  209. executables.push((name, executable.into_std_path_buf()));
  210. }
  211. }
  212. Message::CompilerMessage(CompilerMessage { message, .. }) => {
  213. println!("cargo:warning={message}");
  214. }
  215. Message::TextLine(line) => {
  216. println!("cargo:warning={line}");
  217. }
  218. _ => {}
  219. }
  220. }
  221. let status = child
  222. .wait()
  223. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  224. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {status:?}");
  225. stderr.join().map_err(std::panic::resume_unwind).unwrap();
  226. for (name, binary) in executables {
  227. let dst = out_dir.join(name);
  228. let _: u64 = fs::copy(&binary, &dst)
  229. .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}"));
  230. }
  231. } else {
  232. for (_src, dst) in c_bpf.chain(c_btf) {
  233. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  234. }
  235. let Package { targets, .. } = integration_ebpf_package;
  236. for Target { name, kind, .. } in targets {
  237. if *kind != ["bin"] {
  238. continue;
  239. }
  240. let dst = out_dir.join(name);
  241. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  242. }
  243. }
  244. }