| 1 |
use anyhow::{Context, Result}; |
| 2 |
use fs_err as fs; |
| 3 |
use goblin::elf::Elf; |
| 4 |
use regex::Regex; |
| 5 |
use std::path::{Path, PathBuf}; |
| 6 |
use std::process::{Command, Stdio}; |
| 7 |
|
| 8 |
/// Find musl libc path from executable's ELF header |
| 9 |
pub fn find_musl_libc() -> Result<Option<PathBuf>> { |
| 10 |
let buffer = fs::read("/bin/ls")?; |
| 11 |
let elf = Elf::parse(&buffer)?; |
| 12 |
Ok(elf.interpreter.map(PathBuf::from)) |
| 13 |
} |
| 14 |
|
| 15 |
/// Read the musl version from libc library's output |
| 16 |
/// |
| 17 |
/// The libc library should output something like this to stderr:: |
| 18 |
/// |
| 19 |
/// musl libc (x86_64) |
| 20 |
/// Version 1.2.2 |
| 21 |
/// Dynamic Program Loader |
| 22 |
pub fn get_musl_version(ld_path: impl AsRef<Path>) -> Result<Option<(u16, u16)>> { |
| 23 |
let ld_path = ld_path.as_ref(); |
| 24 |
let output = Command::new(ld_path) |
| 25 |
.stdout(Stdio::null()) |
| 26 |
.stderr(Stdio::piped()) |
| 27 |
.output()?; |
| 28 |
let stderr = std::str::from_utf8(&output.stderr)?; |
| 29 |
let expr = Regex::new(r"Version (\d+)\.(\d+)")?; |
| 30 |
if let Some(capture) = expr.captures(stderr) { |
| 31 |
let context = "Expected a digit"; |
| 32 |
let major = capture |
| 33 |
.get(1) |
| 34 |
.unwrap() |
| 35 |
.as_str() |
| 36 |
.parse::<u16>() |
| 37 |
.context(context)?; |
| 38 |
let minor = capture |
| 39 |
.get(2) |
| 40 |
.unwrap() |
| 41 |
.as_str() |
| 42 |
.parse::<u16>() |
| 43 |
.context(context)?; |
| 44 |
return Ok(Some((major, minor))); |
| 45 |
} |
| 46 |
Ok(None) |
| 47 |
} |