From aa5c38fa0aad65c2b91d911605748762c553e91c Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 22:34:42 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=F0=9F=90=9B=20fix:=20take=20the=20CUDA=20m?= =?UTF-8?q?ajor=20from=20the=20target's=20loaded=20CUPTI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A target that loaded CUDA 13's libcupti beside a libcudart.so.12 pulled in by another package was rejected as mapping conflicting majors. The loaded libcupti now decides the major, read from its SONAME when the file name is calendar-versioned; libcudart decides only when no CUPTI is loaded. Another libcudart major beside a loaded CUPTI gives the validate warning EXTRA_CUDA_RUNTIME. --- docs/cli-reference.md | 2 +- docs/cupti-agent.md | 2 +- xprobe/core/src/cupti_compat.rs | 318 +++++++++++++++++++++++++++----- xprobe/core/src/validate.rs | 58 +++++- 4 files changed, 324 insertions(+), 56 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 59b7768..5d1f1ee 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -111,7 +111,7 @@ A read-only check of target identity, probe resolution, CUDA filters, correlatio - `already_loaded` - `injection_required`: `measure` will inject the Agent; sets `target_mutation: true` and warns `TARGET_PROCESS_WILL_BE_MODIFIED`. - `startup_required`: an NVTX selector needs the Agent loaded at startup; `valid: false`. -- A CUDA major other than 12 or 13, or conflicting majors, returns `UNSUPPORTED_CUDA_VERSION`. +- The CUDA major comes from the target's loaded `libcupti` (by file name, or by SONAME for calendar-versioned files), or from its `libcudart` when no CUPTI is loaded. A `libcudart` of another major beside a loaded `libcupti` gives the warning `EXTRA_CUDA_RUNTIME`. A major other than 12 or 13, or two majors of the deciding library, returns `UNSUPPORTED_CUDA_VERSION`. ## Correlation policies diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index 99e8218..d08948b 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -2,7 +2,7 @@ `libxprobe-cupti.so` runs inside a CUDA target process to collect Runtime/Driver API callbacks, kernel/memcpy/memset activity, and ASCII NVTX range boundaries. Users normally drive it through `xprobe measure --pid`; it is not a daemon or persistent profiling session. -Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.so.13`. `measure` picks the major from the target's mapped CUDA libraries (or from the single installed CUPTI major when the target doesn't expose one) and fails before ptrace attach on conflict, unsupported major, or missing `.so`. +Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.so.13`. `measure` takes the major from the target's loaded `libcupti` (its file name, or its SONAME for a toolkit's calendar-versioned `libcupti.so.2025.x`), else from its `libcudart`, else from the single installed CUPTI major. It fails before ptrace attach when that library is mapped in two majors, when the major is unsupported, or when the `.so` is missing. ## Measurement lifecycle diff --git a/xprobe/core/src/cupti_compat.rs b/xprobe/core/src/cupti_compat.rs index 3b85ec3..66b9653 100644 --- a/xprobe/core/src/cupti_compat.rs +++ b/xprobe/core/src/cupti_compat.rs @@ -19,12 +19,27 @@ pub struct CuptiLibrary { #[derive(Debug)] pub enum CuptiCompatibilityError { - ConflictingTargetVersions(Vec), + /// The target maps more than one major of `library` (`libcupti` or, + /// when no CUPTI is loaded, `libcudart`). + ConflictingTargetVersions { + library: &'static str, + majors: Vec, + }, UnsupportedMajor(u32), AmbiguousInstalledVersions(Vec), LibraryNotFound(Option), - LinkerCache { detail: String }, - Io { path: PathBuf, source: io::Error }, + LinkerCache { + detail: String, + }, + /// A mapped libcupti whose ELF SONAME does not name its major. + InvalidLibrary(PathBuf), + /// A calendar-versioned libcupti deleted after the target loaded it, so + /// its SONAME cannot be read. + DeletedLibrary(PathBuf), + Io { + path: PathBuf, + source: io::Error, + }, } impl CuptiCompatibilityError { @@ -32,11 +47,13 @@ impl CuptiCompatibilityError { pub const fn code(&self) -> ErrorCode { match self { Self::UnsupportedMajor(_) - | Self::ConflictingTargetVersions(_) + | Self::ConflictingTargetVersions { .. } | Self::AmbiguousInstalledVersions(_) => ErrorCode::UnsupportedCudaVersion, - Self::LibraryNotFound(_) | Self::LinkerCache { .. } | Self::Io { .. } => { - ErrorCode::CuptiNotAvailable - } + Self::LibraryNotFound(_) + | Self::LinkerCache { .. } + | Self::InvalidLibrary(_) + | Self::DeletedLibrary(_) + | Self::Io { .. } => ErrorCode::CuptiNotAvailable, } } } @@ -44,12 +61,14 @@ impl CuptiCompatibilityError { impl fmt::Display for CuptiCompatibilityError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::ConflictingTargetVersions(majors) => { - write!( - formatter, - "target maps conflicting CUDA/CUPTI majors {majors:?}" - ) - } + Self::ConflictingTargetVersions { + library: "libcupti", + majors, + } => write!(formatter, "target maps libcupti majors {majors:?}"), + Self::ConflictingTargetVersions { library, majors } => write!( + formatter, + "target maps {library} majors {majors:?} and no libcupti, so the CUDA major to trace is unknown" + ), Self::UnsupportedMajor(major) => { write!( formatter, @@ -72,6 +91,14 @@ impl fmt::Display for CuptiCompatibilityError { "failed to inspect the dynamic linker cache: {detail}" ) } + Self::DeletedLibrary(path) => write!( + formatter, + "the target maps {} but the file was deleted, so its CUDA major cannot be read", + path.display() + ), + Self::InvalidLibrary(path) => { + write!(formatter, "{} has no libcupti.so.N SONAME", path.display()) + } Self::Io { path, source } => { write!(formatter, "failed to inspect {}: {source}", path.display()) } @@ -88,25 +115,38 @@ impl Error for CuptiCompatibilityError { } } -/// Return the CUDA/CUPTI major observable from a target's loaded libraries. +/// Return the CUDA major to trace in a target: the major of its loaded +/// libcupti, or of its libcudart when no CUPTI is loaded. /// /// # Errors /// -/// Returns an error if loaded CUDA and CUPTI libraries report conflicting -/// majors or if the observed major is unsupported. +/// Returns an error if the deciding library is mapped in more than one major +/// or if the major is unsupported. pub fn target_major(report: &ProcessReport) -> Result, CuptiCompatibilityError> { - target_major_from_libraries(&report.loaded_libraries) + target_major_from_libraries(&report.loaded_libraries, &loaded_cupti(report)?) } fn target_major_from_libraries( libraries: &[String], + loaded_cupti: &[LoadedCupti], ) -> Result, CuptiCompatibilityError> { - let cupti = collect_target_cupti_majors(libraries); - let runtime = collect_majors(libraries, "libcudart.so."); - let observed = cupti.union(&runtime).copied().collect::>(); - + // CUPTI traces through the driver, so a libcudart of another major that + // something loaded beside it does not change which Agent to use. + let cupti = loaded_cupti + .iter() + .map(|cupti| cupti.major) + .collect::>(); + let (library, observed) = if cupti.is_empty() { + ("libcudart", collect_majors(libraries, "libcudart.so.")) + } else { + ("libcupti", cupti) + }; + let observed = observed.into_iter().collect::>(); if observed.len() > 1 { - return Err(CuptiCompatibilityError::ConflictingTargetVersions(observed)); + return Err(CuptiCompatibilityError::ConflictingTargetVersions { + library, + majors: observed, + }); } let major = observed.first().copied(); if let Some(major) = major { @@ -115,6 +155,97 @@ fn target_major_from_libraries( Ok(major) } +/// libcudart majors the target maps besides the major of its loaded +/// libcupti. Empty when no CUPTI is loaded, since libcudart then decides. +/// +/// # Errors +/// +/// Returns an error when a mapped libcupti cannot be read. +pub fn other_runtime_majors(report: &ProcessReport) -> Result, CuptiCompatibilityError> { + let cupti = loaded_cupti(report)? + .into_iter() + .map(|cupti| cupti.major) + .collect::>(); + if cupti.is_empty() { + return Ok(Vec::new()); + } + Ok(collect_majors(&report.loaded_libraries, "libcudart.so.") + .difference(&cupti) + .copied() + .collect()) +} + +/// Every libcupti the target maps, with its major. A file named by its CUDA +/// major (`libcupti.so.13`) gives it directly; a toolkit's calendar-versioned +/// file (`libcupti.so.2025.3.0`) gives it through its SONAME, read through +/// the target's root. +fn loaded_cupti(report: &ProcessReport) -> Result, CuptiCompatibilityError> { + let mut loaded = Vec::new(); + for library in &report.loaded_libraries { + let (name, deleted) = match library.strip_suffix(" (deleted)") { + Some(name) => (name, true), + None => (library.as_str(), false), + }; + let path = Path::new(name); + let Some(named) = library_major(path, "libcupti.so.") else { + continue; + }; + let major = if named < 100 { + named + } else if deleted { + return Err(CuptiCompatibilityError::DeletedLibrary(path.to_owned())); + } else { + let root = PathBuf::from(format!("/proc/{}/root", report.target.pid)); + soname_major(&root.join(path.strip_prefix("/").unwrap_or(path)))? + }; + loaded.push(LoadedCupti { + path: path.to_owned(), + major, + deleted, + }); + } + Ok(loaded) +} + +/// A libcupti the target maps. +struct LoadedCupti { + path: PathBuf, + major: u32, + /// The file was deleted after the target loaded it. + deleted: bool, +} + +fn soname_major(path: &Path) -> Result { + use object::read::elf::{Dyn, ElfFile64}; + let file = fs::File::open(path).map_err(|source| CuptiCompatibilityError::Io { + path: path.to_owned(), + source, + })?; + let cache = object::ReadCache::new(file); + let invalid = || CuptiCompatibilityError::InvalidLibrary(path.to_owned()); + let elf = ElfFile64::::parse(&cache).map_err(|_| invalid())?; + let endian = elf.endian(); + let sections = elf.elf_section_table(); + let (dynamic, link) = sections + .dynamic(endian, elf.data()) + .map_err(|_| invalid())? + .ok_or_else(invalid)?; + let strings = sections + .strings(endian, elf.data(), link) + .map_err(|_| invalid())?; + let entry = dynamic + .iter() + .find(|entry| entry.tag32(endian) == Some(object::elf::DT_SONAME)) + .ok_or_else(invalid)?; + let offset = u32::try_from(entry.d_val(endian)).map_err(|_| invalid())?; + let soname = strings.get(offset).map_err(|()| invalid())?; + std::str::from_utf8(soname) + .ok() + .and_then(|name| library_major(Path::new(name), "libcupti.so.")) + .filter(|major| *major < 100) + .ok_or_else(invalid) +} + /// Locate the CUPTI library matching the target process. /// /// # Errors @@ -122,9 +253,14 @@ fn target_major_from_libraries( /// Returns an error when the target version is unsupported, installed versions /// are ambiguous, or the matching library cannot be located. pub fn resolve_library(report: &ProcessReport) -> Result { - let target_major = target_major(report)?; + let cupti = loaded_cupti(report)?; + let target_major = target_major_from_libraries(&report.loaded_libraries, &cupti)?; if let Some(major) = target_major { - if let Some(path) = loaded_library(&report.loaded_libraries, "libcupti.so.", major) { + if let Some(path) = cupti + .iter() + .find(|cupti| cupti.major == major && !cupti.deleted) + .map(|cupti| cupti.path.clone()) + { return Ok(CuptiLibrary { major, path, @@ -173,21 +309,6 @@ fn collect_majors(libraries: &[String], prefix: &str) -> BTreeSet { .collect() } -fn collect_target_cupti_majors(libraries: &[String]) -> BTreeSet { - collect_majors(libraries, "libcupti.so.") - .into_iter() - .filter(|major| *major < 100) - .collect() -} - -fn loaded_library(libraries: &[String], prefix: &str, major: u32) -> Option { - libraries.iter().find_map(|library| { - let path = Path::new(library); - (library_major(path, prefix) == Some(major) && !library.ends_with(" (deleted)")) - .then(|| path.to_owned()) - }) -} - fn library_major(path: &Path, prefix: &str) -> Option { let file_name = path.file_name()?.to_str()?; let suffix = file_name.strip_prefix(prefix)?; @@ -291,11 +412,14 @@ fn known_cuda_paths(major: u32) -> Result, CuptiCompatibilityError> #[cfg(test)] mod tests { - use std::path::Path; + use std::{ + fs, + path::{Path, PathBuf}, + }; use super::{ - CuptiCompatibilityError, collect_target_cupti_majors, library_major, parse_linker_cache, - target_major_from_libraries, + CuptiCompatibilityError, LoadedCupti, library_major, other_runtime_majors, + parse_linker_cache, soname_major, target_major, target_major_from_libraries, }; #[test] @@ -326,10 +450,71 @@ mod tests { assert_eq!(libraries.len(), 2); } + /// CUPTI files named by their major, as `loaded_cupti` reads them. + fn named(libraries: &[String]) -> Vec { + libraries + .iter() + .filter_map(|library| { + library_major(Path::new(library), "libcupti.so.") + .filter(|major| *major < 100) + .map(|major| LoadedCupti { + path: PathBuf::from(library), + major, + deleted: false, + }) + }) + .collect() + } + + /// A shared library at `directory/file` with the given SONAME. + fn shared_library(directory: &Path, file: &str, soname: &str) -> PathBuf { + let source = directory.join("empty.c"); + fs::write(&source, "int xprobe_empty;\n").unwrap(); + let path = directory.join(file); + let status = std::process::Command::new("cc") + .args(["-shared", "-fPIC", &format!("-Wl,-soname,{soname}"), "-o"]) + .arg(&path) + .arg(&source) + .status() + .unwrap(); + assert!(status.success()); + path + } + #[test] - fn ignores_calendar_versions_in_mapped_cupti_file_names() { - let libraries = vec!["/usr/local/cuda/lib64/libcupti.so.2025.1.1".to_owned()]; - assert!(collect_target_cupti_majors(&libraries).is_empty()); + fn reads_the_major_of_a_calendar_versioned_cupti_from_its_soname() { + let directory = std::env::temp_dir().join(format!("xprobe-soname-{}", std::process::id())); + fs::create_dir_all(&directory).unwrap(); + let cupti = shared_library(&directory, "libcupti.so.2025.3.0", "libcupti.so.13"); + let other = shared_library(&directory, "libcupti.so.2025.1.0", "libother.so.1"); + + let mut report = crate::inspect::run(std::process::id()).unwrap(); + report.loaded_libraries = vec![ + "/venv/nvidia/cuda_runtime/lib/libcudart.so.12".to_owned(), + "/usr/local/cuda-13.0/lib64/libcudart.so.13".to_owned(), + cupti.to_string_lossy().into_owned(), + ]; + assert_eq!(target_major(&report).unwrap(), Some(13)); + assert_eq!(other_runtime_majors(&report).unwrap(), vec![12]); + + // A deleted CUPTI still decides: by name, or as an error when only + // its SONAME would tell. + report.loaded_libraries = vec![ + "/venv/nvidia/cuda_runtime/lib/libcudart.so.12".to_owned(), + "/venv/nvidia/cu13/lib/libcupti.so.13 (deleted)".to_owned(), + ]; + assert_eq!(target_major(&report).unwrap(), Some(13)); + report.loaded_libraries[1] = format!("{} (deleted)", cupti.display()); + assert!(matches!( + target_major(&report), + Err(CuptiCompatibilityError::DeletedLibrary(_)) + )); + + assert!(matches!( + soname_major(&other), + Err(CuptiCompatibilityError::InvalidLibrary(_)) + )); + fs::remove_dir_all(&directory).unwrap(); } #[test] @@ -338,20 +523,51 @@ mod tests { "/usr/lib/libcudart.so.12.9".to_owned(), "/usr/lib/libcupti.so.2025.1.1".to_owned(), ]; - assert_eq!(target_major_from_libraries(&cuda12).unwrap(), Some(12)); + assert_eq!( + target_major_from_libraries(&cuda12, &named(&cuda12)).unwrap(), + Some(12) + ); - let conflicting = vec![ - "/usr/lib/libcudart.so.12".to_owned(), + // A libcudart.so.12 loaded beside CUDA 13's CUPTI does not decide. + let extra_runtime = vec![ + "/usr/local/cuda-13.0/lib64/libcudart.so.13".to_owned(), + "/venv/nvidia/cu13/lib/libcudart.so.13".to_owned(), + "/venv/nvidia/cuda_runtime/lib/libcudart.so.12".to_owned(), + "/venv/nvidia/cu13/lib/libcupti.so.13".to_owned(), + ]; + assert_eq!( + target_major_from_libraries(&extra_runtime, &named(&extra_runtime)).unwrap(), + Some(13) + ); + + let two_cupti = vec![ + "/usr/lib/libcupti.so.12".to_owned(), "/usr/lib/libcupti.so.13".to_owned(), ]; assert!(matches!( - target_major_from_libraries(&conflicting), - Err(CuptiCompatibilityError::ConflictingTargetVersions(_)) + target_major_from_libraries(&two_cupti, &named(&two_cupti)), + Err(CuptiCompatibilityError::ConflictingTargetVersions { + library: "libcupti", + .. + }) + )); + + // Without CUPTI, two libcudart majors leave the major unknown. + let two_runtimes = vec![ + "/usr/lib/libcudart.so.12".to_owned(), + "/usr/lib/libcudart.so.13".to_owned(), + ]; + assert!(matches!( + target_major_from_libraries(&two_runtimes, &named(&two_runtimes)), + Err(CuptiCompatibilityError::ConflictingTargetVersions { + library: "libcudart", + .. + }) )); let unsupported = vec!["/usr/lib/libcudart.so.11".to_owned()]; assert!(matches!( - target_major_from_libraries(&unsupported), + target_major_from_libraries(&unsupported, &named(&unsupported)), Err(CuptiCompatibilityError::UnsupportedMajor(11)) )); } diff --git a/xprobe/core/src/validate.rs b/xprobe/core/src/validate.rs index e63d3d5..79bf798 100644 --- a/xprobe/core/src/validate.rs +++ b/xprobe/core/src/validate.rs @@ -204,7 +204,7 @@ pub fn run( &mut issues, &mut warnings, ); - check_cupti_compatibility(report, &requirements, &mut issues); + check_cupti_compatibility(report, &requirements, &mut issues, &mut warnings); if requirements.agent_activation == AgentActivation::AlreadyLoaded { warnings.extend(loaded_agent(report)); } @@ -276,12 +276,36 @@ fn check_cupti_compatibility( report: &ProcessReport, requirements: &ValidationRequirements, issues: &mut Vec, + warnings: &mut Vec, ) { if !requirements.needs_cupti { return; } - if let Err(error) = cupti_compat::target_major(report) { - issues.push(issue(error.code(), error.to_string())); + match cupti_compat::target_major(report) { + Err(error) => issues.push(issue(error.code(), error.to_string())), + Ok(Some(major)) => { + let others = match cupti_compat::other_runtime_majors(report) { + Ok(others) => others, + Err(error) => return issues.push(issue(error.code(), error.to_string())), + }; + if !others.is_empty() { + let mut extra = warning( + "EXTRA_CUDA_RUNTIME", + &format!( + "the target also maps libcudart majors {others:?}; xprobe uses CUDA {major}, the major of its loaded libcupti" + ), + ); + extra + .details + .insert("cuda_major".to_owned(), serde_json::Value::from(major)); + extra.details.insert( + "other_runtime_majors".to_owned(), + serde_json::Value::from(others), + ); + warnings.push(extra); + } + } + Ok(None) => {} } } @@ -1447,6 +1471,34 @@ mod tests { ); } + #[test] + fn follows_loaded_cupti_and_warns_about_another_cudart() { + let mut report = inspect::run(std::process::id()).unwrap(); + report.cuda.xprobe_cupti_loaded = true; + report.capabilities.cuda_callback = true; + report.capabilities.cuda_activity = true; + report.loaded_libraries.extend( + [ + "/venv/nvidia/cu13/lib/libcudart.so.13", + "/venv/nvidia/cu13/lib/libcupti.so.13", + "/venv/nvidia/cuda_runtime/lib/libcudart.so.12", + ] + .map(str::to_owned), + ); + let result = run(&report, "cuda:kernel_start", "cuda:kernel_end", "exact").unwrap(); + assert!(result.valid, "{:?}", result.issues); + let extra = result + .warnings + .iter() + .find(|warning| warning.code == "EXTRA_CUDA_RUNTIME") + .unwrap(); + assert_eq!(extra.details["cuda_major"], 13); + assert_eq!( + extra.details["other_runtime_majors"], + serde_json::json!([12]) + ); + } + #[test] fn reports_nvtx_startup_requirement_before_agent_is_loaded() { let report = inspect::run(std::process::id()).unwrap(); From 3507ab3291ea2fbfdf33322a8259f2e71f84e367 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 22:34:42 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=90=9B=20fix:=20suggest=20another=20-?= =?UTF-8?q?-match=20only=20for=20correlation=20policy=20problems?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit measure told users to rerun with --match for any validation issue, including an unsupported CUDA version, where changing the policy does not help. --- xprobe/cli/src/live.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/xprobe/cli/src/live.rs b/xprobe/cli/src/live.rs index 0a330e9..88248f2 100644 --- a/xprobe/cli/src/live.rs +++ b/xprobe/cli/src/live.rs @@ -451,7 +451,12 @@ pub(crate) fn single_edge_plan(request: &LiveMeasureRequest) -> Result Date: Thu, 3 Dec 2026 22:34:42 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=93=A6=20build:=20install=20the=20whe?= =?UTF-8?q?el's=20CUPTI=20Agents=20under=20libexec?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pip install --target drops a wheel's top-level lib/ data directory, so the Agents were listed in RECORD but never written. The wheel now installs them to libexec/xprobe/cudaNN, which the CLI also searches, and test_wheel.sh covers a --target install. --- docs/cli-reference.md | 2 +- docs/installation.md | 2 +- scripts/build-wheel.py | 9 +++++---- tests/install/test_wheel.sh | 33 ++++++++++++++++++++++----------- xprobe/cli/src/live.rs | 5 +++++ 5 files changed, 34 insertions(+), 17 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 5d1f1ee..8d206c0 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -269,7 +269,7 @@ Results follow `schemas/trigger-result.schema.json` (schema `3.0`). ### Live capture and the CUDA Agent - Host endpoints attach every eBPF link before arming. A duration capture that reaches `--max-events` fails with `EVENT_RATE_TOO_HIGH`. -- CUDA endpoints find the Agent from `--agent`, then `XPROBE_CUPTI_AGENT_PATH`, then `../lib/xprobe/cuda12|cuda13`, then the matching build path. +- CUDA endpoints find the Agent from `--agent`, then `XPROBE_CUPTI_AGENT_PATH`, then `../lib/xprobe/cuda12|cuda13` and `../libexec/xprobe/cuda12|cuda13` next to the CLI, then the matching build path. - One xprobe session owns the Agent at a time. While it runs, another `measure` on the same target fails with `CUPTI_AGENT_BUSY` and leaves the capture alone; combine edges into one measurement graph instead. If torch.profiler or an Nsight tool holds the target's CUPTI subscriber, `measure` fails with `CUPTI_NOT_AVAILABLE` and a hint naming them. - Live injection needs Linux x86_64, the same mount namespace as the target, and ptrace permission. It prints a warning to stderr and emits `CUPTI_AGENT_INJECTED`. On stop it disables CUPTI and removes its private socket while leaving the `.so` mapped. A later `measure` reuses the mapped Agent, even if its file was deleted. `validate` warns `CUPTI_AGENT_ALREADY_LOADED` with `agent_path` and `file_deleted` when a target holds an Agent; see [CUPTI Agent](cupti-agent.md) for what it keeps. - NVTX thread ranges are tracked by `(tid, push_level)` and process ranges by `range_id` across threads (`start_tid`). ASCII `PushA`/`StartA` and the `Ex` forms are supported; wide and registered strings and CUPTI Range Profiling are not. diff --git a/docs/installation.md b/docs/installation.md index 875a4ca..8e98601 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -13,7 +13,7 @@ xprobe --version For pre-releases (`X.Y.Z.devN`), pass `--pre` (`pip install --pre xprobe`). -`pip` installs `xprobe` into `/bin/` and the CUPTI Agents into `/lib/xprobe/cuda12` and `cuda13` (the layout the CLI searches automatically), plus `schemas/` and `skills/` under `/share/xprobe`. This works in virtualenvs, conda/mamba, and `pip install --user`. +`pip` installs `xprobe` into `/bin/` and the CUPTI Agents into `/libexec/xprobe/cuda12` and `cuda13` (the CLI looks there automatically), plus `schemas/` and `skills/` under `/share/xprobe`. This works in virtualenvs, conda/mamba, `pip install --user`, and `pip install --target DIR` (run `DIR/bin/xprobe`). ## Standalone release archive diff --git a/scripts/build-wheel.py b/scripts/build-wheel.py index 9f034f6..f1dbaaa 100755 --- a/scripts/build-wheel.py +++ b/scripts/build-wheel.py @@ -2,8 +2,9 @@ """Build the PyPI wheel from a verified release staging directory. The wheel installs the CLI into the environment's `bin/` and the CUPTI Agents -into `lib/xprobe/cudaNN/`, preserving the `bin/../lib/xprobe` layout the CLI -searches. It contains no Python code and supports glibc 2.34 or newer on +into `libexec/xprobe/cudaNN/`, which the CLI searches as `bin/../libexec/xprobe`. +`pip install --target` keeps `bin/`, `libexec/`, and `share/` but drops a +`lib/` data directory, so the Agents do not go there. It contains no Python code and supports glibc 2.34 or newer on x86_64, matching the release archive. scripts/build-wheel.py dist/xprobe-X.Y.Z-linux-x86_64 dist @@ -43,8 +44,8 @@ # (path inside the staging directory, install scheme path, mode) PAYLOAD = ( ("bin/xprobe", "scripts/xprobe", 0o755), - ("lib/xprobe/cuda12/libxprobe-cupti.so", "data/lib/xprobe/cuda12/libxprobe-cupti.so", 0o755), - ("lib/xprobe/cuda13/libxprobe-cupti.so", "data/lib/xprobe/cuda13/libxprobe-cupti.so", 0o755), + ("lib/xprobe/cuda12/libxprobe-cupti.so", "data/libexec/xprobe/cuda12/libxprobe-cupti.so", 0o755), + ("lib/xprobe/cuda13/libxprobe-cupti.so", "data/libexec/xprobe/cuda13/libxprobe-cupti.so", 0o755), ) SHARED_TREES = ("schemas", "skills") diff --git a/tests/install/test_wheel.sh b/tests/install/test_wheel.sh index 4d83eff..218ff95 100755 --- a/tests/install/test_wheel.sh +++ b/tests/install/test_wheel.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Install the PyPI wheel into a fresh virtual environment and check that the -# CLI runs and finds both CUPTI Agents through the bin/../lib/xprobe layout. +# Install the PyPI wheel into a fresh virtual environment, and with +# `pip install --target`, and check that the CLI runs and finds both CUPTI +# Agents through the bin/../libexec/xprobe layout. set -euo pipefail if [[ $# -ne 1 ]]; then @@ -24,22 +25,32 @@ expected=$(basename "${wheel}" | sed -n 's/^xprobe-\([0-9]*\.[0-9]*\.[0-9]*\)\(\ echo "unexpected version: ${version} (expected ${expected})" >&2 exit 1 } -for major in 12 13; do - agent="$(dirname "${xprobe}")/../lib/xprobe/cuda${major}/libxprobe-cupti.so" - [[ -x "${agent}" ]] || { echo "CUDA ${major} Agent not installed beside the CLI: ${agent}" >&2; exit 1; } - LC_ALL=C readelf -d "${agent}" | grep -Fq "Shared library: [libcupti.so.${major}]" || { - echo "CUDA ${major} Agent is not linked to libcupti.so.${major}" >&2 - exit 1 - } -done +check_agents() { + local major agent + for major in 12 13; do + agent="$(dirname "$1")/../libexec/xprobe/cuda${major}/libxprobe-cupti.so" + [[ -x "${agent}" ]] || { echo "CUDA ${major} Agent not installed beside the CLI: ${agent}" >&2; exit 1; } + LC_ALL=C readelf -d "${agent}" | grep -Fq "Shared library: [libcupti.so.${major}]" || { + echo "CUDA ${major} Agent is not linked to libcupti.so.${major}" >&2 + exit 1 + } + done +} +check_agents "${xprobe}" [[ -f "${work}/venv/share/xprobe/skills/xprobe-perf-profiling/SKILL.md" ]] || { echo "Skill was not installed under share/xprobe" >&2 exit 1 } "${xprobe}" doctor >/dev/null "${work}/venv/bin/python" -m pip uninstall --quiet --yes xprobe -[[ ! -e "${xprobe}" && ! -e "${work}/venv/lib/xprobe/cuda12/libxprobe-cupti.so" ]] || { +[[ ! -e "${xprobe}" && ! -e "${work}/venv/libexec/xprobe/cuda12/libxprobe-cupti.so" ]] || { echo "uninstall left xprobe files behind" >&2 exit 1 } + +# A --target install keeps the same bin/ and libexec/ layout. +"${work}/venv/bin/python" -m pip install --quiet --no-index --target "${work}/target" "${wheel}" +[[ -x "${work}/target/bin/xprobe" ]] || { echo "--target install has no bin/xprobe" >&2; exit 1; } +check_agents "${work}/target/bin/xprobe" +"${work}/target/bin/xprobe" doctor >/dev/null echo "wheel ok: ${version} with python $("${python}" -c 'import sys; print(sys.version.split()[0])')" diff --git a/xprobe/cli/src/live.rs b/xprobe/cli/src/live.rs index 88248f2..81d86f4 100644 --- a/xprobe/cli/src/live.rs +++ b/xprobe/cli/src/live.rs @@ -947,6 +947,11 @@ pub(crate) fn resolve_agent_path( "../lib/xprobe/cuda{}/libxprobe-cupti.so", cupti.major )), + // Where the PyPI wheel installs it. + parent.join(format!( + "../libexec/xprobe/cuda{}/libxprobe-cupti.so", + cupti.major + )), parent.join(format!("cuda{}/libxprobe-cupti.so", cupti.major)), PathBuf::from(format!( "build/cupti/cuda{}/libxprobe-cupti.so", From ad01d708f844efb5af84d156738f093943a7def1 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 22:34:42 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=F0=9F=90=9B=20fix:=20report=20perf=5Fevent?= =?UTF-8?q?=5Fparanoid=3D2=20as=20available=20in=20doctor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit At 2 an unprivileged user can still sample the user space of its own processes, which is all --cpu-sample needs, but doctor reported it as restricted. --cpu-sample still reports another user's target as restricted. --- xprobe/core/src/cpu_sampling.rs | 37 ++++++++++++++++++++++++++++++++- xprobe/core/src/doctor.rs | 4 +++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/xprobe/core/src/cpu_sampling.rs b/xprobe/core/src/cpu_sampling.rs index b1c8b68..cb7cb19 100644 --- a/xprobe/core/src/cpu_sampling.rs +++ b/xprobe/core/src/cpu_sampling.rs @@ -247,7 +247,17 @@ fn effective_perf_check( )), }; } - report.checks.perf_event_paranoid.clone() + let mut check = report.checks.perf_event_paranoid.clone(); + // doctor allows perf_event_paranoid=2 for the caller's own processes; + // this target belongs to another user. + if check.status == CheckStatus::Available { + check.status = CheckStatus::Restricted; + check.detail = Some(format!( + "the target runs as another user; sampling it needs CAP_PERFMON or CAP_SYS_ADMIN; perf_event_paranoid={}", + check.detail.as_deref().unwrap_or("unknown") + )); + } + check } fn python_symbolization_status( @@ -333,3 +343,28 @@ fn warning(code: &str, message: &str) -> Warning { details: BTreeMap::new(), } } + +#[cfg(test)] +mod tests { + use xprobe_protocol::{CheckResult, CheckStatus}; + + use super::effective_perf_check; + + #[test] + fn allows_paranoid_two_only_for_the_callers_own_processes() { + let mut report = crate::doctor::run().unwrap(); + report.capabilities.uprobe = false; + report.environment.effective_uid = 1000; + report.checks.perf_event_paranoid = CheckResult { + status: CheckStatus::Available, + detail: Some("2".to_owned()), + }; + assert_eq!( + effective_perf_check(&report, 1000).status, + CheckStatus::Available + ); + let other_user = effective_perf_check(&report, 1001); + assert_eq!(other_user.status, CheckStatus::Restricted); + assert!(other_user.detail.unwrap().contains("another user")); + } +} diff --git a/xprobe/core/src/doctor.rs b/xprobe/core/src/doctor.rs index 22f3bd9..efb7c02 100644 --- a/xprobe/core/src/doctor.rs +++ b/xprobe/core/src/doctor.rs @@ -70,7 +70,9 @@ pub fn run() -> Result { .into_owned(); let btf = path_check("/sys/kernel/btf/vmlinux")?; - let perf_event_paranoid = integer_setting_check("/proc/sys/kernel/perf_event_paranoid", 1)?; + // At 2 an unprivileged user can still sample the user space of its own + // processes, which is all --cpu-sample asks for. + let perf_event_paranoid = integer_setting_check("/proc/sys/kernel/perf_event_paranoid", 2)?; let ptrace_scope = integer_setting_check("/proc/sys/kernel/yama/ptrace_scope", 0)?; let kernel_lockdown = lockdown_check()?; let ebpf_permissions = ebpf_permission_check(effective_capabilities); From 59a0e8d1cb9c857e375188275215f521a9eae3e8 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 22:34:42 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=F0=9F=93=9D=20docs:=20describe=20how=20mea?= =?UTF-8?q?sure=20finds=20a=20loaded=20Agent's=20start=20function?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/cupti-agent.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index d08948b..6ce8472 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -16,7 +16,7 @@ Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.s - `CLOSE` (used after automatic injection) also removes the private socket. - Neither path calls `dlclose`: unloading callback code in a live CUDA process is unsafe. - After a capture the Agent stays mapped with CUPTI callbacks and activity off, and keeps the last capture's record buffers: 200 bytes per `--max-events` record, plus as much again for a trigger's ring snapshot, until the next capture replaces them or the target exits. - - A later `measure` finds the mapped Agent by the name it was loaded under (`dlopen` with `RTLD_NOLOAD`), so deleting its file, as when a temporary venv is removed, does not stop later captures. `validate` warns `CUPTI_AGENT_ALREADY_LOADED` with `agent_path` and `file_deleted`. + - A later `measure` reads the start function from the mapped Agent's file. If that file was deleted, as when a temporary venv is removed, it asks the target's loader for the Agent by the name it was loaded under (`dlopen` with `RTLD_NOLOAD`), so later captures still work. `validate` warns `CUPTI_AGENT_ALREADY_LOADED` with `agent_path` and `file_deleted`. **Prerequisites**: target and xprobe must share a mount namespace, and ptrace permissions (Yama, `CAP_SYS_PTRACE`, seccomp, LSM) apply. Every remote ptrace call saves and restores registers and touched stack memory on both success and failure.