Skip to content

Commit e3a2809

Browse files
committed
fix: install libc debug symbols during executor setup
Share best-effort libc debug symbol installation across memory, walltime, and simulation setup. Keep Valgrind installation independent of optional debug symbols and use file-based checks for restored packages. Accumulate package metadata across separate cached installations. Keep symbol helpers private and document the shared-cache contract concisely.
1 parent d14d95d commit e3a2809

7 files changed

Lines changed: 165 additions & 140 deletions

File tree

‎src/executor/helpers/apt.rs‎

Lines changed: 24 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -10,43 +10,11 @@ pub fn is_system_compatible(system_info: &SystemInfo) -> bool {
1010
matches!(system_info.os, SupportedOs::Linux(ref distro) if distro.is_supported())
1111
}
1212

13-
/// Installs packages with caching support.
13+
/// Skip installed tools; otherwise restore the cache and recheck before installing.
1414
///
15-
/// This function provides a common pattern for installing tools on Ubuntu/Debian systems
16-
/// with automatic caching to speed up subsequent installations (e.g., in CI environments).
17-
///
18-
/// # Arguments
19-
///
20-
/// * `system_info` - System information to determine compatibility
21-
/// * `setup_cache_dir` - Optional directory to restore from/save to cache
22-
/// * `is_installed` - Function that checks if the tool is already installed
23-
/// * `install_packages` - Async closure that:
24-
/// 1. Performs the installation (e.g., downloads .deb files, calls `apt::install`)
25-
/// 2. Returns a Vec of package names that should be cached via `dpkg -L`
26-
///
27-
/// # Flow
28-
///
29-
/// 1. Check if already installed - if yes, skip everything
30-
/// 2. Try to restore from cache (if cache_dir provided)
31-
/// 3. Check again if installed - if yes, we're done
32-
/// 4. Run the install closure to install and get package names
33-
/// 5. Save installed packages to cache (if cache_dir provided)
34-
///
35-
/// # Example
36-
///
37-
/// ```rust,ignore
38-
/// apt::install_cached(
39-
/// system_info,
40-
/// setup_cache_dir,
41-
/// || Command::new("which").arg("perf").status().is_ok(),
42-
/// || async {
43-
/// let packages = vec!["linux-tools-common".to_string()];
44-
/// let refs: Vec<&str> = packages.iter().map(|s| s.as_str()).collect();
45-
/// apt::install(system_info, &refs)?;
46-
/// Ok(packages) // Return package names for caching
47-
/// },
48-
/// ).await?;
49-
/// ```
15+
/// `install_packages` installs the tool and returns package names to cache via `dpkg -L`.
16+
/// Restore copies files without updating dpkg's database, so `is_installed` must probe
17+
/// the tool or its files. Separate calls can share a cache: files and metadata accumulate.
5018
pub async fn install_cached<F, I, Fut>(
5119
system_info: &SystemInfo,
5220
setup_cache_dir: Option<&Path>,
@@ -63,7 +31,6 @@ where
6331
return Ok(());
6432
}
6533

66-
// Try to restore from cache first
6734
if let Some(cache_dir) = setup_cache_dir {
6835
restore_from_cache(system_info, cache_dir)?;
6936

@@ -73,12 +40,10 @@ where
7340
}
7441
}
7542

76-
// Install and get the package names for caching
7743
let cache_packages = install_packages().await?;
7844

7945
info!("Installation completed successfully");
8046

81-
// Save to cache after successful installation
8247
if let Some(cache_dir) = setup_cache_dir {
8348
let cache_refs: Vec<&str> = cache_packages.iter().map(|s| s.as_str()).collect();
8449
save_to_cache(system_info, cache_dir, &cache_refs)?;
@@ -117,7 +82,6 @@ fn restore_from_cache(system_info: &SystemInfo, cache_dir: &Path) -> Result<()>
11782
return Ok(());
11883
}
11984

120-
// Check if the directory has any contents
12185
let has_contents = std::fs::read_dir(cache_dir)
12286
.map(|mut entries| entries.next().is_some())
12387
.unwrap_or(false);
@@ -132,7 +96,6 @@ fn restore_from_cache(system_info: &SystemInfo, cache_dir: &Path) -> Result<()>
13296
cache_dir.display()
13397
);
13498

135-
// Read and log the metadata file if it exists
13699
let metadata_path = cache_dir.join(METADATA_FILENAME);
137100
if metadata_path.exists() {
138101
match std::fs::read_to_string(&metadata_path) {
@@ -150,12 +113,11 @@ fn restore_from_cache(system_info: &SystemInfo, cache_dir: &Path) -> Result<()>
150113
debug!("No metadata file found in cache directory");
151114
}
152115

153-
// Use bash to properly handle glob expansion
154116
let cache_dir_str = cache_dir
155117
.to_str()
156118
.ok_or_else(|| anyhow!("Invalid cache directory path"))?;
157119

158-
// IMPORTANT: We have to use 'bash' here to ensure that glob patterns are expanded correctly
120+
// A shell is needed to expand the cache directory glob.
159121
let copy_cmd = format!("cp -r {cache_dir_str}/* /");
160122
run_with_sudo("bash", ["-c", &copy_cmd])?;
161123

@@ -175,15 +137,13 @@ fn save_to_cache(system_info: &SystemInfo, cache_dir: &Path, packages: &[&str])
175137
cache_dir.display()
176138
);
177139

