build.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. use std::{
  2. env,
  3. ffi::OsString,
  4. fs,
  5. io::{BufRead as _, BufReader},
  6. path::PathBuf,
  7. process::{Child, Command, 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. for (src, dst) in c_bpf {
  101. let src = bpf_dir.join(src);
  102. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  103. exec(
  104. Command::new("clang")
  105. .arg("-I")
  106. .arg(&libbpf_headers_dir)
  107. .args(["-g", "-O2", "-target", target, "-c"])
  108. .arg(&target_arch)
  109. .arg(src)
  110. .arg("-o")
  111. .arg(dst),
  112. )
  113. .unwrap();
  114. }
  115. for (src, dst) in c_btf {
  116. let src = bpf_dir.join(src);
  117. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  118. let mut cmd = Command::new("clang");
  119. cmd.arg("-I")
  120. .arg(&libbpf_headers_dir)
  121. .args(["-g", "-target", target, "-c"])
  122. .arg(&target_arch)
  123. .arg(src)
  124. .args(["-o", "-"]);
  125. let mut child = cmd
  126. .stdout(Stdio::piped())
  127. .spawn()
  128. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  129. let Child { stdout, .. } = &mut child;
  130. let stdout = stdout.take().unwrap();
  131. let mut output = OsString::new();
  132. output.push(".BTF=");
  133. output.push(dst);
  134. exec(
  135. // NB: objcopy doesn't support reading from stdin, so we have to use llvm-objcopy.
  136. Command::new("llvm-objcopy")
  137. .arg("--dump-section")
  138. .arg(output)
  139. .arg("-")
  140. .stdin(stdout),
  141. )
  142. .unwrap();
  143. let status = child
  144. .wait()
  145. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  146. match status.code() {
  147. Some(code) => match code {
  148. 0 => {}
  149. code => panic!("{cmd:?} exited with status code {code}"),
  150. },
  151. None => panic!("{cmd:?} terminated by signal"),
  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. // 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. match status.code() {
  225. Some(code) => match code {
  226. 0 => {}
  227. code => panic!("{cmd:?} exited with status code {code}"),
  228. },
  229. None => panic!("{cmd:?} terminated by signal"),
  230. }
  231. stderr.join().map_err(std::panic::resume_unwind).unwrap();
  232. for (name, binary) in executables {
  233. let dst = out_dir.join(name);
  234. let _: u64 = fs::copy(&binary, &dst)
  235. .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}"));
  236. }
  237. } else {
  238. for (_src, dst) in c_bpf.chain(c_btf) {
  239. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  240. }
  241. let Package { targets, .. } = integration_ebpf_package;
  242. for Target { name, kind, .. } in targets {
  243. if *kind != ["bin"] {
  244. continue;
  245. }
  246. let dst = out_dir.join(name);
  247. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  248. }
  249. }
  250. }