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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! What is mapped in the calling process: `/proc/self/maps`, read without
//! allocating, the `ioctl` that asks it about one address, and `mincore`.

use crate::mem::{Protection, Sharing, check_range, page_size};
use crate::sys::mem::maps;
use crate::{AsHandle, ErrorKind, OwnedHandle, Result, io};

/// What the kernel knows of a mapping of the calling process: a line of
/// `/proc/self/maps`. See [`Regions`] and [`query`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Region<'a> {
    /// The address of the first page of the region.
    pub base: *mut u8,
    /// Its length in bytes.
    pub len: usize,
    /// How its pages may be accessed now.
    pub protection: Protection,
    /// Whether what is written to it is written to what it maps
    /// ([`Sharing::Shared`]), or kept by the process
    /// ([`Sharing::Private`], which is also what anonymous memory that is
    /// not shared says).
    pub sharing: Sharing,
    /// Where in the file the region starts, for a mapping of a file; for
    /// anonymous memory, a number of no use.
    pub offset: u64,
    /// The device the file is on, major and minor; zeroes for anonymous
    /// memory.
    pub device: (u32, u32),
    /// The inode number of the file; 0 for anonymous memory.
    pub inode: u64,
    /// The path of the file, as the kernel has it now: followed by
    /// ` (deleted)` for a file that was removed, and empty for anonymous
    /// memory, save for the names the kernel gives some of it (`[heap]`,
    /// `[stack]`, `[vdso]`, `[anon:...]`).
    pub path: &'a [u8],
}

/// The size of the buffer the file is read through: a line holds a path
/// of at most 4096 bytes and about a hundred before it.
const BUFFER: usize = 4608;

/// The mappings of the calling process, from the lowest address to the
/// highest: `/proc/self/maps`, read a buffer at a time and parsed as it
/// comes. Nothing is allocated: the structure holds the file and 4.5 KB.
///
/// This is not an [`Iterator`]: a [`Region`] borrows its path from the
/// buffer, until the next one is read.
///
/// ```
/// # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
/// use oscall::mem::linux::Regions;
///
/// let mut mapped = 0;
/// let mut regions = Regions::open()?;
/// while let Some(region) = regions.next()? {
///     mapped += region.len;
/// }
/// assert!(mapped > 0);
/// # }
/// # Ok::<(), oscall::Error>(())
/// ```
///
/// **The list is not a snapshot.** The kernel writes whole lines, each
/// true when it was written, and goes on from the address it had
/// reached: mappings made or removed meanwhile, by this thread (reading
/// the list maps nothing) or by another, may show or not, but no address
/// shows twice.
///
/// A path longer than the buffer is cut. In a path, the kernel writes a
/// line feed as `\012`, which is read back as a line feed here; a path
/// that holds those four characters cannot be told from it.
pub struct Regions {
    file: OwnedHandle,
    buf: [u8; BUFFER],
    /// What of `buf` is read and not yet parsed.
    start: usize,
    end: usize,
    eof: bool,
    /// Whether what comes up to the next line feed is the rest of a line
    /// that was cut.
    skip: bool,
}

impl core::fmt::Debug for Regions {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Regions")
            .field("file", &self.file)
            .finish_non_exhaustive()
    }
}

impl Regions {
    /// Opens the list of the mappings of the calling process.
    ///
    /// # Errors
    ///
    /// [`NotFound`](ErrorKind::NotFound) where `/proc` is not mounted;
    /// [`PermissionDenied`](ErrorKind::PermissionDenied) for a process
    /// that is not dumpable
    /// ([`set_dumpable`](crate::process::linux::set_dumpable)) and not
    /// root.
    pub fn open() -> Result<Self> {
        Ok(Self::from_file(maps::open()?))
    }

    fn from_file(file: OwnedHandle) -> Self {
        Self {
            file,
            buf: [0; BUFFER],
            start: 0,
            end: 0,
            eof: false,
            skip: false,
        }
    }

    /// The next mapping, or `None` after the last.
    ///
    /// # Errors
    ///
    /// Those of reading the file ([`Interrupted`](ErrorKind::Interrupted)
    /// among them), and [`Other`](ErrorKind::Other) for a line that is
    /// not what the kernel is known to write.
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Result<Option<Region<'_>>> {
        let (from, to) = loop {
            let unread = &self.buf[self.start..self.end];
            if let Some(at) = unread.iter().position(|&byte| byte == b'\n') {
                let line = (self.start, self.start + at);
                self.start = line.1 + 1;
                if self.skip {
                    self.skip = false;
                    continue;
                }
                break line;
            }
            if self.eof {
                // The kernel ends every line; what is left is nothing.
                return Ok(None);
            }
            if self.start == 0 && self.end == BUFFER {
                // A line longer than the buffer: what there is of it is
                // the line, and the rest is passed over.
                self.start = BUFFER;
                if self.skip {
                    continue;
                }
                self.skip = true;
                break (0, BUFFER);
            }
            self.buf.copy_within(self.start..self.end, 0);
            self.end -= self.start;
            self.start = 0;
            match io::read(&self.file, &mut self.buf[self.end..])? {
                0 => self.eof = true,
                read => self.end += read,
            }
        };
        parse(&mut self.buf[from..to]).map(Some)
    }
}

