use std::path::{Path, PathBuf};
use std::process::Command;
pub const SELF_MARKER: &str = "rubylang-differential-oracle-self-marker/v1";
#[used]
static SELF_MARKER_ANCHOR: &[u8] = SELF_MARKER.as_bytes();
pub const ORACLE_ENV: &str = "RUBYLANG_ORACLE_RUBY";
pub const ORACLE_ENV_LEGACY: &str = "RUBYLANG_FUZZ_RUBY";
pub const CANDIDATES: &[&str] = &[
"/opt/homebrew/opt/ruby/bin/ruby",
"/usr/local/opt/ruby/bin/ruby",
"/opt/homebrew/bin/ruby",
"/usr/local/bin/ruby",
"/usr/bin/ruby",
];
#[derive(Debug, Clone)]
pub struct Oracle {
pub path: PathBuf,
pub version: String,
}
impl Oracle {
pub fn command(&self) -> Command {
Command::new(&self.path)
}
pub fn id(&self) -> String {
format!("{} ({})", self.path.display(), self.version)
}
}
fn file_contains(path: &Path, needle: &[u8]) -> bool {
use std::io::Read as _;
let Ok(mut f) = std::fs::File::open(path) else {
return false;
};
let overlap = needle.len().saturating_sub(1);
let mut buf = vec![0u8; 1 << 20];
let mut filled = 0usize;
loop {
match f.read(&mut buf[filled..]) {
Ok(0) => return false,
Ok(n) => {
filled += n;
if buf[..filled].windows(needle.len()).any(|w| w == needle) {
return true;
}
if filled + overlap >= buf.len() {
buf.copy_within(filled - overlap..filled, 0);
filled = overlap;
}
}
Err(_) => return false,
}
}
}
fn reject_reason(path: &Path) -> Option<String> {
let real = match path.canonicalize() {
Ok(p) => p,
Err(e) => return Some(format!("cannot canonicalize: {e}")),
};
let shown = real.display().to_string();
if shown.contains("rubylang") {
return Some(format!(
"resolves to {shown} — that is rubylang itself, not the reference"
));
}
if shown.contains("/target/debug/") || shown.contains("/target/release/") {
return Some(format!("resolves to a build directory ({shown})"));
}
if file_contains(&real, SELF_MARKER.as_bytes()) {
return Some(format!(
"{shown} carries rubylang's own build marker — that is rubylang \
itself, however it identifies"
));
}
let ver = match Command::new(&real).arg("--version").output() {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
Ok(o) => return Some(format!("`--version` exited {}", o.status)),
Err(e) => return Some(format!("cannot run `--version`: {e}")),
};
if !ver.starts_with("ruby ") || !ver.contains("revision ") || !ver.ends_with(']') {
return Some(format!(
"`--version` printed {ver:?}, which is not MRI's \
`ruby X.Y.Z (… revision …) [platform]`"
));
}
match Command::new(&real)
.arg("-e")
.arg("print RUBY_ENGINE")
.output()
{
Ok(o) if o.status.success() => {
let engine = String::from_utf8_lossy(&o.stdout).trim().to_string();
if engine != "ruby" {
return Some(format!("RUBY_ENGINE is {engine:?}, not \"ruby\""));
}
}
Ok(o) => return Some(format!("`-e 'print RUBY_ENGINE'` exited {}", o.status)),
Err(e) => return Some(format!("cannot run `-e`: {e}")),
}
None
}
pub fn verify(path: &Path) -> Result<Oracle, String> {
if let Some(why) = reject_reason(path) {
return Err(format!("{}: {why}", path.display()));
}
let real = path.canonicalize().map_err(|e| e.to_string())?;
let version = Command::new(&real)
.arg("--version")
.output()
.map_err(|e| e.to_string())?;
Ok(Oracle {
path: real,
version: String::from_utf8_lossy(&version.stdout).trim().to_string(),
})
}
pub fn find() -> Result<Oracle, String> {
for var in [ORACLE_ENV, ORACLE_ENV_LEGACY] {
if let Ok(p) = std::env::var(var) {
if !p.is_empty() {
return verify(Path::new(&p))
.map_err(|why| format!("{var}={p} is unusable — {why}"));
}
}
}
let mut rejected = Vec::new();
for cand in CANDIDATES {
let path = Path::new(cand);
if !path.exists() {
continue;
}
match verify(path) {
Ok(o) => return Ok(o),
Err(why) => rejected.push(format!(" {why}")),
}
}
Err(format!(
"no reference MRI `ruby` found. Set {ORACLE_ENV} to one.\n\
Bare `ruby` is never tried: rubylang installs under that name, so a \
PATH lookup would compare rubylang to itself.\n\
Rejected candidates:\n{}",
if rejected.is_empty() {
" (none of the candidate paths exist)".to_string()
} else {
rejected.join("\n")
}
))
}
pub fn require_oracle(tool: &str) -> Oracle {
match find() {
Ok(o) => o,
Err(why) => {
eprintln!("{tool}: {why}");
std::process::exit(2);
}
}
}