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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! The vDSO: the small shared object the kernel maps into every process,
//! whose functions answer some system calls without entering the kernel.
//! oscall uses it for one thing, reading clocks.
//!
//! With no libc there is no dynamic linker to ask, so the image is found and
//! read here:
//!
//! 1. Its address is the `AT_SYSINFO_EHDR` entry of the auxiliary vector
//!    ([`auxv`](super::auxv)).
//! 2. Before any of it is read, the kernel is asked to read it (by writing
//!    it to a pipe, which fails with `EFAULT` instead of faulting): the
//!    first page, then the whole extent its program headers give. From then
//!    on the image is a byte slice.
//! 3. [`elf`] finds the function in that slice, in safe code: every offset
//!    is checked against the slice, so a malformed image is a symbol that
//!    is not found, not a crash.
//!
//! Whatever fails, the answer is "no fast path", and the caller makes the
//! system call. The answer is kept: the lookup runs once per process.
//!
//! Symbol names and versions are those of the kernel's linker scripts
//! (`arch/*/kernel/vdso/vdso.lds.S`, `arch/x86/entry/vdso/vdso.lds.S` and
//! `vdso32/vdso32.lds.S`, `arch/arm/vdso/vdso.lds.S`):
//!
//! | | function | version |
//! |---|---|---|
//! | x86_64 | `__vdso_clock_gettime` | `LINUX_2.6` |
//! | x86 | `__vdso_clock_gettime64` | `LINUX_2.6` |
//! | arm | `__vdso_clock_gettime64` | `LINUX_2.6` |
//! | aarch64 | `__kernel_clock_gettime` | `LINUX_2.6.39` |
//! | riscv64 | `__vdso_clock_gettime` | `LINUX_4.15` |
//!
//! riscv32 has no clock in its vDSO (`GENERIC_GETTIMEOFDAY` is selected for
//! 64-bit RISC-V only): it always makes the system call.
//!
//! Each of these takes a `clockid_t` and a pointer to a `struct
//! __kernel_timespec` (two 64-bit fields, also the layout of `timespec` on
//! 64-bit architectures), with the C calling convention of the architecture,
//! and returns zero or a negated error number. They use no thread-local
//! storage and no register the C convention does not give them: the 32-bit
//! x86 one is built with `-mregparm=0` and reaches the kernel, when it has
//! to, through the vDSO's own `__kernel_vsyscall`, not through `%gs`.

use core::sync::atomic::{AtomicUsize, Ordering};

use super::auxv;
use super::time::Timespec;
use crate::sys::syscall;

/// `clock_gettime` as the vDSO exports it.
pub(crate) type ClockGettime = unsafe extern "C" fn(clock: i32, ts: *mut Timespec) -> i32;

/// The name and the version of the function that reads a clock into a
/// 64-bit `timespec`, where the architecture has one.
#[cfg(target_arch = "x86_64")]
const CLOCK_GETTIME: Option<(&[u8], &[u8])> = Some((b"__vdso_clock_gettime", b"LINUX_2.6"));
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
const CLOCK_GETTIME: Option<(&[u8], &[u8])> = Some((b"__vdso_clock_gettime64", b"LINUX_2.6"));
#[cfg(target_arch = "aarch64")]
const CLOCK_GETTIME: Option<(&[u8], &[u8])> = Some((b"__kernel_clock_gettime", b"LINUX_2.6.39"));
#[cfg(target_arch = "riscv64")]
const CLOCK_GETTIME: Option<(&[u8], &[u8])> = Some((b"__vdso_clock_gettime", b"LINUX_4.15"));
#[cfg(target_arch = "riscv32")]
const CLOCK_GETTIME: Option<(&[u8], &[u8])> = None;

/// The states of [`CLOCK_GETTIME_FN`] that are not an address. Neither can
/// be one: the first page is never mapped.
const UNRESOLVED: usize = 0;
const ABSENT: usize = 1;

