findshlibs/linux/
mod.rs

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
//! Linux-specific implementation of the `SharedLibrary` trait.

use libc;

use crate::Segment as SegmentTrait;
use crate::SharedLibrary as SharedLibraryTrait;
use crate::{Bias, IterationControl, SharedLibraryId, Svma};

use std::any::Any;
use std::borrow::Cow;
use std::env::current_exe;
use std::ffi::{CStr, CString, OsStr};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::mem;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
use std::panic;
use std::slice;
use std::usize;

#[cfg(target_pointer_width = "32")]
type Phdr = libc::Elf32_Phdr;

#[cfg(target_pointer_width = "64")]
type Phdr = libc::Elf64_Phdr;

const NT_GNU_BUILD_ID: u32 = 3;

// Normally we would use `Elf32_Nhdr` on 32-bit platforms and `Elf64_Nhdr` on
// 64-bit platforms. However, in practice it seems that only `Elf32_Nhdr` is
// used, and reading through binutil's `readelf` source confirms this.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct Nhdr {
    pub n_namesz: libc::Elf32_Word,
    pub n_descsz: libc::Elf32_Word,
    pub n_type: libc::Elf32_Word,
}

/// A mapped segment in an ELF file.
#[derive(Debug)]
pub struct Segment<'a> {
    phdr: *const Phdr,
    shlib: PhantomData<&'a SharedLibrary<'a>>,
}

impl<'a> Segment<'a> {
    fn phdr(&self) -> &'a Phdr {
        unsafe { self.phdr.as_ref().unwrap() }
    }

    /// You must pass this segment's `SharedLibrary` or else this is wild UB.
    unsafe fn data(&self, shlib: &SharedLibrary<'a>) -> &'a [u8] {
        let phdr = self.phdr();
        let avma = (shlib.addr as usize).wrapping_add(phdr.p_vaddr as usize);
        slice::from_raw_parts(avma as *const u8, phdr.p_memsz as usize)
    }

    fn is_note(&self) -> bool {
        self.phdr().p_type == libc::PT_NOTE
    }

    /// Parse the contents of a `PT_NOTE` segment.
    ///
    /// Returns a triple of
    ///
    /// 1. The `NT_*` note type.
    /// 2. The note name.
    /// 3. The note descriptor payload.
    ///
    /// You must pass this segment's `SharedLibrary` or else this is wild UB.
    unsafe fn notes(
        &self,
        shlib: &SharedLibrary<'a>,
    ) -> impl Iterator<Item = (libc::Elf32_Word, &'a [u8], &'a [u8])> {
        // `man 5 readelf` says that all of the `Nhdr`, name, and descriptor are
        // always 4-byte aligned, but we copy this alignment behavior from
        // `readelf` since that seems to match reality in practice.
        let alignment = std::cmp::max(self.phdr().p_align as usize, 4);
        let align_up = move |data: &'a [u8]| {
            if alignment != 4 && alignment != 8 {
                return None;
            }

            let ptr = data.as_ptr() as usize;
            let alignment_minus_one = alignment - 1;
            let aligned_ptr = ptr.checked_add(alignment_minus_one)? & !alignment_minus_one;
            let diff = aligned_ptr - ptr;
            if data.len() < diff {
                None
            } else {
                Some(&data[diff..])
            }
        };

        let mut data = self.data(shlib);

        iter::from_fn(move || {
            if (data.as_ptr() as usize % alignment) != 0 {
                return None;
            }

            // Each entry in a `PT_NOTE` segment begins with a
            // fixed-size header `Nhdr`.
            let nhdr_size = mem::size_of::<Nhdr>();
            let nhdr = try_split_at(&mut data, nhdr_size)?;
            let nhdr = (nhdr.as_ptr() as *const Nhdr).as_ref().unwrap();

            // No need to `align_up` after the `Nhdr`
            // It is followed by a name of size `n_namesz`.
            let name_size = nhdr.n_namesz as usize;
            let name = try_split_at(&mut data, name_size)?;

            // And after that is the note's (aligned) descriptor payload of size
            // `n_descsz`.
            data = align_up(data)?;
            let desc_size = nhdr.n_descsz as usize;
            let desc = try_split_at(&mut data, desc_size)?;

            // Align the data for the next `Nhdr`.
            data = align_up(data)?;

            Some((nhdr.n_type, name, desc))
        })
        .fuse()
    }
}

fn try_split_at<'a>(data: &mut &'a [u8], index: usize) -> Option<&'a [u8]> {
    if data.len() < index {
        None
    } else {
        let (head, tail) = data.split_at(index);
        *data = tail;
        Some(head)
    }
}

impl<'a> SegmentTrait for Segment<'a> {
    type SharedLibrary = SharedLibrary<'a>;

