steroid 0.5.0

A lightweight framework for dynamic binary instrumentation
Documentation
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! The thread module contains everything related to the manipulation of threads.

use std::cell::{Ref, RefCell};
use std::fs::read_to_string;
use std::marker::PhantomData;
use std::mem::transmute;
use std::rc::Rc;

use nix::libc::{siginfo_t, CLD_DUMPED, CLD_EXITED, CLD_KILLED, CLD_STOPPED, CLD_TRAPPED};
use nix::sys::ptrace::{cont, detach, getevent, getregs, getsiginfo, Event};
use nix::sys::wait::waitpid;
use nix::Error as NixError;

use crate::breakpoint::BreakpointId;
use crate::error::{
    CouldNotDetermineState, CouldNotGetSignalInfo, CouldNotReadRegisters, CouldNotResume,
    CouldNotSetOptions, CouldNotWait,
};
use crate::process::{set_controller_breakpoint_id, Pid, TargetController, TargetProcess};
use crate::run::{
    Executing, PtraceEventStrategy, PtraceOption, PtraceOptionMap, Reason, RunningState, Signal,
};

pub(crate) struct ThreadHandle {
    pub(crate) tid: Pid,
    option_map: RefCell<PtraceOptionMap>,
}

/// This structure represents a running thread. It is the thread equivalent of [`TargetProcess`].
///
/// Note that a [`Thread`] is fundamentally owned by the process it belongs to. This data type
/// exists for the user to manipulate an owned data that can be consumed correctly by a
/// [`TargetController`] is case of thread exit. However a [`Thread`] borrows the process as shown
/// by the `'process` lifetime.
///
/// [`TargetController`]: crate::process::TargetController
pub struct Thread<'process> {
    handle: Rc<ThreadHandle>,
    process: &'process TargetProcess,
    _unsend: PhantomData<*mut ()>,
}

impl<'process> Thread<'process> {
    /// Returns the thread id of this [`Thread`].
    #[must_use]
    pub fn tid(&self) -> Pid {
        self.handle.tid
    }

    /// Create a [`Thread`] owned object encapsulating the given thread handle.
    pub(crate) const fn encapsulate(
        handle: Rc<ThreadHandle>,
        process: &'process TargetProcess,
    ) -> Thread<'process> {
        Thread {
            handle,
            process,
            _unsend: PhantomData,
        }
    }

    /// Get a reference to the [`option map`][PtraceOptionMap] of this thread.
    #[must_use]
    pub fn ptrace_option_map(&self) -> Ref<PtraceOptionMap> {
        self.handle.option_map.borrow()
    }
}

impl<'process> AsRef<Thread<'process>> for Thread<'process> {
    fn as_ref(&self) -> &Thread<'process> {
        self
    }
}

impl<'process> Executing for Thread<'process> {
    type StoppedRepresentation = Self;
    type WaitError = CouldNotWait;

    fn process(&self) -> &TargetProcess {
        self.process
    }

    /// Returns the PID of the thread.
    ///
    /// This corresponds to the TID of this specific thread, not the PGID of the process.
    fn pid(&self) -> Pid {
        self.tid()
    }

    fn set_ptrace_option(
        ctrl: &mut TargetController<Self>,
        option: PtraceOption,
        strategy: PtraceEventStrategy,
    ) -> Result<PtraceEventStrategy, CouldNotSetOptions> {
        let old = ctrl
            .context
            .handle
            .option_map
            .borrow_mut()
            .set(option, strategy);

        let options = ctrl.context.ptrace_option_map().as_ptrace_options();
        ctrl.write_ptrace_options(options)?;

        Ok(old)
    }

    fn wait(self) -> Result<RunningState<Self>, CouldNotWait> {
        let status = waitpid(Some(self.pid().into()), None).map_err(|err| match err {
            NixError::ECHILD => CouldNotWait::ProcessNotFound {
                pid: self.handle.tid,
                source: err.into(),
            },
            _ => todo!("Handle all errors from waitpid"),
        })?;

        let mut ctrl = TargetController::<Self>::new(self, Reason::Trapped, None);

        let reason = Reason::from_wait_status(&mut ctrl, status);
        ctrl.update_reason(reason);

        if matches!(
            ctrl.reason(),
            Reason::Exited { .. } | Reason::Signaled { .. }
        ) {
            Ok(RunningState::Exited {
                tid: ctrl.context.tid(),
                reason: *ctrl.reason(),
            })
        } else {
            if let Reason::ThreadCreated { tid } = *ctrl.reason() {
                let trace_clone_strategy = ctrl
                    .context
                    .handle
                    .option_map
                    .borrow()
                    .get(PtraceOption::TraceClone);

                if trace_clone_strategy == PtraceEventStrategy::Trace {
                    let handle = ThreadHandle::new(tid);
                    ctrl.context().process().add_thread(handle);
                } else {
                    // TODO: Manage the error gracefully.
                    detach(tid.into(), None).unwrap();
                }
            }

            set_controller_breakpoint_id(&mut ctrl);
            Ok(RunningState::Alive(ctrl))
        }
    }

