oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! `process::linux::ptrace`, and what goes with tracing: a wait that
//! reports stops, the memory of another process, a descriptor of another
//! process.
//!
//! The requests are those of `include/uapi/linux/ptrace.h`, which every
//! architecture shares; the registers are each architecture's
//! (`arch/*/include/uapi/asm/ptrace.h`, `user.h`).

use crate::process::linux::ptrace::{
    Options, Registers, SignalInfo, Stop, SyscallInfo, SyscallStop,
};
use crate::process::linux::{WaitEvent, WaitFlags, WaitFor, Waited};
use crate::sys::syscall;
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

const PTRACE_TRACEME: usize = 0;
const PTRACE_PEEKDATA: usize = 2;
const PTRACE_POKEDATA: usize = 5;
const PTRACE_CONT: usize = 7;
const PTRACE_SINGLESTEP: usize = 9;
const PTRACE_ATTACH: usize = 16;
const PTRACE_DETACH: usize = 17;
const PTRACE_SYSCALL: usize = 24;
const PTRACE_SETOPTIONS: usize = 0x4200;
const PTRACE_GETEVENTMSG: usize = 0x4201;
const PTRACE_GETSIGINFO: usize = 0x4202;
const PTRACE_GETREGSET: usize = 0x4204;
const PTRACE_SETREGSET: usize = 0x4205;
const PTRACE_SEIZE: usize = 0x4206;
const PTRACE_INTERRUPT: usize = 0x4207;
const PTRACE_LISTEN: usize = 0x4208;
const PTRACE_GET_SYSCALL_INFO: usize = 0x420e;

const PTRACE_SYSCALL_INFO_NONE: u8 = 0;
const PTRACE_SYSCALL_INFO_ENTRY: u8 = 1;
const PTRACE_SYSCALL_INFO_EXIT: u8 = 2;
const PTRACE_SYSCALL_INFO_SECCOMP: u8 = 3;

/// `NT_PRSTATUS`: the general registers.
pub(crate) const NT_PRSTATUS: u32 = 1;
/// `NT_PRFPREG`: the floating-point registers.
pub(crate) const NT_PRFPREG: u32 = 2;

const SIGTRAP: i32 = 5;

const P_ALL: usize = 0;
const P_PID: usize = 1;
const P_PGID: usize = 2;
const P_PIDFD: usize = 3;
const WNOHANG: usize = 1;
const WSTOPPED: usize = 2;
const WEXITED: usize = 4;
const WCONTINUED: usize = 8;
const WNOWAIT: usize = 0x0100_0000;
const WNOTHREAD: usize = 0x2000_0000;
const WALL: usize = 0x4000_0000;
const CLD_EXITED: i32 = 1;
const CLD_KILLED: i32 = 2;
const CLD_DUMPED: i32 = 3;
const CLD_TRAPPED: i32 = 4;
const CLD_STOPPED: i32 = 5;
const CLD_CONTINUED: i32 = 6;

/// `siginfo_t`: 128 bytes. Three `int`s (`si_signo`, `si_errno`,
/// `si_code`), then a union that holds pointers and is aligned as they
/// are: its first member is at 16 on a 64-bit architecture, at 12 on a
/// 32-bit one.
#[repr(C, align(8))]
#[derive(Clone, Copy)]
pub(crate) struct RawSigInfo(pub(crate) [i32; 32]);

const _: () = assert!(size_of::<RawSigInfo>() == 128);

/// The index of the first `int` of the union.
pub(crate) const SI_FIELDS: usize = if cfg!(target_pointer_width = "64") {
    4
} else {
    3
};

/// An identifier that names one process: 0 and negative numbers mean
/// other things to these calls.
fn checked_pid(pid: u32) -> Result<u32> {
    if pid == 0 || pid > i32::MAX as u32 {
        return Err(ErrorKind::InvalidInput.into());
    }
    Ok(pid)
}

/// One `ptrace` call.
///
/// # Safety
///
/// `addr` and `data` must be what the request reads and writes.
unsafe fn ptrace(request: usize, pid: u32, addr: usize, data: usize) -> Result<usize> {
    // SAFETY: the caller's contract.
    unsafe { syscall!(PTRACE, request, pid, addr, data) }
}