/// The number at `*at` of `line`, in base `radix`, up to `end`, which is
/// passed over; at the end of the line for want of one.
fn number(line: &[u8], at: &mut usize, radix: u32, end: u8) -> Result<u64> {
    let mut value: u64 = 0;
    let mut digits = 0;
    while let Some(&byte) = line.get(*at) {
        *at += 1;
        if byte == end {
            break;
        }
        let digit = (byte as char).to_digit(radix).ok_or(ErrorKind::Other)?;
        value = value
            .checked_mul(u64::from(radix))
            .and_then(|value| value.checked_add(u64::from(digit)))
            .ok_or(ErrorKind::Other)?;
        digits += 1;
    }
    if digits == 0 {
        return Err(ErrorKind::Other.into());
    }
    Ok(value)
}

/// Puts back the line feeds the kernel wrote as `\012`, and returns the
/// new length.
fn unescape(path: &mut [u8]) -> usize {
    let (mut read, mut write) = (0, 0);
    while read < path.len() {
        if path[read..].starts_with(b"\\012") {
            path[write] = b'\n';
            read += 4;
        } else {
            path[write] = path[read];
            read += 1;
        }
        write += 1;
    }
    write
}

/// A line of the file: `start-end rwxp offset major:minor inode  path`.
fn parse(line: &mut [u8]) -> Result<Region<'_>> {
    let mut at = 0;
    let start = number(line, &mut at, 16, b'-')?;
    let end = number(line, &mut at, 16, b' ')?;
    let flags = line.get(at..at + 5).ok_or(ErrorKind::Other)?;
    let mut protection = Protection::empty();
    for (flag, letter, bit) in [
        (flags[0], b'r', Protection::READ),
        (flags[1], b'w', Protection::WRITE),
        (flags[2], b'x', Protection::EXECUTE),
    ] {
        if flag == letter {
            protection |= bit;
        }
    }
    let sharing = if flags[3] == b's' {
        Sharing::Shared
    } else {
        Sharing::Private
    };
    at += 5;
    let offset = number(line, &mut at, 16, b' ')?;
    let major = number(line, &mut at, 16, b':')?;
    let minor = number(line, &mut at, 16, b' ')?;
    let inode = number(line, &mut at, 10, b' ')?;
    while line.get(at) == Some(&b' ') {
        at += 1;
    }
    let start = usize::try_from(start).map_err(|_| ErrorKind::Other)?;
    let end = usize::try_from(end).map_err(|_| ErrorKind::Other)?;
    let path = line.get_mut(at..).unwrap_or_default();
    let len = unescape(path);
    Ok(Region {
        base: core::ptr::without_provenance_mut(start),
        len: end.checked_sub(start).ok_or(ErrorKind::Other)?,
        protection,
        sharing,
        offset,
        device: (major as u32, minor as u32),
        inode,
        path: &path[..len],
    })
}

/// Returns the mapping of the calling process that holds the address
/// `ptr`, or `None` when nothing is mapped there.
///
/// `path` is where the path of the mapping is written, with a byte to
/// spare; given an empty buffer, the path is not asked for and
/// [`Region::path`] is empty.
///
/// Linux has no system call for this. Since Linux 6.11 the file
/// `/proc/self/maps` answers the question by an `ioctl`
/// (`PROCMAP_QUERY`): the file is opened, asked, and closed. Before, and
/// under an emulator, the file is read until the address is passed, as
/// [`Regions`] reads it: the cost then grows with the number of mappings
/// of the process, which may be thousands. Both need `/proc`.
///
/// A region is what the kernel keeps as one mapping: it may be part of a
/// mapping of this module (after [`protect`](crate::mem::protect)ing
/// some of its pages), or several of them that the kernel merged. A
/// reservation is a region with no access. What is true when the function returns may no
/// longer be when the answer is used, if other threads map memory.
///
/// # Errors
///
/// [`BufferTooSmall`](ErrorKind::BufferTooSmall) for a path that does not
/// fit in `path`; those of [`Regions::open`].
pub fn query<'a>(ptr: *const u8, path: &'a mut [u8]) -> Result<Option<Region<'a>>> {
    let file = maps::open()?;
    let address = ptr.addr();
    match maps::query(file.as_handle(), address, path)? {
        Some(answer) => from_ioctl(answer, path),
        None => query_text(file, address, path),
    }
}

