4
0

build.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. let clang = || {
  101. let mut cmd = Command::new("clang");
  102. cmd.arg("-I")
  103. .arg(&libbpf_headers_dir)
  104. .args(["-g", "-O2", "-target", target, "-c"])
  105. .arg(&target_arch);
  106. cmd
  107. };
  108. for (src, dst) in c_bpf {
  109. let src = bpf_dir.join(src);
  110. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  111. exec(clang().arg(src).arg("-o").arg(dst)).unwrap();
  112. }
  113. for (src, dst) in c_btf {
  114. let src = bpf_dir.join(src);
  115. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  116. let mut cmd = clang();
  117. let mut child = cmd
  118. .arg(src)
  119. .args(["-o", "-"])
  120. .stdout(Stdio::piped())
  121. .spawn()
  122. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  123. let Child { stdout, .. } = &mut child;
  124. let stdout = stdout.take().unwrap();
  125. let mut output = OsString::new();
  126. output.push(".BTF=");
  127. output.push(dst);
  128. exec(
  129. // NB: objcopy doesn't support reading from stdin, so we have to use llvm-objcopy.
  130. Command::new("llvm-objcopy")
  131. .arg("--dump-section")
  132. .arg(output)
  133. .arg("-")
  134. .stdin(stdout),
  135. )
  136. .unwrap();
  137. let output = child
  138. .wait_with_output()
  139. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  140. let Output { status, .. } = &output;
  141. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {output:?}");
  142. }
  143. let target = format!("{target}-unknown-none");
  144. let Package { manifest_path, .. } = integration_ebpf_package;
  145. let integration_ebpf_dir = manifest_path.parent().unwrap();
  146. // We have a build-dependency on `integration-ebpf`, so cargo will automatically rebuild us
  147. // if `integration-ebpf`'s *library* target or any of its dependencies change. Since we
  148. // depend on `integration-ebpf`'s *binary* targets, that only gets us half of the way. This
  149. // stanza ensures cargo will rebuild us on changes to the binaries too, which gets us the
  150. // rest of the way.
  151. println!("cargo:rerun-if-changed={}", integration_ebpf_dir.as_str());
  152. let mut cmd = Command::new("cargo");
  153. cmd.args([
  154. "build",
  155. "-Z",
  156. "build-std=core",
  157. "--bins",
  158. "--message-format=json",
  159. "--release",
  160. "--target",
  161. &target,
  162. ]);
  163. // Workaround to make sure that the rust-toolchain.toml is respected.
  164. for key in ["RUSTUP_TOOLCHAIN", "RUSTC"] {
  165. cmd.env_remove(key);
  166. }
  167. cmd.current_dir(integration_ebpf_dir);
  168. // Workaround for https://github.com/rust-lang/cargo/issues/6412 where cargo flocks itself.
  169. let ebpf_target_dir = out_dir.join("integration-ebpf");
  170. cmd.arg("--target-dir").arg(&ebpf_target_dir);
  171. let mut child = cmd
  172. .stdout(Stdio::piped())
  173. .stderr(Stdio::piped())
  174. .spawn()
  175. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  176. let Child { stdout, stderr, .. } = &mut child;
  177. // Trampoline stdout to cargo warnings.
  178. let stderr = stderr.take().unwrap();
  179. let stderr = BufReader::new(stderr);
  180. let stderr = std::thread::spawn(move || {
  181. for line in stderr.lines() {
  182. let line = line.unwrap();
  183. println!("cargo:warning={line}");
  184. }
  185. });
  186. let stdout = stdout.take().unwrap();
  187. let stdout = BufReader::new(stdout);
  188. let mut executables = Vec::new();
  189. for message in Message::parse_stream(stdout) {
  190. #[allow(clippy::collapsible_match)]
  191. match message.expect("valid JSON") {
  192. Message::CompilerArtifact(Artifact {
  193. executable,
  194. target: Target { name, .. },
  195. ..
  196. }) => {
  197. if let Some(executable) = executable {
  198. executables.push((name, executable.into_std_path_buf()));
  199. }
  200. }
  201. Message::CompilerMessage(CompilerMessage { message, .. }) => {
  202. println!("cargo:warning={message}");
  203. }
  204. Message::TextLine(line) => {
  205. println!("cargo:warning={line}");
  206. }
  207. _ => {}
  208. }
  209. }
  210. let status = child
  211. .wait()
  212. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  213. assert_eq!(status.code(), Some(0), "{cmd:?} failed: {status:?}");
  214. stderr.join().map_err(std::panic::resume_unwind).unwrap();
  215. for (name, binary) in executables {
  216. let dst = out_dir.join(name);
  217. let _: u64 = fs::copy(&binary, &dst)
  218. .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}"));
  219. }
  220. } else {
  221. for (_src, dst) in c_bpf.chain(c_btf) {
  222. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  223. }
  224. let Package { targets, .. } = integration_ebpf_package;
  225. for Target { name, kind, .. } in targets {
  226. if *kind != ["bin"] {
  227. continue;
  228. }
  229. let dst = out_dir.join(name);
  230. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  231. }
  232. }
  233. }