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
//! A tiny library to parse the in-memory vDSO.
//! For more documentation of what's vDSO and why we need it on Linux see
//! [here](https://man7.org/linux/man-pages/man7/vdso.7.html).

#![no_std]

#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "aarch64",
        target_pointer_width = "64"
    ),
    path = "arch/aarch64.rs"
)]
#[cfg_attr(
    all(target_os = "linux", target_arch = "arm", target_pointer_width = "32"),
    path = "arch/arm.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "loongarch64",
        target_endian = "little",
        target_pointer_width = "64"
    ),
    path = "arch/loongarch64.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        any(
            all(target_arch = "mips", target_pointer_width = "32"),
            target_arch = "mips64"
        )
    ),
    path = "arch/mips.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "powerpc",
        target_endian = "big",
        target_pointer_width = "32"
    ),
    path = "arch/powerpc.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "powerpc64",
        target_pointer_width = "64"
    ),
    path = "arch/powerpc64.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        all(
            any(
                all(target_arch = "riscv32", target_pointer_width = "32"),
                all(target_arch = "riscv64", target_pointer_width = "64")
            ),
            target_endian = "little"
        )
    ),
    path = "arch/riscv.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "s390x",
        target_endian = "big",
        target_pointer_width = "64"
    ),
    path = "arch/s390x.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "x86_64",
        target_endian = "little",
        target_pointer_width = "32"
    ),
    path = "arch/x32.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "x86",
        target_endian = "little",
        target_pointer_width = "32"
    ),
    path = "arch/x86.rs"
)]
#[cfg_attr(
    all(
        target_os = "linux",
        target_arch = "x86_64",
        target_endian = "little",
        target_pointer_width = "64"
    ),
    path = "arch/x86_64.rs"
)]
mod arch;

mod elf;
pub(crate) mod util;

pub use arch::Vdso;

use core::{marker::PhantomData, ptr};

pub(crate) struct VdsoReader<'a> {
    header: &'a VdsoHeader,
    versyms: *const u16,
    verdefs: *const elf::Verdef,
    strings: *const u8,
    syms: &'a [elf::Sym],
}

impl<'a> VdsoReader<'a> {
    pub unsafe fn from_ptr(ptr: *const core::ffi::c_void) -> Option<Self> {
        Self::from_header(VdsoHeader::from_ptr(ptr)?)
    }

    unsafe fn from_header(header: &'a VdsoHeader) -> Option<VdsoReader> {
        let mut versyms: *const u16 = ptr::null();
        let mut verdefs: *const elf::Verdef = ptr::null();
        let mut strings: *const u8 = ptr::null();
        let mut syms: Option<&[elf::Sym]> = None;
        let mut filled = 0u8;

        for sh in header.shs() {
            match sh.sh_type {
                elf::SHT_GNU_VERSYM => {
                    versyms = header.offset(sh.sh_offset);
                    filled |= 1 << 0;
                    if filled == 15 {
                        break;
                    }
                }
                elf::SHT_GNU_VERDEF => {
                    verdefs = header.offset(sh.sh_offset);
                    filled |= 1 << 1;
                    if filled == 15 {
                        break;
                    }
                }
                elf::SHT_STRTAB => {
                    strings = header.offset(sh.sh_offset);
                    filled |= 1 << 2;
                    if filled == 15 {
                        break;
                    }
                }
                elf::SHT_DYNSYM => {
                    syms = Some(header.slice(sh.sh_offset, sh.sh_size));
                    filled |= 1 << 3;
                    if filled == 15 {
                        break;
                    }
                }
                _ => (),
            }
        }

        if versyms.is_null() {
            verdefs = ptr::null();
        } else if verdefs.is_null() {
            versyms = ptr::null();
        }
        let syms = syms?;
        if strings.is_null() {
            return None;
        }

        Some(Self {
            header,
            versyms,
            verdefs,
            strings,
            syms,
        })
    }

    pub fn versions(&self) -> VersionIter {
        VersionIter {
            verdefs: self.verdefs,
            reader: self,
        }
    }

    pub fn symbols(&self) -> SymbolIter {
        SymbolIter {
            versyms: self.versyms,
            iter: self.syms.iter(),
            reader: self,
        }
    }
}

pub(crate) struct Version<'a> {
    hash: u32,
    id: u16,
    name: *const u8,
    _life: PhantomData<&'a ()>,
}

impl<'a> Version<'a> {
    #[inline]
    pub const fn hash(&self) -> u32 {
        self.hash
    }

    #[inline]
    pub const fn id(&self) -> u16 {
        self.id
    }

    #[inline]
    pub fn name(&self) -> *const u8 {
        self.name
    }
}

pub(crate) struct VersionIter<'a> {
    verdefs: *const elf::Verdef,
    reader: &'a VdsoReader<'a>,
}