/// A request that takes numbers alone.
fn request(request: usize, pid: u32, addr: usize, data: usize) -> Result<()> {
    // SAFETY: none of the requests this is used for passes memory.
    unsafe { ptrace(request, pid, addr, data) }.map(drop)
}

/// `PTRACE_TRACEME`. Only a system call: the child of `spawn` makes it.
pub(crate) fn trace_me() -> Result<()> {
    request(PTRACE_TRACEME, 0, 0, 0)
}

pub(crate) fn attach(pid: u32) -> Result<()> {
    request(PTRACE_ATTACH, pid, 0, 0)
}

pub(crate) fn seize(pid: u32, options: Options) -> Result<()> {
    request(PTRACE_SEIZE, pid, 0, options.bits() as usize)
}

pub(crate) fn interrupt(pid: u32) -> Result<()> {
    request(PTRACE_INTERRUPT, pid, 0, 0)
}

pub(crate) fn listen(pid: u32) -> Result<()> {
    request(PTRACE_LISTEN, pid, 0, 0)
}

pub(crate) fn detach(pid: u32, signal: i32) -> Result<()> {
    request(PTRACE_DETACH, pid, 0, signal as usize)
}

pub(crate) fn cont(pid: u32, signal: i32) -> Result<()> {
    request(PTRACE_CONT, pid, 0, signal as usize)
}

pub(crate) fn syscall(pid: u32, signal: i32) -> Result<()> {
    request(PTRACE_SYSCALL, pid, 0, signal as usize)
}

pub(crate) fn single_step(pid: u32, signal: i32) -> Result<()> {
    request(PTRACE_SINGLESTEP, pid, 0, signal as usize)
}

pub(crate) fn set_options(pid: u32, options: Options) -> Result<()> {
    request(PTRACE_SETOPTIONS, pid, 0, options.bits() as usize)
}

pub(crate) fn event_message(pid: u32) -> Result<u64> {
    let mut message: usize = 0;
    // SAFETY: the kernel writes one `unsigned long`.
    unsafe { ptrace(PTRACE_GETEVENTMSG, pid, 0, (&raw mut message).addr()) }?;
    Ok(message as u64)
}

pub(crate) fn peek(pid: u32, address: usize) -> Result<usize> {
    let mut word: usize = 0;
    // The system call, unlike the function of a C library, writes the
    // word where its last argument points.
    // SAFETY: the kernel writes one word.
    unsafe { ptrace(PTRACE_PEEKDATA, pid, address, (&raw mut word).addr()) }?;
    Ok(word)
}

pub(crate) fn poke(pid: u32, address: usize, word: usize) -> Result<()> {
    request(PTRACE_POKEDATA, pid, address, word)
}

/// `struct iovec`.
#[repr(C)]
struct IoVec {
    base: *mut u8,
    len: usize,
}

pub(crate) fn get_regset(pid: u32, kind: u32, buf: &mut [u8]) -> Result<usize> {
    let mut vec = IoVec {
        base: buf.as_mut_ptr(),
        len: buf.len(),
    };
    // SAFETY: the kernel writes at most `len` bytes where `base` points,
    // and the length it wrote in the structure.
    unsafe { ptrace(PTRACE_GETREGSET, pid, kind as usize, (&raw mut vec).addr()) }?;
    Ok(vec.len.min(buf.len()))
}

pub(crate) fn set_regset(pid: u32, kind: u32, data: &[u8]) -> Result<()> {
    let mut vec = IoVec {
        base: data.as_ptr().cast_mut(),
        len: data.len(),
    };
    // SAFETY: the kernel reads `len` bytes from `base`, and writes the
    // length it took in the structure.
    unsafe { ptrace(PTRACE_SETREGSET, pid, kind as usize, (&raw mut vec).addr()) }.map(drop)
}