/// The address of the vDSO's `clock_gettime`, once looked up. It cannot
/// change while the process runs.
static CLOCK_GETTIME_FN: AtomicUsize = AtomicUsize::new(UNRESOLVED);

/// The vDSO's `clock_gettime`, if there is one. The first call looks it up.
#[inline]
pub(crate) fn clock_gettime() -> Option<ClockGettime> {
    // Relaxed: the value says everything, and what it points to was mapped
    // before the process started.
    let addr = match CLOCK_GETTIME_FN.load(Ordering::Relaxed) {
        UNRESOLVED => resolve(),
        addr => addr,
    };
    if addr == ABSENT {
        return None;
    }
    // SAFETY: an address stored in `CLOCK_GETTIME_FN` is that of a function
    // symbol of the vDSO, inside one of its executable segments, and the
    // name and version asked for are those of a function with this
    // signature.
    Some(unsafe {
        core::mem::transmute::<*const (), ClockGettime>(core::ptr::with_exposed_provenance(addr))
    })
}

#[cold]
fn resolve() -> usize {
    // Racing threads find the same value.
    let addr = locate().unwrap_or(ABSENT);
    CLOCK_GETTIME_FN.store(addr, Ordering::Relaxed);
    addr
}

fn locate() -> Option<usize> {
    let (name, version) = CLOCK_GETTIME?;
    let image = image()?;
    let offset = elf::find(image, name, version)?;
    // Inside the image, so neither a state nor an overflow.
    Some(image.as_ptr().addr() + offset)
}

/// No vDSO is anywhere near this large (they are a page or two): a header
/// that says otherwise is not believed.
const MAX_IMAGE: usize = 1 << 24;

/// The first bytes of the image, enough for its headers: every mapping has
/// at least the smallest page.
const HEAD: usize = 4096;

/// The vDSO of this process, as bytes: from its ELF header to the end of
/// its last loaded segment.
fn image() -> Option<&'static [u8]> {
    let base = auxv::get(auxv::AT_SYSINFO_EHDR)?;
    if base == 0 || !base.is_multiple_of(HEAD) {
        return None;
    }
    let probe = Probe::new()?;
    if !probe.readable(base, HEAD) {
        return None;
    }
    let base_ptr = core::ptr::with_exposed_provenance::<u8>(base);
    // SAFETY: the kernel just read these bytes, so they are mapped and
    // readable. They are not written while this process runs: the address
    // comes from the kernel as that of the vDSO, which is mapped read-only
    // and stays where it is unless the program itself unmaps or replaces
    // it, which no safe code can do.
    let head = unsafe { core::slice::from_raw_parts(base_ptr, HEAD) };
    let len = elf::layout(head)?.len;
    if len > MAX_IMAGE || base.checked_add(len).is_none() || !probe.readable(base, len) {
        return None;
    }
    // SAFETY: as above, for the whole extent.
    Some(unsafe { core::slice::from_raw_parts(base_ptr, len) })
}

/// A pipe to ask the kernel whether memory can be read: writing a range to
/// it copies the bytes if they are readable, and fails with `EFAULT` if
/// they are not, where reading them directly would kill the process.
struct Probe {
    read: i32,
    write: i32,
}

/// The same on every architecture oscall supports.
const O_CLOEXEC: usize = 0o2000000;
const O_NONBLOCK: usize = 0o4000;

impl Probe {
    fn new() -> Option<Self> {
        let mut fds = [0i32; 2];
        // SAFETY: the kernel writes two descriptors to `fds`.
        unsafe { syscall!(PIPE2, fds.as_mut_ptr(), O_CLOEXEC | O_NONBLOCK) }.ok()?;
        Some(Self {
            read: fds[0],
            write: fds[1],
        })
    }