    fn resume(mut ctrl: TargetController<Self>) -> Result<Self, CouldNotResume> {
        let pid = ctrl.context().pid();
        ctrl.pass_over_breakpoint()?;

        match cont(pid.into(), None) {
            Ok(()) => Ok(ctrl.context),
            Err(source) => Err(CouldNotResume::CouldNotRestart {
                pid,
                source: source.into(),
            }),
        }
    }
}

impl ThreadHandle {
    pub fn new(tid: Pid) -> Self {
        Self {
            tid,
            option_map: RefCell::default(),
        }
    }
}

/// Encapsulation of a thread providing the user with either a [`Thread`] or a [`TargetController`]
/// depending on the thread running state.
pub enum CurrentState<'process> {
    Running(Thread<'process>),
    Stopped(TargetController<Thread<'process>>),
}

fn reason_from_ptrace_event(
    event: Event,
    signo: i32,
    brk_id: Option<BreakpointId>,
    msg: i64,
) -> Reason {
    match event {
        Event::PTRACE_EVENT_CLONE => Reason::ThreadCreated {
            tid: Pid::from_raw(msg as i32),
        },

        Event::PTRACE_EVENT_STOP => {
            let signal = unsafe { transmute(signo) };

            match signal {
                Signal::SIGTRAP => brk_id.map_or_else(|| Reason::Trapped, Reason::Breakpoint),
                _ => Reason::Stopped { signal },
            }
        }
        unknown_event => {
            let cld = unknown_event as i32;
            unimplemented!("ptrace event: {:?} ({})", unknown_event, cld);
        }
    }
}

fn reason_from_siginfo(siginfo: siginfo_t, brk_id: Option<BreakpointId>, msg: i64) -> Reason {
    let status = unsafe { siginfo.si_status() };

    match siginfo.si_code {
        CLD_EXITED => Reason::Exited { exit_code: status },
        CLD_KILLED => Reason::Signaled {
            signal: unsafe { transmute(status) },
            dumped: false,
        },
        CLD_DUMPED => Reason::Signaled {
            signal: unsafe { transmute(status) },
            dumped: true,
        },
        CLD_STOPPED => Reason::Stopped {
            signal: unsafe { transmute(status) },
        },
        CLD_TRAPPED => brk_id.map_or_else(|| Reason::Trapped, Reason::Breakpoint),
        cld => {
            if cld == 0x80 /* SI_KERNEL */ || cld <= 0
            /* signal from kill, etc */
            {
                let signal = unsafe { transmute(siginfo.si_signo) };
                if signal == Signal::SIGTRAP {
                    brk_id.map_or_else(|| Reason::Trapped, Reason::Breakpoint)
                } else {
                    Reason::Stopped { signal }
                }
            } else if siginfo.si_signo == Signal::SIGTRAP as i32 {
                let event_code = cld >> 8;
                let event = unsafe { transmute(event_code) };
                reason_from_ptrace_event(event, status, brk_id, msg)
            } else {
                unreachable!("si_code == {}", cld)
            }
        }
    }
}

/// Test if the thread is stopped or still running and return either the [`Thread`] itself or a
/// [`TargetController`] over this thread if it is stopped.
///
/// This function is useful to get a [`TargetController`] back if it has been dropped without
/// resuming the remote thread, typically when using [`TargetProcess::wait`].
///
/// # Errors
///
/// This function will return an error if the file `/proc/{pgid}/task/{tid}/stat` could not be read
/// or if the registers and signal info of the stopped thread could not be read by [`ptrace(2)`].
///
/// [`ptrace(2)`]: https://man7.org/linux/man-pages/man2/ptrace.2.html
#[allow(clippy::missing_panics_doc)]
pub(crate) fn determine_state(thread: Thread) -> Result<CurrentState, CouldNotDetermineState> {
    let stat_file = format!("/proc/{}/task/{}/stat", thread.pgid(), thread.tid());
    let stat = read_to_string(stat_file)?;

    let state = stat
        .chars()
        .skip_while(|c| *c != ')')
        .nth(2) // skip the ')' and the whitespace afterwards
        .unwrap(); // get the running state character

    Ok(match state {
        'R' | 'S' | 'Z' => CurrentState::Running(thread),
        'T' | 't' => {
            let regs = getregs(thread.pid().into()).map_err(|err| CouldNotReadRegisters {
                pid: thread.pid(),
                source: err.into(),
            })?;

            let brk_id = thread
                .process()
                .breakpoints()
                .find(|brk| brk.address() as u64 == regs.rip - 1)
                .map(|brk| brk.id());

            let eventmsg = getevent(thread.pid().into()).unwrap_or_default();
            let siginfo = getsiginfo(thread.pid().into()).map_err(|err| CouldNotGetSignalInfo {
                pid: thread.pid(),
                source: err.into(),
            })?;

            let reason = reason_from_siginfo(siginfo, brk_id, eventmsg);

            CurrentState::Stopped(TargetController::new(thread, reason, brk_id))
        }
        unknown => unreachable!("Process state '{}' is not supposed to exist.", unknown),
    })
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use anyhow::Error as AnyError;

    use crate::error::CouldNotExecute;
    use crate::process::spawn_process;

    use super::*;

    fn spawn_create_thread_join_and_die() -> Result<TargetProcess, CouldNotExecute> {
        let mut path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path_buf.push("resources/test/create_thread_join_and_die");
        spawn_process::<_, _, &str>(path_buf, vec![])
    }

    #[test]
    fn set_ptrace_option_clone() -> Result<(), AnyError> {
        let mut process = spawn_create_thread_join_and_die()?;
        let mut threads = process.threads();
        let main_thread = threads
            .pop()
            .expect("Expected the process to have a main thread.");

        assert_eq!(main_thread.tid(), main_thread.pgid());

        let running_state = main_thread.wait()?;
        assert!(running_state.is_alive());
        let mut ctrl_start = running_state.assume_alive()?;

        Thread::set_ptrace_option(
            &mut ctrl_start,
            PtraceOption::TraceClone,
            PtraceEventStrategy::Trace,
        )?;

        let main_thread2 = ctrl_start.resume()?;

        let running_state2 = main_thread2.wait()?;
        assert!(running_state2.is_alive());
        let ctrl_create_thread = running_state2.assume_alive()?;

        assert!(matches!(
            *ctrl_create_thread.reason(),
            Reason::ThreadCreated { .. }
        ));
        Ok(())
    }

    #[test]
    fn whole_multithread_application() -> Result<(), AnyError> {
        let mut process = spawn_create_thread_join_and_die()?;
        let mut threads = process.threads();
        let main_thread = threads
            .pop()
            .expect("Expected the process to have a main thread.");

        assert_eq!(main_thread.tid(), main_thread.pgid());

        let running_state = main_thread.wait()?;
        assert!(running_state.is_alive());
        let mut ctrl_start = running_state.assume_alive()?;

        Thread::set_ptrace_option(
            &mut ctrl_start,
            PtraceOption::TraceClone,
            PtraceEventStrategy::Trace,
        )?;

        let main_thread2 = ctrl_start.resume()?;

        let running_state2 = main_thread2.wait()?;
        assert!(running_state2.is_alive());
        let ctrl_create_thread = running_state2.assume_alive()?;

        assert!(matches!(
            *ctrl_create_thread.reason(),
            Reason::ThreadCreated { .. }
        ));

        match *ctrl_create_thread.reason() {
            Reason::ThreadCreated { tid } => {
                let ctrl_after_thread_resumed = process.wait()?.assume_alive()?;
                let mut process_all_restarted = ctrl_after_thread_resumed.resume()?;

                let mut threads = process_all_restarted.threads();
                assert_eq!(threads.len(), 2);

                let child_thread = threads.pop().unwrap();
                let main_thread = threads.pop().unwrap();

                assert_eq!(main_thread.tid(), main_thread.pgid());
                assert_eq!(child_thread.tid(), tid);

                let state_child = child_thread.wait()?;
                assert!(state_child.has_exited());

                let state_main = main_thread.wait()?;
                assert!(state_main.has_exited());
            }
            _ => unreachable!(),
        }

        Ok(())
    }
}