178-
// Create cache directory if it doesn't exist
179140
std::fs::create_dir_all(cache_dir).context("Failed to create cache directory")?;
180141

181142
let cache_dir_str = cache_dir
182143
.to_str()
183144
.ok_or_else(|| anyhow!("Invalid cache directory path"))?;
184145

185146
// Logic taken from https://stackoverflow.com/a/59277514
186-
// This shell command lists all the files outputted by the given packages and copy them to the cache directory
187147
let packages_str = packages.join(" ");
188148
let shell_cmd = format!(
189149
"dpkg -L {packages_str} | while IFS= read -r f; do if test -f \"$f\"; then echo \"$f\"; fi; done | xargs cp --parents --target-directory {cache_dir_str}",
@@ -203,9 +163,26 @@ fn save_to_cache(system_info: &SystemInfo, cache_dir: &Path, packages: &[&str])
203163
bail!("Failed to save packages to cache");
204164
}
205165

206-
// Create metadata file containing the installed packages
166+
// Separate installs share the cache, so retain previously cached package names.
207167
let metadata_path = cache_dir.join(METADATA_FILENAME);
208-
let metadata_content = packages.join("\n"); // TODO: add package versions as well, by using the output of the install command for example
168+
let existing_metadata = match std::fs::read_to_string(&metadata_path) {
169+
Ok(content) => content,
170+
Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
171+
Err(error) => {
172+
warn!(
173+
"Failed to read cache metadata at {}: {error}",
174+
metadata_path.display()
175+
);
176+
return Ok(());
177+
}
178+
};
179+
let mut cached_packages: Vec<&str> = existing_metadata
180+
.lines()
181+
.chain(packages.iter().copied())
182+
.collect();
183+
cached_packages.sort_unstable();
184+
cached_packages.dedup();
185+
let metadata_content = cached_packages.join("\n");
209186
if let Ok(()) = std::fs::create_dir_all(metadata_path.parent().unwrap()) {
210187
if let Ok(()) = std::fs::write(&metadata_path, metadata_content)
211188
.context("Failed to write metadata file")
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
use super::apt;
2+
use super::debug_file;
3+
use super::run_with_sudo::can_elevate_without_prompt;
4+
use crate::prelude::*;
5+
use crate::system::SystemInfo;
6+
use std::path::{Path, PathBuf};
7+
8+
/// Debian/Ubuntu package that ships the separate debug file of the system libc.
9+
const LIBC_DEBUG_PACKAGE: &str = "libc6-dbg";
10+
11+
/// Path of the system libc, following the Debian multiarch layout.
12+
fn system_libc_path(system_info: &SystemInfo) -> Option<PathBuf> {
13+
let triplet = match system_info.arch.as_str() {
14+
"x86_64" => "x86_64-linux-gnu",
15+
"aarch64" => "aarch64-linux-gnu",
16+
arch => {
17+
debug!("No known multiarch triplet for {arch}");
18+
return None;
19+
}
20+
};
21+
Some(PathBuf::from(format!("/lib/{triplet}/libc.so.6")))
22+
}
23+
24+
/// Whether a separate debug file can be resolved for `binary`, through the same
25+
/// build-id and `.gnu_debuglink` lookup that GDB and valgrind perform.
26+
fn has_debug_symbols(binary: &Path) -> bool {
27+
let data = match std::fs::read(binary) {
28+
Ok(data) => data,
29+
Err(e) => {
30+
debug!("Failed to read {}: {e}", binary.display());
31+
return false;
32+
}
33+
};
34+
let object = match object::File::parse(data.as_slice()) {
35+
Ok(object) => object,
36+
Err(e) => {
37+
debug!("Failed to parse {} as ELF: {e}", binary.display());
38+
return false;
39+
}
40+
};
41+
42+
match debug_file::find_debug_file(&object, binary) {
43+
Some(debug_path) => {
44+
debug!(
45+
"Resolved debug file for {}: {}",
46+
binary.display(),
47+
debug_path.display()
48+
);
49+
true
50+
}
51+
None => {
52+
debug!("No debug file found for {}", binary.display());
53+
false
54+
}
55+
}
56+
}
57+
58+
/// Whether the system libc has the separate debug file `libc6-dbg` provides.
59+
///
60+
/// Probed by file rather than through dpkg, because the setup cache restores package
61+
/// files without touching dpkg's database.
62+
fn has_libc_debug_symbols(system_info: &SystemInfo) -> bool {
63+
system_libc_path(system_info).is_some_and(|libc| has_debug_symbols(&libc))
64+
}
65+
66+
/// Warn when the system libc has no debug symbols: they sharpen the output but are not
67+
/// needed to run.
68+
fn warn_on_missing_libc_debug_symbols(system_info: &SystemInfo) {
69+
if !apt::is_system_compatible(system_info) {
70+
debug!("Skipping the libc debug symbol check on a non-apt-based system");
71+
return;
72+
}
73+
74+
if !has_libc_debug_symbols(system_info) {
75+
warn!(
76+
"Debug info for the system libc not found. Frames of the system libc can show up \
77+
as addresses in the flamegraph. Install {LIBC_DEBUG_PACKAGE} (Debian/Ubuntu) or \
78+
glibc-debuginfo (Fedora/RHEL) for more accurate results"
79+
);
80+
}
81+
}
82+
83+
/// Install the libc debug symbols so frames of the system libc resolve to their real names.
84+
///
85+
/// Best effort: they sharpen the output but are not needed to run, so a failure (no sudo,
86+
/// no network) is a warning instead of an error. Non-apt systems are skipped; the warning
87+
/// raised while saving the module artifacts still points those users to the package.
88+
pub async fn ensure_libc_debug_symbols(system_info: &SystemInfo, setup_cache_dir: Option<&Path>) {
89+
if !apt::is_system_compatible(system_info) {
90+
debug!("Skipping the libc debug symbol install on a non-apt-based system");
91+
return;
92+
}
93+
94+
if has_libc_debug_symbols(system_info) {
95+
debug!("The libc debug symbols are already installed");
96+
return;
97+
}
98+
99+
// An optional install must not stop to ask for a password, and a failing sudo logs an
100+
// error. Only elevate when that works silently (root, or passwordless sudo).
101+
if !can_elevate_without_prompt() {
102+
debug!("Not installing {LIBC_DEBUG_PACKAGE}: it needs root or passwordless sudo");
103+
warn_on_missing_libc_debug_symbols(system_info);
104+
return;
105+
}
106+
107+
let result = apt::install_cached(
108+
system_info,
109+
setup_cache_dir,
110+
|| has_libc_debug_symbols(system_info),
111+
|| async {
112+
debug!("Installing {LIBC_DEBUG_PACKAGE}");
113+
apt::install(system_info, &[LIBC_DEBUG_PACKAGE])?;
114+
Ok(vec![LIBC_DEBUG_PACKAGE.to_string()])
115+
},
116+
)
117+
.await;
118+
119+
if let Err(error) = result {
120+
warn!("Could not install {LIBC_DEBUG_PACKAGE}: {error}");
121+
}
122+
}

‎src/executor/helpers/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub mod harvest_perf_maps_for_pids;
1212
pub mod homebrew;
1313
pub mod introspected_golang;
1414
pub mod introspected_nodejs;
15+
pub mod libc_debug_info;
1516
pub mod linux_sysctl;
1617
pub mod profile_folder;
1718
pub mod run_command_with_log_pipe;

‎src/executor/memory/executor.rs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::executor::ToolStatus;
55
use crate::executor::helpers::command::CommandBuilder;
66
use crate::executor::helpers::env::{build_path_env, get_base_injected_env};
77
use crate::executor::helpers::get_bench_command::get_bench_command;
8+
use crate::executor::helpers::libc_debug_info::ensure_libc_debug_symbols;
89
use crate::executor::helpers::run_command_with_log_pipe::run_command_with_log_pipe_and_callback;
910
use crate::executor::helpers::run_with_env::prefix_command_with_env;
1011
use crate::executor::helpers::run_with_sudo::is_root_user;
@@ -146,12 +147,12 @@ impl Executor for MemoryExecutor {
146147
}
147148
}
148149

