Skip to content

Commit

Permalink
Ask for sudo permission by kmemsnoop directly
Browse files Browse the repository at this point in the history
  • Loading branch information
RinHizakura committed Feb 11, 2025
1 parent feb2bab commit 1a1fb75
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 14 deletions.
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ perf-event-open-sys2 = "5.0.3"
plain = "0.2.3"
blazesym = "0.2.0-alpha.12"
clap = { version = "4.5.4", features = ["derive"] }
sudo = "0.6.0"

[build-dependencies]
anyhow = "1.0.82"
Expand Down
40 changes: 26 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::mem::MaybeUninit;
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
Expand Down Expand Up @@ -109,19 +110,18 @@ struct Cli {
plat_dev: Option<String>,
}

fn parse_addr(bp_type: u32) -> Result<usize> {
let cli = Cli::parse();
let expr = cli.expr;
let pid_task = cli.pid_task;
let pci_dev = cli.pci_dev;
let usb_dev = cli.usb_dev;
let plat_dev = cli.plat_dev;
let vmlinux = cli.vmlinux;
fn parse_addr(cli: &Cli, bp_type: u32) -> Result<usize> {
let expr = &cli.expr;
let pid_task = &cli.pid_task;
let pci_dev = &cli.pci_dev;
let usb_dev = &cli.usb_dev;
let plat_dev = &cli.plat_dev;
let vmlinux = &cli.vmlinux;

/* Use kexpr if special option is specified.
* FIXME: If several kexpr option is specified, kmemsnoop
* only takes one of it by order. Do we want to avoid this? */
if let Some(pid) = pid_task {
if let Some(pid) = *pid_task {
return task_kexpr2addr(pid, &expr);
}

Expand Down Expand Up @@ -149,9 +149,8 @@ fn parse_addr(bp_type: u32) -> Result<usize> {
ksym2addr(&expr, bp_type)
}

fn parse_bp() -> (u32, u64) {
let cli = Cli::parse();
let bp = cli.bp;
fn parse_bp(cli: &Cli) -> (u32, u64) {
let bp = &cli.bp;

let bp_len = match bp {
BpType::R1 | BpType::W1 | BpType::RW1 | BpType::X1 => 1,
Expand All @@ -170,8 +169,21 @@ fn parse_bp() -> (u32, u64) {
}

fn main() -> Result<()> {
let (bp_type, bp_len) = parse_bp();
let addr = parse_addr(bp_type)?;
let cli = Cli::parse();

if sudo::check() != sudo::RunningAs::Root {
println!("Root permission is required for kmemsnoop");
/* Force to ask password for sudo */
Command::new("sudo")
.arg("-k")
.spawn()
.expect("Fail to run 'sudo -k'");

let _ = sudo::escalate_if_needed();
}

let (bp_type, bp_len) = parse_bp(&cli);
let addr = parse_addr(&cli, bp_type)?;

println!("Watchpoint attached on {addr:x}");

Expand Down

0 comments on commit 1a1fb75

Please sign in to comment.