impl<'a> Iterator for VersionIter<'a> {
    type Item = Version<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            unsafe {
                if self.verdefs.is_null() {
                    return None;
                }

                let verdef = &*self.verdefs;
                if verdef.vd_next == 0 {
                    self.verdefs = ptr::null();
                } else {
                    self.verdefs = self
                        .verdefs
                        .cast::<u8>()
                        .add(verdef.vd_next as usize)
                        .cast();
                }

                if verdef.vd_version == 1 && verdef.vd_flags & 1 == 0 {
                    let aux = &*(verdef as *const elf::Verdef)
                        .cast::<u8>()
                        .add(verdef.vd_aux as usize)
                        .cast::<elf::Verdaux>();
                    let name = self.reader.strings.add(aux.vda_name as usize);

                    return Some(Version {
                        hash: verdef.vd_hash,
                        id: verdef.vd_ndx,
                        name,
                        _life: PhantomData,
                    });
                }
            }
        }
    }
}

pub(crate) struct Symbol<'a> {
    name: *const u8,
    ptr: *const core::ffi::c_void,
    vid: Option<u16>,
    _life: PhantomData<&'a ()>,
}

impl<'a> Symbol<'a> {
    #[inline]
    pub fn name(&self) -> *const u8 {
        self.name
    }

    #[inline]
    pub fn ptr(&self) -> *const core::ffi::c_void {
        self.ptr
    }

    #[inline]
    pub fn version_id(&self) -> Option<u16> {
        self.vid
    }
}

pub(crate) struct SymbolIter<'a> {
    versyms: *const u16,
    iter: core::slice::Iter<'a, elf::Sym>,
    reader: &'a VdsoReader<'a>,
}

impl<'a> Iterator for SymbolIter<'a> {
    type Item = Symbol<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            unsafe {
                let sym = self.iter.next()?;
                let vid = if !self.versyms.is_null() {
                    let res = *self.versyms;
                    self.versyms = self.versyms.add(1);
                    Some(res)
                } else {
                    None
                };

                let typ = elf::st_type(sym.st_info);
                let bind = elf::st_bind(sym.st_info);

                if (bind == elf::STB_GLOBAL || bind == elf::STB_WEAK)
                    && (typ == elf::STT_FUNC || typ == elf::STT_NOTYPE)
                    && elf::st_visibility(sym.st_other) == elf::STV_DEFAULT
                {
                    let name = self.reader.strings.add(sym.st_name as usize);

                    return Some(Symbol {
                        name,
                        ptr: self.reader.header.offset(sym.st_value),
                        vid,
                        _life: PhantomData,
                    });
                }
            }
        }
    }
}

#[repr(transparent)]
struct VdsoHeader(elf::Header);

impl VdsoHeader {
    pub(crate) unsafe fn from_ptr<'a>(ptr: *const core::ffi::c_void) -> Option<&'a Self> {
        let head = &*(ptr as *const Self);

        // Test magic number
        if head.0.e_ident[..elf::ELFMAG.len()] != elf::ELFMAG[..] {
            return None;
        }

        // Test class
        if head.0.e_ident[elf::EI_CLASS] != elf::ELFCLASS {
            return None;
        }

        // Test OS ABI
        match head.0.e_ident[elf::EI_OSABI] {
            elf::ELFOSABI_SYSV | elf::ELFOSABI_LINUX => (),
            _ => return None,
        }

        // Test ABI version
        if head.0.e_ident[elf::EI_ABIVERSION] != 0 {
            return None;
        }

        // Test elf type, it must be dynamic
        if head.0.e_type != elf::ET_DYN {
            return None;
        }

        // Test elf version
        if head.0.e_ident[elf::EI_VERSION] != elf::EV_CURRENT {
            return None;
        }

        // Test some sizes
        if head.0.e_ehsize as usize != core::mem::size_of::<elf::Header>()
            || head.0.e_phentsize as usize != core::mem::size_of::<elf::ProgramHeader>()
        {
            return None;
        }

        if head.0.e_phnum == 0xffff {
            return None;
        }

        if (head.0.e_phoff as usize) < core::mem::size_of::<elf::Header>() {
            return None;
        }

        // Test endianness
        if head.0.e_ident[elf::EI_DATA] != elf::ELFDATA {
            return None;
        }

        // Test arch
        if head.0.e_machine != elf::EM_CURRENT {
            return None;
        }

        Some(head)
    }

    pub(crate) unsafe fn offset<T, O>(&self, off: O) -> *const T
    where
        O: Into<elf::Word>,
    {
        (self as *const Self)
            .cast::<u8>()
            .add(off.into() as usize)
            .cast::<T>()
    }

