1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use std::{
    fs::{read_dir, read_to_string},
    io::{self, ErrorKind, Read},
    os::raw::c_void,
    ptr::null,
};

use nix::sys::{
    ptrace,
    signal::{self, Signal},
    wait::waitpid,
};

pub use nix::{errno::Errno, unistd::Pid};

pub mod reader;
pub mod writer;

pub use reader::ProcessReader;
pub use writer::ProcessWriter;

const POINTER_WIDTH: usize = usize::BITS as usize / 8;

fn get_process_status_name(file: &str) -> io::Result<String> {
    let data = read_to_string(file)?;
    let line = data.lines().next().expect("Bad /proc/*/status format");
    if let Some(name) = line.strip_prefix("Name:\t") {
        return Ok(name.to_string());
    }

    Err(io::Error::new(
        ErrorKind::NotFound,
        format!("Failed to find name in {file}"),
    ))
}

fn check_process_status_file(file: &str, target: &str) -> io::Result<bool> {
    Ok(get_process_status_name(file)?.contains(target))
}

fn check_process_status_file_strict(file: &str, target: &str) -> io::Result<bool> {
    Ok(get_process_status_name(file)? == target)
}

/// An attached process.
///
/// To attach to a process, call `Process::new(pid)`. To find a process by
/// name (just checks for string inclusion), use `Process::find(name)`. To
/// detach from a process, drop this struct.
///
/// Attaching to a process, as well as reading/writing its memory, stops
/// the process. To continue it, use `Process::cont()`, or detach.
#[derive(Debug)]
pub struct Process {
    pid: Pid,
    stopped: bool,

    name: String,
    base: Option<usize>,
}

impl Process {
    /// Attach to a process.
    ///
    /// Also reads its name from `/proc/<pid>/status`. If that fails, so will
    /// the method.
    pub fn new(pid: Pid) -> io::Result<Self> {
        // Call this first in case it fails
        let name = get_process_status_name(&format!("/proc/{pid}/status"))?;

        ptrace::attach(pid)?;
        waitpid(pid, None)?;

        Ok(Self {
            pid,
            stopped: true,

            name,
            base: None,
        })
    }

    /// Finds a process by name, then calls `Process::new`. Simply checks for string inclusion (e.g.
    /// `myapp` will match both `./myapp --gui` and `find / | grep myapp`, whichever has a lower pid).
    pub fn find(target: &str) -> io::Result<Self> {
        let dir = read_dir("/proc")?;

        for entry in dir {
            let entry = entry?;
            if !entry
                .file_name()
                .to_string_lossy()
                .chars()
                .all(char::is_numeric)
            {
                continue;
            }

            if check_process_status_file(
                &format!("/proc/{}/status", entry.file_name().to_string_lossy()),
                target,
            )? {
                return Self::new(Pid::from_raw(
                    entry.file_name().to_string_lossy().parse().unwrap(),
                ));
            }
        }

        Err(io::Error::new(
            ErrorKind::NotFound,
            format!("Failed to find process `{target}`"),
        ))
    }

    /// Finds a process by name, then calls `Process::new`. Only allows strict matches (e.g.
    /// `myapp` won't match `./myapp --gui` and `find / | grep myapp`).
    pub fn find_strict(target: &str) -> io::Result<Self> {
        let dir = read_dir("/proc")?;

        for entry in dir {
            let entry = entry?;
            if !entry
                .file_name()
                .to_string_lossy()
                .chars()
                .all(char::is_numeric)
            {
                continue;
            }

            if check_process_status_file_strict(
                &format!("/proc/{}/status", entry.file_name().to_string_lossy()),
                target,
            )? {
                return Self::new(Pid::from_raw(
                    entry.file_name().to_string_lossy().parse().unwrap(),
                ));
            }
        }

        Err(io::Error::new(
            ErrorKind::NotFound,
            format!("Failed to find process `{target}`"),
        ))
    }

    /// Gets the base address of the process' r/w memory (the first entry in `/proc/<pid>/maps` that
    /// contains both `rw-p` and the process name).
    ///
    /// If it hasn't been called yet, calling `<read/write>_word_offset` will call this first.
    pub fn get_base(&mut self) -> io::Result<()> {
        if self.base.is_some() {
            return Ok(());
        }

        let file = format!("/proc/{}/maps", self.pid);

        let data = read_to_string(file)?;
        for line in data.lines() {
            if line.contains("rw-p") && line.contains(&self.name) {
                let (base, _) = line.split_once('-').ok_or(Errno::ENOKEY)?;

                self.base = Some(usize::from_str_radix(base, 16).map_err(|_| {
                    io::Error::new(
                        ErrorKind::InvalidData,
                        format!("Bad format in /proc/{}/maps", self.pid),
                    )
                })?);
                return Ok(());
            }
        }

        Err(io::Error::new(
            ErrorKind::NotFound,
            format!("No suitable mapping in /proc/{}/maps", self.pid),
        ))
    }