149-
async fn setup(
150-
&self,
151-
_system_info: &SystemInfo,
152-
_setup_cache_dir: Option<&Path>,
153-
) -> Result<()> {
154-
install_memtrack().await
150+
async fn setup(&self, system_info: &SystemInfo, setup_cache_dir: Option<&Path>) -> Result<()> {
151+
install_memtrack().await?;
152+
// FIXME(COD-2794): resolve libc symbols through debuginfod once it is back up, instead
153+
// of installing libc6-dbg.
154+
ensure_libc_debug_symbols(system_info, setup_cache_dir).await;
155+
Ok(())
155156
}
156157

157158
fn grant_privileges(&self) -> Result<()> {

‎src/executor/valgrind/executor.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::path::Path;
33

44
use crate::executor::Executor;
55
use crate::executor::ToolStatus;
6+
use crate::executor::helpers::libc_debug_info::ensure_libc_debug_symbols;
67
use crate::executor::{ExecutionContext, ExecutorName, ExecutorSupport};
78
use crate::instruments::mongo_tracer::MongoTracer;
89
use crate::prelude::*;
@@ -56,6 +57,8 @@ impl Executor for ValgrindExecutor {
5657
}
5758
}
5859

60+
ensure_libc_debug_symbols(system_info, setup_cache_dir).await;
61+
5962
if let Err(error) = venv_compat::symlink_libpython(None) {
6063
warn!(
6164
"Failed to symlink libpython into the virtual environment, flamegraphs may contain artifacts: {error}"

0 commit comments

Comments
 (0)