    /// Whether every byte of `addr..addr + len` is mapped and readable.
    /// The range must not wrap.
    fn readable(&self, addr: usize, len: usize) -> bool {
        // No more than the pipe takes at once, whatever the page size.
        let mut sink = [0u8; 4096];
        let mut done = 0;
        while done < len {
            let n = (len - done).min(sink.len());
            // SAFETY: the kernel reads `n` bytes at an address that may not
            // be mapped, which it reports as an error; nothing in this
            // process reads them. The pipe is empty, so `n` bytes fit and
            // the call does not block.
            let written = unsafe { syscall!(WRITE, self.write, addr + done, n) };
            if written != Ok(n) {
                return false;
            }
            // Empty the pipe for the next round.
            // SAFETY: the kernel writes at most `n` bytes to `sink`.
            let read = unsafe { syscall!(READ, self.read, sink.as_mut_ptr(), n) };
            if read != Ok(n) {
                return false;
            }
            done += n;
        }
        true
    }
}

impl Drop for Probe {
    fn drop(&mut self) {
        // SAFETY: both descriptors were made by `new` and nothing else has
        // them.
        unsafe {
            crate::sys::close(self.read);
            crate::sys::close(self.write);
        }
    }
}

/// Just enough of ELF to find a function in a loaded shared object: program
/// headers, the dynamic section, the symbol table with either hash table,
/// and symbol versions. All of it is safe code over a byte slice.
///
/// The image is in memory as the kernel mapped it: the byte at virtual
/// address `v` is at index `v - layout.min_vaddr`. The vDSO is never
/// relocated, so the addresses in its dynamic section are virtual addresses
/// too.
mod elf {
    /// `e_machine` of the target architecture.
    #[cfg(target_arch = "x86")]
    const MACHINE: u16 = 3; // EM_386
    #[cfg(target_arch = "arm")]
    const MACHINE: u16 = 40; // EM_ARM
    #[cfg(target_arch = "x86_64")]
    const MACHINE: u16 = 62; // EM_X86_64
    #[cfg(target_arch = "aarch64")]
    const MACHINE: u16 = 183; // EM_AARCH64
    #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
    const MACHINE: u16 = 243; // EM_RISCV

    /// The offsets of the fields used, in the ELF class of the target:
    /// `Elf64_Ehdr`, `Elf64_Phdr`, `Elf64_Dyn` and `Elf64_Sym`.
    #[cfg(target_pointer_width = "64")]
    mod class {
        pub(super) const CLASS: u8 = 2; // ELFCLASS64
        pub(super) const WORD: usize = 8;
        pub(super) const E_PHOFF: usize = 32;
        pub(super) const E_PHENTSIZE: usize = 54;
        pub(super) const E_PHNUM: usize = 56;
        pub(super) const PHDR_SIZE: usize = 56;
        pub(super) const P_FLAGS: usize = 4;
        pub(super) const P_OFFSET: usize = 8;
        pub(super) const P_VADDR: usize = 16;
        pub(super) const P_MEMSZ: usize = 40;
        pub(super) const SYM_SIZE: usize = 24;
        pub(super) const ST_INFO: usize = 4;
        pub(super) const ST_SHNDX: usize = 6;
        pub(super) const ST_VALUE: usize = 8;
    }

    /// `Elf32_Ehdr`, `Elf32_Phdr`, `Elf32_Dyn` and `Elf32_Sym`.
    #[cfg(target_pointer_width = "32")]
    mod class {
        pub(super) const CLASS: u8 = 1; // ELFCLASS32
        pub(super) const WORD: usize = 4;
        pub(super) const E_PHOFF: usize = 28;
        pub(super) const E_PHENTSIZE: usize = 42;
        pub(super) const E_PHNUM: usize = 44;
        pub(super) const PHDR_SIZE: usize = 32;
        pub(super) const P_FLAGS: usize = 24;
        pub(super) const P_OFFSET: usize = 4;
        pub(super) const P_VADDR: usize = 8;
        pub(super) const P_MEMSZ: usize = 20;
        pub(super) const SYM_SIZE: usize = 16;
        pub(super) const ST_INFO: usize = 12;
        pub(super) const ST_SHNDX: usize = 14;
        pub(super) const ST_VALUE: usize = 4;
    }