pub(crate) fn registers(pid: u32) -> Result<Registers> {
    let mut registers = Registers::default();
    let mut vec = IoVec {
        base: (&raw mut registers).cast(),
        len: size_of::<Registers>(),
    };
    // SAFETY: the kernel writes at most `len` bytes of a structure any
    // bytes are a value of.
    unsafe {
        ptrace(
            PTRACE_GETREGSET,
            pid,
            NT_PRSTATUS as usize,
            (&raw mut vec).addr(),
        )
    }?;
    // A tracee of another architecture has other registers.
    if vec.len != size_of::<Registers>() {
        return Err(ErrorKind::Other.into());
    }
    Ok(registers)
}

pub(crate) fn set_registers(pid: u32, registers: &Registers) -> Result<()> {
    let mut vec = IoVec {
        base: core::ptr::from_ref(registers).cast_mut().cast(),
        len: size_of::<Registers>(),
    };
    // SAFETY: the kernel reads `len` bytes from `base`.
    unsafe {
        ptrace(
            PTRACE_SETREGSET,
            pid,
            NT_PRSTATUS as usize,
            (&raw mut vec).addr(),
        )
    }
    .map(drop)
}

pub(crate) fn signal_info(pid: u32) -> Result<SignalInfo> {
    let mut info = RawSigInfo([0; 32]);
    // SAFETY: the kernel writes one `siginfo_t`.
    unsafe { ptrace(PTRACE_GETSIGINFO, pid, 0, (&raw mut info).addr()) }?;
    Ok(SignalInfo::from_raw(info.0))
}

/// `struct ptrace_syscall_info`, with the largest member of its union.
/// Every 64-bit member is at a multiple of eight.
#[repr(C)]
#[derive(Default)]
struct RawSyscallInfo {
    op: u8,
    reserved: u8,
    flags: u16,
    arch: u32,
    instruction_pointer: u64,
    stack_pointer: u64,
    /// `entry.nr`, `seccomp.nr`, or `exit.rval`.
    first: u64,
    /// `entry.args`, `seccomp.args`; the first byte of the first is
    /// `exit.is_error`.
    args: [u64; 6],
    ret_data: u32,
    reserved2: u32,
}

const _: () = assert!(
    size_of::<RawSyscallInfo>() == 88
        && core::mem::offset_of!(RawSyscallInfo, first) == 24
        && core::mem::offset_of!(RawSyscallInfo, ret_data) == 80
);

pub(crate) fn syscall_info(pid: u32) -> Result<SyscallInfo> {
    let mut raw = RawSyscallInfo::default();
    let size = size_of::<RawSyscallInfo>();
    // SAFETY: the kernel writes at most `size` bytes.
    unsafe { ptrace(PTRACE_GET_SYSCALL_INFO, pid, size, (&raw mut raw).addr()) }?;
    let stop = match raw.op {
        PTRACE_SYSCALL_INFO_NONE => SyscallStop::None,
        PTRACE_SYSCALL_INFO_ENTRY => SyscallStop::Entry {
            number: raw.first,
            args: raw.args,
        },
        PTRACE_SYSCALL_INFO_EXIT => SyscallStop::Exit {
            value: raw.first as i64,
            // One byte, the first of the member on a little-endian
            // machine.
            is_error: raw.args[0] as u8 != 0,
        },
        PTRACE_SYSCALL_INFO_SECCOMP => SyscallStop::Seccomp {
            number: raw.first,
            args: raw.args,
            data: raw.ret_data,
        },
        _ => return Err(ErrorKind::Other.into()),
    };
    Ok(SyscallInfo {
        arch: raw.arch,
        instruction_pointer: raw.instruction_pointer,
        stack_pointer: raw.stack_pointer,
        stop,
    })
}

/// What the status of a traced thread that stopped says.
pub(crate) const fn stop_from(status: i32) -> Stop {
    let signal = status & 0x7f;
    match status >> 8 {
        0 if status == SIGTRAP | 0x80 => Stop::Syscall,
        0 => Stop::Signal(status),
        1 if signal == SIGTRAP => Stop::Fork,
        2 if signal == SIGTRAP => Stop::Vfork,
        3 if signal == SIGTRAP => Stop::Clone,
        4 if signal == SIGTRAP => Stop::Exec,
        5 if signal == SIGTRAP => Stop::VforkDone,
        6 if signal == SIGTRAP => Stop::Exit,
        7 if signal == SIGTRAP => Stop::Seccomp,
        128 if signal == SIGTRAP => Stop::Interrupted,
        128 => Stop::GroupStop(signal),
        _ => Stop::Unknown(status),
    }
}