    /// Halts the process.
    ///
    /// Called before all read/write operations.
    pub fn stop(&mut self) -> io::Result<()> {
        if !self.stopped {
            signal::kill(self.pid, Signal::SIGSTOP)?;
            waitpid(self.pid, None)?;
            self.stopped = true;
        }

        Ok(())
    }

    /// Continues the process.
    ///
    /// This is never called automatically.
    pub fn cont(&mut self) -> io::Result<()> {
        if self.stopped {
            signal::kill(self.pid, Signal::SIGCONT)?;
            self.stopped = false;
        }

        Ok(())
    }

    /// Reads a single i64 from the process' memory.
    pub fn read_word(&mut self, address: usize) -> io::Result<i64> {
        self.stop()?;

        let addr = unsafe { null::<c_void>().add(address) as *mut c_void };

        let data = ptrace::read(self.pid, addr)?;
        Ok(data)
    }

    /// Reads a single i64 from the process' memory, using `offset`.
    ///
    /// If `Process::get_base()` hasn't been called yet, calls that first.
    pub fn read_word_offset(&mut self, offset: usize) -> io::Result<i64> {
        self.get_base()?;
        self.read_word(self.base.unwrap() + offset)
    }

    /// Writes a single i64 into the process' memory.
    pub fn write_word(&mut self, address: usize, data: i64) -> io::Result<()> {
        self.stop()?;

        let addr = unsafe { null::<c_void>().add(address) as *mut c_void };

        let data = unsafe { null::<c_void>().offset(data as isize) as *mut c_void };

        unsafe {
            ptrace::write(self.pid, addr, data)?;
        }

        Ok(())
    }

    /// Writes a single i64 into the process' memory, using `offset`.
    ///
    /// If `Process::get_base()` hasn't been called yet, calls that first.
    pub fn write_word_offset(&mut self, offset: usize, data: i64) -> io::Result<()> {
        self.get_base()?;
        self.write_word(self.base.unwrap() + offset, data)
    }

    /// Resolves a chain of pointer offsets.
    pub fn pointer_chain(&mut self, mut address: usize, offsets: Vec<isize>) -> io::Result<usize> {        
        let mut reader = self.reader(address, POINTER_WIDTH)?.no_advance();

        let mut address_bytes = [0; POINTER_WIDTH];
        for offset in offsets.iter() {
            reader.goto(address);
            reader.read_exact(&mut address_bytes)?;
            address = usize::from_le_bytes(address_bytes);

            if *offset >= 0 {
       			address += *offset as usize;
       		} else {
       			address -= offset.unsigned_abs();
       		}

        }

        Ok(address)
    }

    /// Returns the pid of the attached process.
    pub fn pid(&self) -> Pid {
        self.pid
    }

    /// Returns the full name of the attached process.
    pub fn name(&self) -> String {
        self.name.clone()
    }

    /// Returns the base address of the attached process.
    pub fn base(&mut self) -> io::Result<usize> {
        self.get_base()?;
        Ok(self.base.unwrap())
    }

    /// Returns a `ProcessReader` for this process, good for `length` bytes, starting at `address`.
    pub fn reader(&mut self, address: usize, length: usize) -> io::Result<ProcessReader> {
        self.get_base()?;
        Ok(ProcessReader::new(self, address, length))
    }

    /// Returns a `ProcessWriter` for this process, starting at `address`.
    pub fn writer(&mut self, address: usize) -> io::Result<ProcessWriter> {
        self.get_base()?;
        Ok(ProcessWriter::new(self, address))
    }

    /// Returns a `ProcessReader` for this process, good for `length` bytes, starting at `offset`.
    pub fn reader_offset(&mut self, offset: isize, length: usize) -> io::Result<ProcessReader> {
        self.get_base()?;
        Ok(ProcessReader::offset(self, offset, length))
    }

    /// Returns a `ProcessWriter` for this process, starting at `offset`.
    pub fn writer_offset(&mut self, offset: isize) -> io::Result<ProcessWriter> {
        self.get_base()?;
        Ok(ProcessWriter::offset(self, offset))
    }
}

impl Drop for Process {
    fn drop(&mut self) {
        let sig = if self.stopped {
            Some(Signal::SIGCONT)
        } else {
            None
        };

        if let Err(e) = ptrace::detach(self.pid, sig) {
            panic!(
                "Failed to detach from process {} (tried to send signal {sig:?}): {e}",
                self.pid
            );
        }
    }
}