    fn name(&self) -> &str {
        unsafe {
            match self.phdr.as_ref().unwrap().p_type {
                libc::PT_NULL => "NULL",
                libc::PT_LOAD => "LOAD",
                libc::PT_DYNAMIC => "DYNAMIC",
                libc::PT_INTERP => "INTERP",
                libc::PT_NOTE => "NOTE",
                libc::PT_SHLIB => "SHLIB",
                libc::PT_PHDR => "PHDR",
                libc::PT_TLS => "TLS",
                libc::PT_GNU_EH_FRAME => "GNU_EH_FRAME",
                libc::PT_GNU_STACK => "GNU_STACK",
                libc::PT_GNU_RELRO => "GNU_RELRO",
                _ => "(unknown segment type)",
            }
        }
    }

    #[inline]
    fn is_code(&self) -> bool {
        let hdr = self.phdr();
        // 0x1 is PT_X for executable
        hdr.p_type == libc::PT_LOAD && (hdr.p_flags & 0x1) != 0
    }

    #[inline]
    fn is_load(&self) -> bool {
        self.phdr().p_type == libc::PT_LOAD
    }

    #[inline]
    fn stated_virtual_memory_address(&self) -> Svma {
        Svma(self.phdr().p_vaddr as _)
    }

    #[inline]
    fn len(&self) -> usize {
        self.phdr().p_memsz as _
    }
}

/// An iterator of mapped segments in a shared library.
pub struct SegmentIter<'a> {
    inner: std::slice::Iter<'a, Phdr>,
}

impl<'a> Iterator for SegmentIter<'a> {
    type Item = Segment<'a>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|phdr| Segment {
            phdr: phdr,
            shlib: PhantomData,
        })
    }
}

impl<'a> fmt::Debug for SegmentIter<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let ref phdr = self.inner.as_slice()[0];

        f.debug_struct("SegmentIter")
            .field("phdr", &DebugPhdr(phdr))
            .finish()
    }
}

/// A shared library on Linux.
pub struct SharedLibrary<'a> {
    size: usize,
    addr: *const u8,
    name: Cow<'a, CStr>,
    headers: &'a [Phdr],
}

struct IterState<F> {
    f: F,
    panic: Option<Box<dyn Any + Send>>,
    idx: usize,
}

const CONTINUE: libc::c_int = 0;
const BREAK: libc::c_int = 1;

impl<'a> SharedLibrary<'a> {
    unsafe fn new(info: &'a libc::dl_phdr_info, size: usize, is_first_lib: bool) -> Self {
        // try to get the name from the dl_phdr_info.  If that fails there are two
        // cases we can and need to deal with.  The first one is if we are the first
        // loaded library in which case the name is the executable which we can
        // discover via env::current_exe (reads the proc/self symlink).
        //
        // Otherwise if we have a no name we might be a dylib that was loaded with
        // dlopen in which case we can use dladdr to recover the name.
        let mut name = Cow::Borrowed(if info.dlpi_name.is_null() {
            CStr::from_bytes_with_nul_unchecked(b"\0")
        } else {
            CStr::from_ptr(info.dlpi_name)
        });
        if name.to_bytes().is_empty() {
            if is_first_lib {
                if let Ok(exe) = current_exe() {
                    name = Cow::Owned(CString::from_vec_unchecked(exe.into_os_string().into_vec()));
                }
            } else {
                let mut dlinfo: libc::Dl_info = mem::zeroed();
                if libc::dladdr(info.dlpi_addr as *const libc::c_void, &mut dlinfo) != 0 {
                    name = Cow::Owned(CString::from(CStr::from_ptr(dlinfo.dli_fname)));
                }
            }
        }

        SharedLibrary {
            size: size,
            addr: info.dlpi_addr as usize as *const _,
            name,
            headers: slice::from_raw_parts(info.dlpi_phdr, info.dlpi_phnum as usize),
        }
    }

    unsafe extern "C" fn callback<F, C>(
        info: *mut libc::dl_phdr_info,
        size: usize,
        state: *mut libc::c_void,
    ) -> libc::c_int
    where
        F: FnMut(&Self) -> C,
        C: Into<IterationControl>,
    {
        if (*info).dlpi_phdr.is_null() {
            return CONTINUE;
        }

        let state = &mut *(state as *mut IterState<F>);
        state.idx += 1;

        match panic::catch_unwind(panic::AssertUnwindSafe(|| {
            let info = info.as_ref().unwrap();
            let shlib = SharedLibrary::new(info, size, state.idx == 1);

            (state.f)(&shlib).into()
        })) {
            Ok(IterationControl::Continue) => CONTINUE,
            Ok(IterationControl::Break) => BREAK,
            Err(panicked) => {
                state.panic = Some(panicked);
                BREAK
            }
        }
    }

    fn note_segments(&self) -> impl Iterator<Item = Segment<'a>> {
        self.segments().filter(|s| s.is_note())
    }
}

impl<'a> SharedLibraryTrait for SharedLibrary<'a> {
    type Segment = Segment<'a>;
    type SegmentIter = SegmentIter<'a>;

    #[inline]
    fn name(&self) -> &OsStr {
        OsStr::from_bytes(self.name.to_bytes())
    }