/// The region `PROCMAP_QUERY` described, with its name in `path`.
fn from_ioctl(answer: Option<maps::ProcmapQuery>, path: &mut [u8]) -> Result<Option<Region<'_>>> {
    let Some(found) = answer else {
        return Ok(None);
    };
    {
        let mut protection = Protection::empty();
        for (flag, bit) in [
            (maps::PROCMAP_QUERY_VMA_READABLE, Protection::READ),
            (maps::PROCMAP_QUERY_VMA_WRITABLE, Protection::WRITE),
            (maps::PROCMAP_QUERY_VMA_EXECUTABLE, Protection::EXECUTE),
        ] {
            if found.vma_flags & flag != 0 {
                protection |= bit;
            }
        }
        let start = usize::try_from(found.vma_start).map_err(|_| ErrorKind::Other)?;
        let end = usize::try_from(found.vma_end).map_err(|_| ErrorKind::Other)?;
        // The size counts the byte that ends the name.
        let name = (found.vma_name_size as usize)
            .saturating_sub(1)
            .min(path.len());
        Ok(Some(Region {
            base: core::ptr::without_provenance_mut(start),
            len: end.checked_sub(start).ok_or(ErrorKind::Other)?,
            protection,
            sharing: if found.vma_flags & maps::PROCMAP_QUERY_VMA_SHARED != 0 {
                Sharing::Shared
            } else {
                Sharing::Private
            },
            offset: found.vma_offset,
            device: (found.dev_major, found.dev_minor),
            inode: found.inode,
            path: &path[..name],
        }))
    }
}

/// The region that holds `address`, from the text of the file, with its
/// path copied to `path`.
fn query_text(file: OwnedHandle, address: usize, path: &mut [u8]) -> Result<Option<Region<'_>>> {
    let mut regions = Regions::from_file(file);
    while let Some(region) = regions.next()? {
        let base = region.base.addr();
        // In ascending order: past the address, nothing holds it.
        if address < base {
            break;
        }
        if address - base >= region.len {
            continue;
        }
        let name = if path.is_empty() {
            0
        } else if region.path.len() < path.len() {
            path[..region.path.len()].copy_from_slice(region.path);
            region.path.len()
        } else {
            return Err(ErrorKind::BufferTooSmall.into());
        };
        return Ok(Some(Region {
            base: region.base,
            len: region.len,
            protection: region.protection,
            sharing: region.sharing,
            offset: region.offset,
            device: region.device,
            inode: region.inode,
            path: &path[..name],
        }));
    }
    Ok(None)
}