    use class::*;

    // The same in both classes.
    const E_MACHINE: usize = 18;
    const P_TYPE: usize = 0;
    const ST_NAME: usize = 0;
    /// `Elf_Dyn`: a tag and a value, one word each.
    const DYN_SIZE: usize = 2 * WORD;
    /// `Elf_Verdef`, the same in both classes.
    const VD_FLAGS: usize = 2;
    const VD_NDX: usize = 4;
    const VD_AUX: usize = 12;
    const VD_NEXT: usize = 16;

    const PT_LOAD: u32 = 1;
    const PT_DYNAMIC: u32 = 2;
    const PF_X: u32 = 1;

    const DT_NULL: usize = 0;
    const DT_HASH: usize = 4;
    const DT_STRTAB: usize = 5;
    const DT_SYMTAB: usize = 6;
    const DT_STRSZ: usize = 10;
    const DT_SYMENT: usize = 11;
    const DT_GNU_HASH: usize = 0x6fff_fef5;
    const DT_VERSYM: usize = 0x6fff_fff0;
    const DT_VERDEF: usize = 0x6fff_fffc;
    const DT_VERDEFNUM: usize = 0x6fff_fffd;

    const SHN_UNDEF: u16 = 0;
    const STT_FUNC: u8 = 2;
    const STB_GLOBAL: u8 = 1;
    const STB_WEAK: u8 = 2;
    /// The version definition of the object itself, not of a symbol.
    const VER_FLG_BASE: u16 = 1;
    /// The bit of a `versym` entry that hides the symbol.
    const VERSYM_HIDDEN: u16 = 0x8000;

    /// The most program headers and version definitions looked at: an image
    /// that claims more is not a vDSO.
    const MAX_PHDRS: usize = 64;
    const MAX_VERDEFS: usize = 64;

    /// On arm the low bit of a function's address says it is Thumb code: it
    /// is not part of where the function is, and must stay in the address
    /// that is called.
    #[cfg(target_arch = "arm")]
    const MODE_BITS: usize = 1;
    #[cfg(not(target_arch = "arm"))]
    const MODE_BITS: usize = 0;