    fn id(&self) -> Option<SharedLibraryId> {
        // Search for `PT_NOTE` segments, containing auxilliary information.
        // Such segments contain a series of "notes" and one kind of note is
        // `NT_GNU_BUILD_ID`, whose payload contains a unique identifier
        // generated by the linker. Return the first one we find, if any.
        for segment in self.note_segments() {
            for (note_type, note_name, note_descriptor) in unsafe { segment.notes(self) } {
                if note_type == NT_GNU_BUILD_ID && note_name == b"GNU\0" {
                    return Some(SharedLibraryId::GnuBuildId(note_descriptor.to_vec()));
                }
            }
        }

        None
    }

    #[inline]
    fn segments(&self) -> Self::SegmentIter {
        SegmentIter {
            inner: self.headers.iter(),
        }
    }

    #[inline]
    fn virtual_memory_bias(&self) -> Bias {
        Bias(self.addr as usize)
    }

    #[inline]
    fn each<F, C>(f: F)
    where
        F: FnMut(&Self) -> C,
        C: Into<IterationControl>,
    {
        let mut state = IterState {
            f: f,
            panic: None,
            idx: 0,
        };

        unsafe {
            libc::dl_iterate_phdr(Some(Self::callback::<F, C>), &mut state as *mut _ as *mut _);
        }

        if let Some(panic) = state.panic {
            panic::resume_unwind(panic);
        }
    }
}

impl<'a> fmt::Debug for SharedLibrary<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "SharedLibrary {{ size: {:?}, addr: {:?}, ",
            self.size, self.addr
        )?;
        write!(f, "name: {:?}, headers: [", self.name)?;

        // Debug does not usually have a trailing comma in the list,
        // last element must be formatted separately.
        let l = self.headers.len();
        self.headers[..(l - 1)]
            .into_iter()
            .map(|phdr| write!(f, "{:?}, ", &DebugPhdr(phdr)))
            .collect::<fmt::Result>()?;

        write!(f, "{:?}", &DebugPhdr(&self.headers[l - 1]))?;

        write!(f, "] }}")
    }
}

struct DebugPhdr<'a>(&'a Phdr);

impl<'a> fmt::Debug for DebugPhdr<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let phdr = self.0;

        // The layout is different for 32-bit vs 64-bit,
        // but since the fields are the same, it shouldn't matter much.
        f.debug_struct("Phdr")
            .field("p_type", &phdr.p_type)
            .field("p_flags", &phdr.p_flags)
            .field("p_offset", &phdr.p_offset)
            .field("p_vaddr", &phdr.p_vaddr)
            .field("p_paddr", &phdr.p_paddr)
            .field("p_filesz", &phdr.p_filesz)
            .field("p_memsz", &phdr.p_memsz)
            .field("p_align", &phdr.p_align)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use crate::linux;
    use crate::{IterationControl, Segment, SharedLibrary};

    #[test]
    fn have_libc() {
        let mut found_libc = false;
        linux::SharedLibrary::each(|info| {
            found_libc |= info
                .name
                .to_bytes()
                .split(|c| *c == b'.' || *c == b'/')
                .find(|s| s == b"libc")
                .is_some();
        });
        assert!(found_libc);
    }

    #[test]
    fn can_break() {
        let mut first_count = 0;
        linux::SharedLibrary::each(|_| {
            first_count += 1;
        });
        assert!(first_count > 2);

        let mut second_count = 0;
        linux::SharedLibrary::each(|_| {
            second_count += 1;

            if second_count == first_count - 1 {
                IterationControl::Break
            } else {
                IterationControl::Continue
            }
        });
        assert_eq!(second_count, first_count - 1);
    }

    #[test]
    fn get_name() {
        use std::ffi::OsStr;
        let mut names = vec![];
        linux::SharedLibrary::each(|shlib| {
            println!("{:?}", shlib);
            let name = shlib.name();
            if name != OsStr::new("") {
                names.push(name.to_str().unwrap().to_string());
            }
        });

        assert!(names.iter().any(|x| x.contains("findshlibs")));
        assert!(names.iter().any(|x| x.contains("libc.so")));
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn get_id() {
        use std::path::Path;
        use std::process::Command;

        linux::SharedLibrary::each(|shlib| {
            let name = shlib.name();
            let id = shlib.id();
            if id.is_none() {
                println!("no id found for {:?}", name);
                return;
            }
            let path: &Path = name.as_ref();
            if !path.is_absolute() {
                return;
            }
            let gnu_build_id = id.unwrap().to_string();
            let readelf = Command::new("readelf")
                .arg("-n")
                .arg(path)
                .output()
                .unwrap();
            for line in String::from_utf8(readelf.stdout).unwrap().lines() {
                if let Some(index) = line.find("Build ID: ") {
                    let readelf_build_id = line[index + 9..].trim();
                    assert_eq!(readelf_build_id, gnu_build_id);
                }
            }
            println!("{}: {}", path.display(), gnu_build_id);
        });
    }

    #[test]
    fn have_load_segment() {
        linux::SharedLibrary::each(|shlib| {
            println!("shlib = {:?}", shlib.name());

            let mut found_load = false;
            for seg in shlib.segments() {
                println!("    segment = {:?}", seg.name());

                found_load |= seg.name() == "LOAD";
            }
            assert!(found_load);
        });
    }
}