solcompat_project/
tools.rs1use crate::input::inside;
4use anyhow::{bail, ensure, Context, Result};
5use solcompat_core::{Program, ToolObservation};
6use std::{
7 fs,
8 io::Read,
9 path::{Path, PathBuf},
10 process::Command,
11 time::Duration,
12};
13
14fn probe_candidate(tool: &str) -> Result<PathBuf> {
15 let paths = std::env::var_os("PATH").context("PATH is unavailable")?;
16 for directory in std::env::split_paths(&paths) {
17 let path = directory.join(tool);
18 let Ok(metadata) = fs::symlink_metadata(&path) else {
19 continue;
20 };
21 ensure!(
22 !metadata.file_type().is_symlink(),
23 "refusing a symlink/shim"
24 );
25 ensure!(metadata.is_file(), "not a regular executable");
26 let mut file = fs::File::open(&path)?;
27 let mut bytes = [0u8; 4];
28 let read = file.read(&mut bytes)?;
29 let native = bytes[..read].starts_with(b"\x7fELF")
30 || bytes.starts_with(&[0xfe, 0xed, 0xfa, 0xce])
31 || bytes.starts_with(&[0xcf, 0xfa, 0xed, 0xfe])
32 || bytes.starts_with(b"MZ");
33 ensure!(native, "refusing a script or unrecognized launcher");
34 return Ok(path);
35 }
36 bail!("not found")
37}
38
39pub fn probe_tools() -> Vec<ToolObservation> {
42 ["anchor", "cargo-build-sbf", "rustc"]
43 .into_iter()
44 .map(|tool| {
45 let path = match probe_candidate(tool) {
46 Ok(path) => path,
47 Err(error) => {
48 return ToolObservation {
49 tool: tool.into(),
50 version: None,
51 executable: None,
52 status: format!("not probed: {error}"),
53 }
54 }
55 };
56 let mut command = Command::new(&path);
57 command.arg("--version");
58 let (version, status) =
59 match crate::execution::run(&mut command, Duration::from_secs(3), 8192) {
60 Ok(output) => probe_version(&output),
61 Err(error) => (None, format!("probe failed: {error}")),
62 };
63 ToolObservation {
64 tool: tool.into(),
65 version,
66 executable: Some(path.to_string_lossy().into_owned()),
67 status,
68 }
69 })
70 .collect()
71}
72
73fn probe_version(output: &crate::execution::Captured) -> (Option<String>, String) {
74 let failure = if output.timed_out {
75 Some("timed out")
76 } else if !output.success {
77 Some("probe failed: unsuccessful exit or output read")
78 } else if output.truncated {
79 Some("probe failed: output exceeds 8 KiB retention limit")
80 } else {
81 None
82 };
83 if let Some(status) = failure {
84 return (None, status.into());
85 }
86 let versions: std::collections::BTreeSet<_> = output
87 .stdout
88 .split_whitespace()
89 .map(|token| token.trim_start_matches('v'))
90 .filter(|token| semver::Version::parse(token).is_ok())
91 .collect();
92 if versions.len() != 1 {
93 return (
94 None,
95 "probe failed: expected one exact version in stdout".into(),
96 );
97 }
98 (
99 versions.into_iter().next().map(str::to_owned),
100 "observed".into(),
101 )
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107 #[test]
108 fn failed_truncated_or_ambiguous_probes_do_not_supply_a_version() {
109 let mut output = crate::execution::Captured {
110 success: true,
111 timed_out: false,
112 stdout: "anchor v0.31.1".into(),
113 stderr: String::new(),
114 truncated: false,
115 };
116 assert_eq!(probe_version(&output).0.as_deref(), Some("0.31.1"));
117 output.success = false;
118 assert_eq!(probe_version(&output).0, None);
119 output.success = true;
120 output.truncated = true;
121 assert_eq!(probe_version(&output).0, None);
122 output.truncated = false;
123 output.timed_out = true;
124 assert_eq!(probe_version(&output).0, None);
125 output.timed_out = false;
126 output.stdout = "anchor 0.31.1 0.32.1".into();
127 assert_eq!(probe_version(&output).0, None);
128 }
129}
130
131#[derive(Clone, Debug)]
132pub struct BuildObservation {
135 pub success: bool,
136 pub command: String,
137 pub manifest: String,
138 pub output: String,
139}
140
141pub fn build_program(root: &Path, program: &Program) -> Result<BuildObservation> {
144 build_program_with_timeout(root, program, Duration::from_secs(1800))
145}
146
147pub fn build_program_with_timeout(
149 root: &Path,
150 program: &Program,
151 timeout: Duration,
152) -> Result<BuildObservation> {
153 let root = fs::canonicalize(root).context("cannot resolve build root")?;
154 let manifest = inside(&root, &root.join(&program.manifest))?;
155 let (mut command, display) = if program.framework == "anchor" {
156 let mut command = Command::new("anchor");
157 command.arg("build").current_dir(&root);
158 (command, "anchor build".to_owned())
159 } else {
160 let mut command = Command::new("cargo");
161 command
162 .arg("build-sbf")
163 .arg("--manifest-path")
164 .arg(&manifest)
165 .current_dir(&root);
166 (
167 command,
168 format!("cargo build-sbf --manifest-path {}", program.manifest),
169 )
170 };
171 let output = crate::execution::run(&mut command, timeout, 64 * 1024)
172 .with_context(|| format!("failed to start `{display}`"))?;
173 let mut combined = format!("{}{}", output.stdout, output.stderr);
174 if output.timed_out {
175 combined.push_str(&format!(
176 "\nBuild timed out after {} seconds.\n",
177 timeout.as_secs()
178 ));
179 }
180 if output.truncated {
181 combined.push_str("\nBuild output truncated to 64 KiB per stream.\n");
182 }
183 let lines: Vec<_> = combined.lines().collect();
184 let start = lines.len().saturating_sub(40);
185 Ok(BuildObservation {
186 success: output.success,
187 command: display,
188 manifest: program.manifest.clone(),
189 output: lines[start..].join("\n"),
190 })
191}
192
193pub fn enrich_tool_observations(
197 project: &mut solcompat_core::Project,
198 tools: Vec<ToolObservation>,
199) {
200 project.tools = tools;
201 let anchor = project
202 .tools
203 .iter()
204 .find(|tool| tool.tool == "anchor")
205 .and_then(|tool| tool.version.clone());
206 let builder = project
207 .tools
208 .iter()
209 .find(|tool| tool.tool == "cargo-build-sbf")
210 .and_then(|tool| tool.version.clone());
211 for program in &mut project.programs {
212 if program.anchor_cli_version.is_none() {
213 program.anchor_cli_version = anchor.clone();
214 }
215 if program.cargo_build_sbf_version.is_none() {
216 program.cargo_build_sbf_version = builder.clone();
217 }
218 }
219}