build.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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_PROBES: &[(&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. ("text_64_64_reloc.c", "text_64_64_reloc.o"),
  64. ];
  65. let c_bpf_probes = C_BPF_PROBES
  66. .iter()
  67. .map(|(src, dst)| (src, out_dir.join(dst)));
  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. for (src, dst) in c_bpf_probes {
  100. let src = bpf_dir.join(src);
  101. println!("cargo:rerun-if-changed={}", src.to_str().unwrap());
  102. exec(
  103. Command::new("clang")
  104. .arg("-I")
  105. .arg(&libbpf_headers_dir)
  106. .args(["-g", "-O2", "-target", target, "-c"])
  107. .arg(&target_arch)
  108. .arg(src)
  109. .arg("-o")
  110. .arg(dst),
  111. )
  112. .unwrap();
  113. }
  114. let target = format!("{target}-unknown-none");
  115. let Package { manifest_path, .. } = integration_ebpf_package;
  116. let integration_ebpf_dir = manifest_path.parent().unwrap();
  117. let mut cmd = Command::new("cargo");
  118. cmd.args([
  119. "build",
  120. "-Z",
  121. "build-std=core",
  122. "--release",
  123. "--message-format=json",
  124. "--target",
  125. &target,
  126. ]);
  127. // Workaround to make sure that the rust-toolchain.toml is respected.
  128. for key in ["RUSTUP_TOOLCHAIN", "RUSTC"] {
  129. cmd.env_remove(key);
  130. }
  131. cmd.current_dir(integration_ebpf_dir);
  132. // Workaround for https://github.com/rust-lang/cargo/issues/6412 where cargo flocks itself.
  133. let ebpf_target_dir = out_dir.join("integration-ebpf");
  134. cmd.arg("--target-dir").arg(&ebpf_target_dir);
  135. let mut child = cmd
  136. .stdout(Stdio::piped())
  137. .stderr(Stdio::piped())
  138. .spawn()
  139. .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}"));
  140. let Child { stdout, stderr, .. } = &mut child;
  141. // Trampoline stdout to cargo warnings.
  142. let stderr = stderr.take().unwrap();
  143. let stderr = BufReader::new(stderr);
  144. let stderr = std::thread::spawn(move || {
  145. for line in stderr.lines() {
  146. let line = line.unwrap();
  147. println!("cargo:warning={line}");
  148. }
  149. });
  150. let stdout = stdout.take().unwrap();
  151. let stdout = BufReader::new(stdout);
  152. let mut executables = Vec::new();
  153. for message in Message::parse_stream(stdout) {
  154. #[allow(clippy::collapsible_match)]
  155. match message.expect("valid JSON") {
  156. Message::CompilerArtifact(Artifact {
  157. executable,
  158. target: Target { name, .. },
  159. ..
  160. }) => {
  161. if let Some(executable) = executable {
  162. executables.push((name, executable.into_std_path_buf()));
  163. }
  164. }
  165. Message::CompilerMessage(CompilerMessage { message, .. }) => {
  166. println!("cargo:warning={message}");
  167. }
  168. Message::TextLine(line) => {
  169. println!("cargo:warning={line}");
  170. }
  171. _ => {}
  172. }
  173. }
  174. let status = child
  175. .wait()
  176. .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}"));
  177. match status.code() {
  178. Some(code) => match code {
  179. 0 => {}
  180. code => panic!("{cmd:?} exited with status code {code}"),
  181. },
  182. None => panic!("{cmd:?} terminated by signal"),
  183. }
  184. stderr.join().map_err(std::panic::resume_unwind).unwrap();
  185. for (name, binary) in executables {
  186. let dst = out_dir.join(name);
  187. let _: u64 = fs::copy(&binary, &dst)
  188. .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}"));
  189. }
  190. } else {
  191. for (_src, dst) in c_bpf_probes {
  192. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  193. }
  194. let Package { targets, .. } = integration_ebpf_package;
  195. for Target { name, kind, .. } in targets {
  196. if *kind != ["bin"] {
  197. continue;
  198. }
  199. let dst = out_dir.join(name);
  200. fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}"));
  201. }
  202. }
  203. }