    /// Bounds-checked, little-endian reads. oscall's Linux backend refuses
    /// to compile for big-endian targets.
    #[derive(Clone, Copy)]
    struct Bytes<'a>(&'a [u8]);

    impl<'a> Bytes<'a> {
        fn get<const N: usize>(self, offset: usize) -> Option<[u8; N]> {
            let bytes = self.0.get(offset..offset.checked_add(N)?)?;
            bytes.try_into().ok()
        }

        fn u8(self, offset: usize) -> Option<u8> {
            self.0.get(offset).copied()
        }

        fn u16(self, offset: usize) -> Option<u16> {
            self.get(offset).map(u16::from_le_bytes)
        }

        fn u32(self, offset: usize) -> Option<u32> {
            self.get(offset).map(u32::from_le_bytes)
        }

        /// An address, an offset or a size of the target's class.
        fn word(self, offset: usize) -> Option<usize> {
            self.get(offset).map(usize::from_le_bytes)
        }

        /// The entry `index` of a table of `size`-byte entries at `table`,
        /// as an offset.
        fn entry(table: usize, index: usize, size: usize) -> Option<usize> {
            table.checked_add(index.checked_mul(size)?)
        }

        /// Whether the NUL-terminated string at `offset` is `expected`.
        fn str_is(self, offset: usize, expected: &[u8]) -> bool {
            let Some(end) = offset.checked_add(expected.len()) else {
                return false;
            };
            self.0.get(offset..end) == Some(expected) && self.0.get(end) == Some(&0)
        }
    }

    /// Where the image is in the address space it was linked for.
    pub(super) struct Layout {
        /// The virtual address of the first byte of the image.
        min_vaddr: usize,
        /// From the first byte to the end of the last loaded segment.
        pub(super) len: usize,
        phoff: usize,
        phnum: usize,
    }

    impl Layout {
        /// The index in the image of the byte at virtual address `vaddr`.
        fn offset(&self, vaddr: usize) -> Option<usize> {
            vaddr.checked_sub(self.min_vaddr).filter(|o| *o < self.len)
        }

        /// The program headers: `(type, flags, offset, vaddr, memsz)`.
        fn segments<'a>(
            &self,
            image: Bytes<'a>,
        ) -> impl Iterator<Item = Option<(u32, u32, usize, usize, usize)>> + use<'a> {
            let phoff = self.phoff;
            (0..self.phnum).map(move |i| {
                let at = Bytes::entry(phoff, i, PHDR_SIZE)?;
                Some((
                    image.u32(at.checked_add(P_TYPE)?)?,
                    image.u32(at.checked_add(P_FLAGS)?)?,
                    image.word(at.checked_add(P_OFFSET)?)?,
                    image.word(at.checked_add(P_VADDR)?)?,
                    image.word(at.checked_add(P_MEMSZ)?)?,
                ))
            })
        }
    }

    /// Reads the ELF header and the program headers, which must be within
    /// `head`, the first bytes of the image.
    pub(super) fn layout(head: &[u8]) -> Option<Layout> {
        let image = Bytes(head);
        // Magic, class, and little-endian data.
        if image.get(0)? != [0x7f, b'E', b'L', b'F', CLASS, 1] || image.u16(E_MACHINE)? != MACHINE {
            return None;
        }
        let phnum = usize::from(image.u16(E_PHNUM)?);
        if usize::from(image.u16(E_PHENTSIZE)?) != PHDR_SIZE || phnum > MAX_PHDRS {
            return None;
        }
        let mut layout = Layout {
            min_vaddr: 0,
            len: 0,
            phoff: image.word(E_PHOFF)?,
            phnum,
        };
        // The lowest loaded segment, and the end of the highest.
        let mut first: Option<(usize, usize)> = None;
        let mut end = 0;
        for segment in layout.segments(image) {
            let (kind, _, offset, vaddr, memsz) = segment?;
            if kind != PT_LOAD {
                continue;
            }
            end = end.max(vaddr.checked_add(memsz)?);
            if first.is_none_or(|(lowest, _)| vaddr < lowest) {
                first = Some((vaddr, offset));
            }
        }
        // The image starts with the file's first byte, the ELF header: that
        // is what the address the kernel gives points to.
        let (min_vaddr, 0) = first? else {
            return None;
        };
        layout.min_vaddr = min_vaddr;
        layout.len = end.checked_sub(min_vaddr).filter(|len| *len > 0)?;
        Some(layout)
    }

    /// The function `name` with version `version` in `image`, as an offset
    /// from the start of the image (with the Thumb bit on arm, if the
    /// function has it). An image with no version information at all
    /// matches any version.
    ///
    /// `None` if there is no such function, or if the image is not a sound
    /// ELF object of the target architecture. The offset returned is inside
    /// an executable segment that lies within `image`.
    pub(super) fn find(image: &[u8], name: &[u8], version: &[u8]) -> Option<usize> {
        find_with(image, name, version, true)
    }

    /// [`find`], ignoring the System V hash table if `sysv_hash` is false:
    /// most images have both tables, and the tests want each one used.
    pub(super) fn find_with(
        image: &[u8],
        name: &[u8],
        version: &[u8],
        sysv_hash: bool,
    ) -> Option<usize> {
        let layout = layout(image)?;
        let image = Bytes(image.get(..layout.len)?);

        let mut dynamic = None;
        for segment in layout.segments(image) {
            let (kind, _, _, vaddr, memsz) = segment?;
            if kind == PT_DYNAMIC {
                dynamic = Some((layout.offset(vaddr)?, memsz));
                break;
            }
        }
        let (dynamic, dynamic_len) = dynamic?;

        let mut symtab = None;
        let mut strtab = None;
        let mut strsz = None;
        let mut hash = None;
        let mut gnu_hash = None;
        let mut versym = None;
        let mut verdef = None;
        let mut verdefnum = MAX_VERDEFS;
        for i in 0..dynamic_len / DYN_SIZE {
            let at = Bytes::entry(dynamic, i, DYN_SIZE)?;
            let value = image.word(at.checked_add(WORD)?)?;
            match image.word(at)? {
                DT_NULL => break,
                DT_SYMTAB => symtab = Some(layout.offset(value)?),
                DT_STRTAB => strtab = Some(layout.offset(value)?),
                DT_STRSZ => strsz = Some(value),
                DT_SYMENT if value != SYM_SIZE => return None,
                DT_HASH if sysv_hash => hash = Some(layout.offset(value)?),
                DT_GNU_HASH => gnu_hash = Some(layout.offset(value)?),
                DT_VERSYM => versym = Some(layout.offset(value)?),
                DT_VERDEF => verdef = Some(layout.offset(value)?),
                DT_VERDEFNUM => verdefnum = value.min(MAX_VERDEFS),
                _ => {}
            }
        }
        let symtab = symtab?;
        let strtab = strtab?;
        // The string table, on its own: a name cannot run past its end.
        let strings = match strsz {
            Some(size) => image.0.get(strtab..strtab.checked_add(size)?)?,
            None => image.0.get(strtab..)?,
        };
        let strings = Bytes(strings);

        // Neither hash table is used to look the name up: there are a dozen
        // symbols and one lookup per process. They say how many symbols
        // there are, which nothing else does.
        let count = match (hash, gnu_hash) {
            // `nchain`, the second word of the table.
            (Some(hash), _) => image.u32(hash.checked_add(4)?)? as usize,
            (None, Some(gnu_hash)) => gnu_symbol_count(image, gnu_hash)?,
            (None, None) => return None,
        };

        // The first symbol is the undefined one.
        for index in 1..count {
            let at = Bytes::entry(symtab, index, SYM_SIZE)?;
            let info = image.u8(at.checked_add(ST_INFO)?)?;
            if info & 0xf != STT_FUNC
                || !matches!(info >> 4, STB_GLOBAL | STB_WEAK)
                || image.u16(at.checked_add(ST_SHNDX)?)? == SHN_UNDEF
                || !strings.str_is(image.u32(at.checked_add(ST_NAME)?)? as usize, name)
            {
                continue;
            }
            if let (Some(versym), Some(verdef)) = (versym, verdef) {
                let wanted = image.u16(Bytes::entry(versym, index, 2)?)? & !VERSYM_HIDDEN;
                if !version_is(image, strings, verdef, verdefnum, wanted, version)? {
                    continue;
                }
            }
            let value = image.word(at.checked_add(ST_VALUE)?)?;
            let code = value & !MODE_BITS;
            // Only code is called: the address must be in a segment that is
            // loaded executable.
            for segment in layout.segments(image) {
                let (kind, flags, _, vaddr, memsz) = segment?;
                if kind == PT_LOAD
                    && flags & PF_X != 0
                    && code >= vaddr
                    && code - vaddr < memsz
                    && layout.offset(code).is_some()
                {
                    return value.checked_sub(layout.min_vaddr);
                }
            }
            return None;
        }
        None
    }

    /// The number of symbols, from a GNU hash table: it does not say, but
    /// it holds the index of every symbol it hashes, and those are the last
    /// ones of the symbol table.
    fn gnu_symbol_count(image: Bytes<'_>, table: usize) -> Option<usize> {
        // nbuckets, symoffset, bloom_size, bloom_shift; the bloom filter
        // (words); the buckets; the chains, one entry per hashed symbol.
        let nbuckets = image.u32(table)? as usize;
        let symoffset = image.u32(table.checked_add(4)?)? as usize;
        let bloom_size = image.u32(table.checked_add(8)?)? as usize;
        let buckets = Bytes::entry(table.checked_add(16)?, bloom_size, WORD)?;
        let chains = Bytes::entry(buckets, nbuckets, 4)?;
        // The highest symbol a bucket starts with: every read is checked, so
        // a table that lies about its size ends the loop where the image
        // ends.
        let mut last = 0;
        for bucket in 0..nbuckets {
            last = last.max(image.u32(Bytes::entry(buckets, bucket, 4)?)? as usize);
        }
        if last < symoffset {
            // Nothing is hashed.
            return Some(symoffset);
        }
        // Its chain runs to an entry with the low bit set.
        loop {
            let chain = image.u32(Bytes::entry(chains, last - symoffset, 4)?)?;
            last = last.checked_add(1)?;
            if chain & 1 != 0 {
                return Some(last);
            }
        }
    }

    /// Whether the version definition with index `wanted` is named
    /// `version`. `None` if the definitions are malformed.
    fn version_is(
        image: Bytes<'_>,
        strings: Bytes<'_>,
        verdef: usize,
        verdefnum: usize,
        wanted: u16,
        version: &[u8],
    ) -> Option<bool> {
        let mut at = verdef;
        for _ in 0..verdefnum {
            let flags = image.u16(at.checked_add(VD_FLAGS)?)?;
            let index = image.u16(at.checked_add(VD_NDX)?)? & !VERSYM_HIDDEN;
            if flags & VER_FLG_BASE == 0 && index == wanted {
                // The first auxiliary entry holds the name of the version
                // (`vda_name`, its first field).
                let aux = at.checked_add(image.u32(at.checked_add(VD_AUX)?)? as usize)?;
                return Some(strings.str_is(image.u32(aux)? as usize, version));
            }
            match image.u32(at.checked_add(VD_NEXT)?)? as usize {
                0 => break,
                next => at = at.checked_add(next)?,
            }
        }
        Some(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// What the tests know of this process's vDSO, for the log: whether the
    /// fast path exists depends on the kernel, and under qemu-user on the
    /// emulator.
    #[test]
    fn lookup() {
        let base = auxv::get(auxv::AT_SYSINFO_EHDR);
        let image = image();
        let found = clock_gettime();
        #[cfg(feature = "std")]
        std::eprintln!(
            "vdso: AT_SYSINFO_EHDR = {base:x?}, image of {:?} bytes, clock_gettime at {:?}",
            image.map(<[u8]>::len),
            found.map(|f| f as usize as *const ()),
        );
        // The answer does not change.
        assert_eq!(
            clock_gettime().map(|f| f as usize),
            found.map(|f| f as usize)
        );
        assert_eq!(locate(), found.map(|f| f as usize));
        if base.is_none() {
            assert!(image.is_none());
        }
        let Some(image) = image else {
            assert!(found.is_none());
            return;
        };
        assert_eq!(base, Some(image.as_ptr().addr()));
        if let Some(found) = found {
            let offset = (found as usize).wrapping_sub(image.as_ptr().addr());
            assert!(offset < image.len());
        }
        let Some((name, version)) = CLOCK_GETTIME else {
            assert!(found.is_none());
            return;
        };
        // Counting the symbols with the GNU hash table, for an image that
        // has one, finds the same function. (x86 and riscv images have both
        // tables, arm ones the System V table only.)
        let with_gnu_hash = elf::find_with(image, name, version, false);
        #[cfg(feature = "std")]
        std::eprintln!("vdso: with the GNU hash table alone: {with_gnu_hash:?}");
        if with_gnu_hash.is_some() {
            assert_eq!(with_gnu_hash, elf::find(image, name, version));
        }
        // Another name is not found, and neither is another version when
        // the image has versions, which every kernel's does.
        assert_eq!(elf::find(image, b"__vdso_no_such_function", version), None);
        assert_eq!(elf::find(image, &name[..name.len() - 1], version), None);
        if found.is_some() {
            assert_eq!(elf::find(image, name, b"LINUX_0.0"), None);
            assert_eq!(elf::find(image, name, &version[..version.len() - 1]), None);
        }
    }

    #[test]
    fn probe() {
        let probe = Probe::new().unwrap();
        let data = [7u8; 10_000];
        assert!(probe.readable(data.as_ptr().addr(), data.len()));
        assert!(probe.readable(data.as_ptr().addr() + 1, 1));
        assert!(probe.readable(data.as_ptr().addr(), 0));
        // The first page is never mapped, and neither is the last.
        assert!(!probe.readable(0, 1));
        assert!(!probe.readable(4096 - 16, 64));
        assert!(!probe.readable(usize::MAX - 4096, 4096));
        // A range that starts in mapped memory and leaves it. 64 KiB is a
        // whole number of pages whatever their size.
        let page = 1usize << 16;
        // SAFETY: a new private, anonymous, readable mapping, wherever the
        // kernel likes.
        #[cfg(target_pointer_width = "32")]
        let base = unsafe { syscall!(MMAP2, 0, 2 * page, 1, 0x22, -1i32, 0) }.unwrap();
        // SAFETY: as above.
        #[cfg(target_pointer_width = "64")]
        let base = unsafe { syscall!(MMAP, 0, 2 * page, 1, 0x22, -1i32, 0) }.unwrap();
        assert!(probe.readable(base, 2 * page));
        // SAFETY: the second half of the mapping made above, which nothing
        // else knows of, becomes inaccessible.
        unsafe { syscall!(MPROTECT, base + page, page, 0) }.unwrap();
        assert!(probe.readable(base, page));
        assert!(!probe.readable(base, page + 1));
        assert!(!probe.readable(base + page - 1, 2));
        assert!(!probe.readable(base + page, 1));
        // SAFETY: the mapping made above.
        unsafe { syscall!(MUNMAP, base, 2 * page) }.unwrap();
        assert!(!probe.readable(base, 1));
    }

    /// Whatever is done to the image, looking a symbol up in it returns: no
    /// panic, no read outside of it, and an offset inside it or nothing.
    #[test]
    fn malformed_images() {
        let (Some(image), Some((name, version))) = (image(), CLOCK_GETTIME) else {
            return;
        };
        let mut copy = [0u8; 1 << 17];
        let Some(copy) = copy.get_mut(..image.len()) else {
            return;
        };
        copy.copy_from_slice(image);
        let pristine = elf::find(copy, name, version);
        assert_eq!(pristine, elf::find(image, name, version));

        let check = |bytes: &[u8]| {
            for sysv_hash in [true, false] {
                if let Some(offset) = elf::find_with(bytes, name, version, sysv_hash) {
                    assert!(offset < bytes.len());
                }
            }
        };

        // Cut short anywhere.
        for len in (0..copy.len()).step_by(7).chain(0..600) {
            check(&copy[..len.min(copy.len())]);
        }

        // Every byte of the headers and tables, which are at the start,
        // replaced in turn by values that make offsets and counts absurd.
        let tables = copy.len().min(2048);
        for at in 0..tables {
            let old = copy[at];
            for new in [
                0x00,
                0x01,
                0x7f,
                0x80,
                0xff,
                old ^ 0x04,
                old.wrapping_add(1),
            ] {
                copy[at] = new;
                check(copy);
            }
            copy[at] = old;
        }

        // And random damage anywhere, several bytes at a time.
        let mut state = 0x9e37_79b9_7f4a_7c15u64;
        let mut random = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as usize
        };
        for _ in 0..4000 {
            let mut saved = [(0usize, 0u8); 4];
            for slot in &mut saved {
                // Half of the damage goes where the tables are.
                let at = if random() % 2 == 0 {
                    random() % tables
                } else {
                    random() % copy.len()
                };
                *slot = (at, copy[at]);
                copy[at] = random() as u8;
            }
            check(copy);
            for (at, old) in saved.into_iter().rev() {
                copy[at] = old;
            }
        }
        assert_eq!(elf::find(copy, name, version), pristine);
    }
}