pub(crate) fn wait(who: WaitFor<'_>, flags: WaitFlags) -> Result<Option<Waited>> {
    let (kind, id) = match who {
        WaitFor::Any => (P_ALL, 0),
        WaitFor::Process(pid) => (P_PID, checked_pid(pid)? as usize),
        WaitFor::Group(group) => {
            if group > i32::MAX as u32 {
                return Err(ErrorKind::InvalidInput.into());
            }
            (P_PGID, group as usize)
        }
        WaitFor::PidFd(pidfd) => (P_PIDFD, pidfd.as_raw() as usize),
    };
    let table = [
        (WaitFlags::EXITED, WEXITED),
        (WaitFlags::STOPPED, WSTOPPED),
        (WaitFlags::CONTINUED, WCONTINUED),
        (WaitFlags::NO_HANG, WNOHANG),
        (WaitFlags::NO_WAIT, WNOWAIT),
        (WaitFlags::ALL_CHILDREN, WALL),
        (WaitFlags::NO_THREAD, WNOTHREAD),
    ];
    let mut options = 0;
    for (flag, value) in table {
        if flags.contains(flag) {
            options |= value;
        }
    }
    let mut info = RawSigInfo([0; 32]);
    // SAFETY: `info` is a writable `siginfo_t`, and no `struct rusage` is
    // asked for.
    unsafe { syscall!(WAITID, kind, id, &raw mut info, options, 0usize) }?;
    let info = info.0;
    // With WNOHANG and nothing to report, nothing is written.
    if info[SI_FIELDS] == 0 {
        return Ok(None);
    }
    let status = info[SI_FIELDS + 2];
    let event = match info[2] {
        CLD_EXITED => WaitEvent::Exited(status),
        CLD_KILLED => WaitEvent::Killed {
            signal: status,
            core_dumped: false,
        },
        CLD_DUMPED => WaitEvent::Killed {
            signal: status,
            core_dumped: true,
        },
        CLD_TRAPPED => WaitEvent::Trapped(stop_from(status)),
        CLD_STOPPED => WaitEvent::Stopped(status),
        CLD_CONTINUED => WaitEvent::Continued,
        _ => return Err(ErrorKind::Other.into()),
    };
    Ok(Some(Waited {
        pid: info[SI_FIELDS] as u32,
        uid: info[SI_FIELDS + 1] as u32,
        event,
    }))
}

/// `process_vm_readv` or `process_vm_writev`, on arrays of `struct
/// iovec`.
///
/// # Safety
///
/// `local` must point to `local_count` structures that name memory of
/// the caller valid for the direction of the call, and `remote` to
/// `remote_count` structures.
pub(crate) unsafe fn process_vm(
    write: bool,
    pid: u32,
    local: *const u8,
    local_count: usize,
    remote: *const u8,
    remote_count: usize,
) -> Result<usize> {
    let pid = checked_pid(pid)?;
    // SAFETY: the caller's contract; the kernel checks the addresses of
    // the other process itself.
    unsafe {
        if write {
            syscall!(
                PROCESS_VM_WRITEV,
                pid,
                local,
                local_count,
                remote,
                remote_count,
                0usize
            )
        } else {
            syscall!(
                PROCESS_VM_READV,
                pid,
                local,
                local_count,
                remote,
                remote_count,
                0usize
            )
        }
    }
}

pub(crate) fn pidfd_getfd(pidfd: BorrowedHandle<'_>, fd: u32) -> Result<OwnedHandle> {
    // SAFETY: no memory is involved.
    let fd = unsafe { syscall!(PIDFD_GETFD, pidfd.as_raw(), fd, 0usize) }?;
    // SAFETY: the descriptor was just created (close-on-exec, as the
    // call always makes it).
    Ok(unsafe { OwnedHandle::from_raw(fd as i32) })
}