/// Says which pages of a range are in physical memory: `mincore`. Each
/// page of the range gets a byte of `pages`, in order: 1 when an access
/// to it would not have to wait for the page to be brought in, 0
/// otherwise. Returns the number of pages, which is how many bytes were
/// written.
///
/// The answer is about the moment of the call: the kernel may let go of
/// a page, or bring one in, at once. For the pages of a file, "in memory"
/// means in the cache of the system, whoever put it there; since Linux
/// 5.14 that is only said to a caller that could write the file, and the
/// others are told every such page is there.
///
/// The range follows the rules of the [module](crate::mem#ranges).
///
/// # Errors
///
/// [`BufferTooSmall`](ErrorKind::BufferTooSmall) if `pages` has fewer
/// bytes than the range has pages;
/// [`OutOfMemory`](ErrorKind::OutOfMemory) (`ENOMEM`) for a range that
/// is not all mapped.
pub fn resident_pages(ptr: *const u8, len: usize, pages: &mut [u8]) -> Result<usize> {
    check_range(ptr, len)?;
    let count = len.div_ceil(page_size());
    let pages = pages.get_mut(..count).ok_or(ErrorKind::BufferTooSmall)?;
    maps::mincore(ptr, len, pages)?;
    // The other bits of each byte are the kernel's to define.
    for page in pages.iter_mut() {
        *page &= 1;
    }
    Ok(count)
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use std::format;
    use std::vec::Vec;

    use super::*;

    fn line(text: &str) -> Vec<u8> {
        text.as_bytes().to_vec()
    }

    #[test]
    fn lines() {
        let mut text = line("7f1c2000-7f1e3000 r-xp 0001f000 fd:01 1234567   /usr/lib/x y");
        let region = parse(&mut text).unwrap();
        assert_eq!(region.base.addr(), 0x7f1c_2000);
        assert_eq!(region.len, 0x21000);
        assert_eq!(region.protection, Protection::READ | Protection::EXECUTE);
        assert_eq!(region.sharing, Sharing::Private);
        assert_eq!(region.offset, 0x1f000);
        assert_eq!(region.device, (0xfd, 1));
        assert_eq!(region.inode, 1_234_567);
        assert_eq!(region.path, b"/usr/lib/x y");

        // Anonymous memory: nothing after the inode, not even a space.
        let mut text = line("1000-3000 rw-s 00000000 00:00 0");
        let region = parse(&mut text).unwrap();
        assert_eq!((region.base.addr(), region.len), (0x1000, 0x2000));
        assert_eq!(region.protection, Protection::READ | Protection::WRITE);
        assert_eq!(region.sharing, Sharing::Shared);
        assert_eq!((region.device, region.inode), ((0, 0), 0));
        assert!(region.path.is_empty());

        let mut text = line("1000-2000 ---p 00000000 00:00 0                  [heap]");
        let region = parse(&mut text).unwrap();
        assert_eq!(region.protection, Protection::empty());
        assert_eq!(region.path, b"[heap]");

        // A line feed in a name, and a name that was removed.
        let mut text = line("1000-2000 r--p 00000000 08:02 7 /a\\012b\\012 (deleted)");
        assert_eq!(parse(&mut text).unwrap().path, b"/a\nb\n (deleted)");

        for bad in [
            "",
            "1000",
            "1000-2000",
            "1000-2000 r--p",
            "zz-2000 r--p 0 0:0 0",
            "2000-1000 r--p 0 0:0 0",
            "1000-2000 r--p 0 00 0",
            "1000-2000 r--p 0 0:0 x",
            "11111111111111111-2000 r--p 0 0:0 0",
        ] {
            let mut text = line(bad);
            let error = parse(&mut text).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::Other, "{bad:?}");
        }
    }

    /// The reader, on a pipe that gives the text a few bytes at a time,
    /// with a line longer than the buffer in the middle.
    #[test]
    fn reader() {
        let long = "x".repeat(2 * BUFFER);
        let text = format!(
            "1000-2000 r--p 00000000 00:00 0\n\
             2000-3000 rw-p 00000000 08:01 5 /{long}\n\
             3000-4000 r-xp 00001000 08:01 6 /bin/last\n"
        );
        let (read, write) = io::pipe().unwrap();
        let writer = std::thread::spawn(move || {
            for chunk in text.as_bytes().chunks(1000) {
                let mut rest = chunk;
                while !rest.is_empty() {
                    let written = io::write(&write, rest).unwrap();
                    rest = &rest[written..];
                }
            }
        });
        let mut regions = Regions::from_file(read);
        let first = regions.next().unwrap().unwrap();
        assert_eq!((first.base.addr(), first.len), (0x1000, 0x1000));
        assert!(first.path.is_empty());
        let second = regions.next().unwrap().unwrap();
        assert_eq!((second.base.addr(), second.inode), (0x2000, 5));
        // Cut, and nothing of it taken for another line.
        assert!(second.path.len() > BUFFER - 100 && second.path.len() < BUFFER);
        assert!(second.path.starts_with(b"/xxx"));
        let third = regions.next().unwrap().unwrap();
        assert_eq!((third.base.addr(), third.offset), (0x3000, 0x1000));
        assert_eq!(third.path, b"/bin/last");
        assert!(regions.next().unwrap().is_none());
        assert!(regions.next().unwrap().is_none());
        writer.join().unwrap();
    }

    /// The two ways to ask about an address say the same, where the
    /// kernel has both.
    #[test]
    fn both_ways() {
        use crate::mem::Mapping;

        let here = both_ways as fn() as *const u8;
        // A page nothing can be merged with: its neighbours are this
        // mapping's, and are not like it.
        let page = page_size();
        let all = Protection::READ | Protection::WRITE;
        let map = Mapping::anonymous(3 * page, all).unwrap();
        let middle = map.as_ptr().wrapping_add(page);
        // SAFETY: a page of this mapping, which nothing uses.
        unsafe { crate::mem::protect(middle, page, Protection::READ) }.unwrap();
        let mut by_ioctl = [0u8; 4200];
        let mut by_text = [0u8; 4200];
        for address in [here.addr(), middle.addr(), 0] {
            let file = maps::open().unwrap();
            let text = query_text(file, address, &mut by_text).unwrap();
            assert_eq!(text.is_some(), address != 0);
            if address == middle.addr() {
                let region = text.unwrap();
                assert_eq!((region.base.addr(), region.len), (address, page));
                assert_eq!(region.protection, Protection::READ);
            }
            let file = maps::open().unwrap();
            let Some(answer) = maps::query(file.as_handle(), address, &mut by_ioctl).unwrap()
            else {
                // A kernel before 6.11, or an emulator: one way only.
                continue;
            };
            assert_eq!(from_ioctl(answer, &mut by_ioctl).unwrap(), text);
        }
    }
}