1use core::convert::TryInto;
2use core::fmt::Debug;
3
4use crate::elf;
5use crate::endian;
6use crate::pod::Pod;
7use crate::read::{ReadError, Result, StringTable};
8
9/// A trait for generic access to [`elf::Dyn32`] and [`elf::Dyn64`].
10#[allow(missing_docs)]
11pub trait Dyn: Debug + Pod {
12 type Word: Into<u64>;
13 type Endian: endian::Endian;
14
15 fn d_tag(&self, endian: Self::Endian) -> Self::Word;
16 fn d_val(&self, endian: Self::Endian) -> Self::Word;
17
18 /// Try to convert the tag to a `u32`.
19 fn tag32(&self, endian: Self::Endian) -> Option<u32> {
20 self.d_tag(endian).into().try_into().ok()
21 }
22
23 /// Try to convert the value to a `u32`.
24 fn val32(&self, endian: Self::Endian) -> Option<u32> {
25 self.d_val(endian).into().try_into().ok()
26 }
27
28 /// Return true if the value is an offset in the dynamic string table.
29 fn is_string(&self, endian: Self::Endian) -> bool {
30 if let Some(tag) = self.tag32(endian) {
31 match tag {
32 elf::DT_NEEDED
33 | elf::DT_SONAME
34 | elf::DT_RPATH
35 | elf::DT_RUNPATH
36 | elf::DT_AUXILIARY
37 | elf::DT_FILTER => true,
38 _ => false,
39 }
40 } else {
41 false
42 }
43 }
44
45 /// Use the value to get a string in a string table.
46 ///
47 /// Does not check for an appropriate tag.
48 fn string<'data>(
49 &self,
50 endian: Self::Endian,
51 strings: StringTable<'data>,
52 ) -> Result<&'data [u8]> {
53 self.val32(endian)
54 .and_then(|val| strings.get(val).ok())
55 .read_error("Invalid ELF dyn string")
56 }
57
58 /// Return true if the value is an address.
59 fn is_address(&self, endian: Self::Endian) -> bool {
60 if let Some(tag) = self.tag32(endian) {
61 match tag {
62 elf::DT_PLTGOT
63 | elf::DT_HASH
64 | elf::DT_STRTAB
65 | elf::DT_SYMTAB
66 | elf::DT_RELA
67 | elf::DT_INIT
68 | elf::DT_FINI
69 | elf::DT_SYMBOLIC
70 | elf::DT_REL
71 | elf::DT_DEBUG
72 | elf::DT_JMPREL
73 | elf::DT_FINI_ARRAY
74 | elf::DT_INIT_ARRAY
75 | elf::DT_PREINIT_ARRAY
76 | elf::DT_SYMTAB_SHNDX
77 | elf::DT_VERDEF
78 | elf::DT_VERNEED
79 | elf::DT_VERSYM
80 | elf::DT_ADDRRNGLO..=elf::DT_ADDRRNGHI => true,
81 _ => false,
82 }
83 } else {
84 false
85 }
86 }
87}
88
89impl<Endian: endian::Endian> Dyn for elf::Dyn32<Endian> {
90 type Word = u32;
91 type Endian = Endian;
92
93 #[inline]
94 fn d_tag(&self, endian: Self::Endian) -> Self::Word {
95 self.d_tag.get(endian)
96 }
97
98 #[inline]
99 fn d_val(&self, endian: Self::Endian) -> Self::Word {
100 self.d_val.get(endian)
101 }
102}
103
104impl<Endian: endian::Endian> Dyn for elf::Dyn64<Endian> {
105 type Word = u64;
106 type Endian = Endian;
107
108 #[inline]
109 fn d_tag(&self, endian: Self::Endian) -> Self::Word {
110 self.d_tag.get(endian)
111 }
112
113 #[inline]
114 fn d_val(&self, endian: Self::Endian) -> Self::Word {
115 self.d_val.get(endian)
116 }
117}
118