use std::path::PathBuf;
const PDB_MODULE: &str = "pdb";
const PDB_ATTACH_FLAG: &str = "-p";
const SUDO: &str = "sudo";
pub const MIN_ATTACH_VERSION: PyVersion = PyVersion {
major: 3,
minor: 14,
patch: 0,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PyVersion {
pub major: u32,
pub minor: u32,
pub patch: u32,
}
impl PyVersion {
pub fn parse(s: &str) -> Option<PyVersion> {
let token = s
.split_whitespace()
.find(|t| t.chars().next().is_some_and(|c| c.is_ascii_digit()))?;
let mut parts = token.split('.');
let major = leading_u32(parts.next()?)?;
let minor = leading_u32(parts.next()?)?;
let patch = parts.next().and_then(leading_u32).unwrap_or(0);
Some(PyVersion {
major,
minor,
patch,
})
}
pub fn supports_remote_attach(&self) -> bool {
(self.major, self.minor) >= (MIN_ATTACH_VERSION.major, MIN_ATTACH_VERSION.minor)
}
}
fn leading_u32(s: &str) -> Option<u32> {
let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
digits.parse().ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
MacOs,
Linux,
}
impl Platform {
pub fn current() -> Platform {
if cfg!(target_os = "macos") {
Platform::MacOs
} else {
Platform::Linux
}
}
}
pub fn elevation_required(platform: Platform, yama_ptrace_scope: Option<u8>) -> bool {
match platform {
Platform::MacOs => true,
Platform::Linux => !matches!(yama_ptrace_scope, Some(0)),
}
}
pub fn read_yama_ptrace_scope() -> Option<u8> {
std::fs::read_to_string("/proc/sys/kernel/yama/ptrace_scope")
.ok()?
.trim()
.parse()
.ok()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachPlan {
pub interpreter: PathBuf,
pub pid: u32,
pub elevate: bool,
}
impl AttachPlan {
pub fn command_line(&self) -> (String, Vec<String>) {
let interp = self.interpreter.to_string_lossy().into_owned();
let pid = self.pid.to_string();
let pdb_args = [
"-m".to_string(),
PDB_MODULE.to_string(),
PDB_ATTACH_FLAG.to_string(),
pid,
];
if self.elevate {
let mut args = Vec::with_capacity(pdb_args.len() + 1);
args.push(interp);
args.extend(pdb_args);
(SUDO.to_string(), args)
} else {
(interp, pdb_args.to_vec())
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttachError {
UnsupportedTarget(PyVersion),
}
pub fn plan_attach(
target_version: PyVersion,
interpreter: PathBuf,
pid: u32,
platform: Platform,
yama_ptrace_scope: Option<u8>,
) -> Result<AttachPlan, AttachError> {
if !target_version.supports_remote_attach() {
return Err(AttachError::UnsupportedTarget(target_version));
}
Ok(AttachPlan {
interpreter,
pid,
elevate: elevation_required(platform, yama_ptrace_scope),
})
}
pub fn is_python_process(name: &str, exe: Option<&std::path::Path>) -> bool {
let basename = exe
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
.unwrap_or(name);
let lower = basename.to_ascii_lowercase();
let stem = lower.strip_suffix(".exe").unwrap_or(&lower);
if stem == "python" {
return true;
}
if let Some(rest) = stem.strip_prefix("python") {
return rest.starts_with(|c: char| c.is_ascii_digit());
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn parses_python_version_banner() {
assert_eq!(
PyVersion::parse("Python 3.14.2"),
Some(PyVersion {
major: 3,
minor: 14,
patch: 2
})
);
}
#[test]
fn parses_bare_version_and_two_component_version() {
assert_eq!(
PyVersion::parse("3.13.2"),
Some(PyVersion {
major: 3,
minor: 13,
patch: 2
})
);
assert_eq!(
PyVersion::parse("3.14"),
Some(PyVersion {
major: 3,
minor: 14,
patch: 0
})
);
}
#[test]
fn tolerates_prerelease_suffix_on_patch() {
assert_eq!(
PyVersion::parse("Python 3.14.0a5"),
Some(PyVersion {
major: 3,
minor: 14,
patch: 0
})
);
}
#[test]
fn rejects_non_version_strings() {
assert_eq!(PyVersion::parse(""), None);
assert_eq!(PyVersion::parse("not a version"), None);
assert_eq!(PyVersion::parse("python"), None);
}
#[test]
fn remote_attach_gate_is_3_14() {
assert!(!PyVersion::parse("3.13.2").unwrap().supports_remote_attach());
assert!(PyVersion::parse("3.14.0").unwrap().supports_remote_attach());
assert!(PyVersion::parse("3.14.2").unwrap().supports_remote_attach());
assert!(PyVersion::parse("3.15.0").unwrap().supports_remote_attach());
assert!(PyVersion::parse("4.0.0").unwrap().supports_remote_attach());
}
#[test]
fn macos_always_requires_elevation() {
assert!(elevation_required(Platform::MacOs, None));
assert!(elevation_required(Platform::MacOs, Some(0)));
assert!(elevation_required(Platform::MacOs, Some(1)));
}
#[test]
fn linux_elevation_follows_ptrace_scope() {
assert!(!elevation_required(Platform::Linux, Some(0))); assert!(elevation_required(Platform::Linux, Some(1))); assert!(elevation_required(Platform::Linux, Some(2)));
assert!(elevation_required(Platform::Linux, Some(3)));
assert!(elevation_required(Platform::Linux, None)); }
#[test]
fn command_line_without_elevation_runs_interpreter_directly() {
let plan = AttachPlan {
interpreter: PathBuf::from("/usr/bin/python3.14"),
pid: 4242,
elevate: false,
};
let (program, args) = plan.command_line();
assert_eq!(program, "/usr/bin/python3.14");
assert_eq!(args, vec!["-m", "pdb", "-p", "4242"]);
}
#[test]
fn command_line_with_elevation_wraps_in_sudo() {
let plan = AttachPlan {
interpreter: PathBuf::from("/opt/py/python3.14"),
pid: 99,
elevate: true,
};
let (program, args) = plan.command_line();
assert_eq!(program, "sudo");
assert_eq!(args, vec!["/opt/py/python3.14", "-m", "pdb", "-p", "99"]);
}
#[test]
fn plan_attach_rejects_pre_3_14_target() {
let old = PyVersion::parse("3.13.2").unwrap();
let err = plan_attach(
old,
PathBuf::from("/x/python3.14"),
7,
Platform::Linux,
Some(0),
)
.unwrap_err();
assert_eq!(err, AttachError::UnsupportedTarget(old));
}
#[test]
fn plan_attach_macos_elevates_even_with_supported_target() {
let v = PyVersion::parse("3.14.2").unwrap();
let plan =
plan_attach(v, PathBuf::from("/x/python3.14"), 7, Platform::MacOs, None).unwrap();
assert!(plan.elevate);
assert_eq!(plan.pid, 7);
}
#[test]
fn plan_attach_linux_relaxed_ptrace_skips_sudo() {
let v = PyVersion::parse("3.14.2").unwrap();
let plan = plan_attach(
v,
PathBuf::from("/x/python3.14"),
7,
Platform::Linux,
Some(0),
)
.unwrap();
assert!(!plan.elevate);
}
#[test]
fn recognizes_python_interpreters() {
assert!(is_python_process("python", None));
assert!(is_python_process("python3", None));
assert!(is_python_process("python3.14", None));
assert!(is_python_process("Python", None)); assert!(is_python_process(
"Python",
Some(Path::new("/Library/Frameworks/Python.framework/.../Python"))
));
assert!(is_python_process(
"anything",
Some(Path::new("/usr/bin/python3.14"))
));
}
#[test]
fn rejects_python_lookalikes() {
assert!(!is_python_process("pythonista", None));
assert!(!is_python_process("my_python_tool", None));
assert!(!is_python_process("node", None));
assert!(!is_python_process(
"python",
Some(Path::new("/usr/bin/node"))
));
}
}