    pub(crate) unsafe fn slice<'a, T, T1, T2>(&'a self, off: T1, len: T2) -> &[T]
    where
        T1: Into<elf::Word> + 'a,
        T2: Into<elf::Word> + 'a,
    {
        core::slice::from_raw_parts::<u8>(self.offset(off), len.into() as usize)
            .align_to()
            .1
    }

    pub(crate) unsafe fn shs(&self) -> &[elf::SectionHeader] {
        self.slice(self.0.e_shoff, self.0.e_shentsize * self.0.e_shnum)
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    #[cfg(all(
        target_os = "linux",
        target_arch = "x86_64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/x86_64.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "x86_64",
        target_endian = "little",
        target_pointer_width = "32"
    ))]
    const FAKE: &str = "fake/x32.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "x86",
        target_endian = "little",
        target_pointer_width = "32"
    ))]
    const FAKE: &str = "fake/x86.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "aarch64",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/aarch64.so";
    #[cfg(all(target_os = "linux", target_arch = "arm", target_pointer_width = "32"))]
    const FAKE: &str = "fake/arm.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "loongarch64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/loongarch64.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "mips",
        target_endian = "big",
        target_pointer_width = "32"
    ))]
    const FAKE: &str = "fake/mips.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "mips",
        target_endian = "little",
        target_pointer_width = "32"
    ))]
    const FAKE: &str = "fake/mipsel.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "mips64",
        target_endian = "big",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/mips64.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "mips64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/mips64el.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "powerpc",
        target_endian = "big",
        target_pointer_width = "32"
    ))]
    const FAKE: &str = "fake/powerpc.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "powerpc64",
        target_endian = "big",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/powerpc64.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "powerpc64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/powerpc64le.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "riscv32",
        target_endian = "little",
        target_pointer_width = "32"
    ))]
    const FAKE: &str = "fake/riscv32.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "riscv64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/riscv64.so";
    #[cfg(all(
        target_os = "linux",
        target_arch = "s390x",
        target_endian = "big",
        target_pointer_width = "64"
    ))]
    const FAKE: &str = "fake/s390x.so";

    #[cfg(all(
        target_os = "linux",
        target_arch = "x86_64",
        target_endian = "little",
        any(target_pointer_width = "64", target_pointer_width = "32")
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.getcpu.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.time.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "x86",
        target_endian = "little",
        target_pointer_width = "32"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.sigreturn.is_null());
        assert!(!vdso.rt_sigreturn.is_null());
        assert!(!vdso.vsyscall.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.time.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "aarch64",
        target_pointer_width = "64"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.rt_sigreturn.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.clock_getres.is_null());
    }

    #[cfg(all(target_os = "linux", target_arch = "arm", target_pointer_width = "32"))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.clock_gettime.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "loongarch64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.getcpu.is_null());
        assert!(!vdso.clock_getres.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.rt_sigreturn.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        any(
            all(target_arch = "mips", target_pointer_width = "32"),
            target_arch = "mips64"
        )
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.clock_gettime.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "powerpc",
        target_endian = "big",
        target_pointer_width = "32"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.clock_getres.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.clock_gettime64.is_null());
        assert!(!vdso.datapage_offset.is_null());
        assert!(!vdso.get_syscall_map.is_null());
        assert!(!vdso.get_tbfreq.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.sigtramp_rt32.is_null());
        assert!(!vdso.sigtramp32.is_null());
        assert!(!vdso.sync_dicache.is_null());
        assert!(!vdso.sync_dicache_p5.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "powerpc64",
        target_pointer_width = "64"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.clock_getres.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.clock_gettime64.is_null());
        assert!(!vdso.datapage_offset.is_null());
        assert!(!vdso.get_syscall_map.is_null());
        assert!(!vdso.get_tbfreq.is_null());
        assert!(!vdso.getcpu.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.sigtramp_rt32.is_null());
        assert!(!vdso.sigtramp32.is_null());
        assert!(!vdso.sync_dicache.is_null());
        assert!(!vdso.sync_dicache_p5.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "riscv64",
        target_endian = "little",
        target_pointer_width = "64"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.rt_sigreturn.is_null());
        assert!(!vdso.gettimeofday.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.clock_getres.is_null());
        assert!(!vdso.getcpu.is_null());
        assert!(!vdso.flush_icache.is_null());
    }

    #[cfg(all(
        target_os = "linux",
        target_arch = "s390x",
        target_endian = "big",
        target_pointer_width = "64"
    ))]
    #[test]
    fn parse() {
        let data = std::fs::read(FAKE).unwrap();
        let vdso = unsafe { super::Vdso::from_ptr(data.as_ptr().cast()) };
        assert!(vdso.is_some());
        let vdso = vdso.unwrap();
        assert!(!vdso.clock_getres.is_null());
        assert!(!vdso.clock_gettime.is_null());
        assert!(!vdso.gettimeofday.is_null());
    }
}