Skip to main content

scx_cake/
build_identity.rs

1// SPDX-License-Identifier: GPL-2.0
2
3use std::fs::File;
4use std::process::{Command, Stdio};
5
6use anyhow::{Context, Result, ensure};
7
8/// Identify the running executable, including local changes and its embedded BPF.
9/// Open before spawning: /proc/self/exe in the child would identify sha256sum.
10/// The open inode also remains correct if a rebuild replaces the binary on disk.
11pub fn binary_sha256() -> Result<String> {
12    let executable = File::open("/proc/self/exe").context("opening running executable")?;
13    let output = Command::new("sha256sum")
14        .stdin(Stdio::from(executable))
15        .stderr(Stdio::null())
16        .output()
17        .context("running sha256sum (coreutils)")?;
18    ensure!(output.status.success(), "sha256sum failed");
19    let stdout = std::str::from_utf8(&output.stdout).context("reading SHA-256 output")?;
20    let hash = stdout.split_whitespace().next().unwrap_or_default();
21    ensure!(
22        hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()),
23        "invalid SHA-256 output"
24    );
25    Ok(hash.to_ascii_lowercase())
26}