| 1 |
//! A byte-offset based string table. |
| 2 |
//! Commonly used in ELF binaries, Unix archives, and even PE binaries. |
| 3 |
|
| 4 |
use core::fmt; |
| 5 |
use core::ops::Index; |
| 6 |
use core::str; |
| 7 |
use scroll::{ctx, Pread}; |
| 8 |
if_alloc! { |
| 9 |
use crate::error; |
| 10 |
use alloc::vec::Vec; |
| 11 |
} |
| 12 |
|
| 13 |
/// A common string table format which is indexed by byte offsets (and not |
| 14 |
/// member index). Constructed using [`parse`](#method.parse) |
| 15 |
/// with your choice of delimiter. Please be careful. |
| 16 |
pub struct Strtab<'a> { |
| 17 |
delim: ctx::StrCtx, |
| 18 |
bytes: &'a [u8], |
| 19 |
#[cfg(feature = "alloc")] |
| 20 |
strings: Vec<(usize, &'a str)>, |
| 21 |
} |
| 22 |
|
| 23 |
#[inline(always)] |
| 24 |
fn get_str(offset: usize, bytes: &[u8], delim: ctx::StrCtx) -> scroll::Result<&str> { |
| 25 |
bytes.pread_with::<&str>(offset, delim) |
| 26 |
} |
| 27 |
|
| 28 |
impl<'a> Strtab<'a> { |
| 29 |
/// Creates a `Strtab` with `bytes` as the backing string table, using `delim` as the delimiter between entries. |
| 30 |
/// |
| 31 |
/// NB: this does *not* preparse the string table, which can have non-optimal access patterns. |
| 32 |
/// See <https://github.com/m4b/goblin/pull/275> |
| 33 |
pub fn new(bytes: &'a [u8], delim: u8) -> Self { |
| 34 |
Self::from_slice_unparsed(bytes, 0, bytes.len(), delim) |
| 35 |
} |
| 36 |
|
| 37 |
/// Returns the length of this `Strtab` in bytes |
| 38 |
pub fn len(&self) -> usize { |
| 39 |
self.bytes.len() |
| 40 |
} |
| 41 |
|
| 42 |
/// Creates a `Strtab` directly without bounds check and without parsing it. |
| 43 |
/// |
| 44 |
/// This is potentially unsafe and should only be used if `feature = "alloc"` is disabled. |
| 45 |
pub fn from_slice_unparsed(bytes: &'a [u8], offset: usize, len: usize, delim: u8) -> Self { |
| 46 |
Self { |
| 47 |
delim: ctx::StrCtx::Delimiter(delim), |
| 48 |
bytes: &bytes[offset..offset + len], |
| 49 |
#[cfg(feature = "alloc")] |
| 50 |
strings: Vec::new(), |
| 51 |
} |
| 52 |
} |
| 53 |
/// Gets a str reference from the backing bytes starting at byte `offset`. |
| 54 |
/// |
| 55 |
/// If the index is out of bounds, `None` is returned. Panics if bytes are invalid UTF-8. |
| 56 |
/// Use this method if the `Strtab` was created using `from_slice_unparsed()`. |
| 57 |
pub fn get_unsafe(&self, offset: usize) -> Option<&'a str> { |
| 58 |
if offset >= self.bytes.len() { |
| 59 |
None |
| 60 |
} else { |
| 61 |
Some(get_str(offset, self.bytes, self.delim).unwrap()) |
| 62 |
} |
| 63 |
} |
| 64 |
#[cfg(feature = "alloc")] |
| 65 |
/// Parses a `Strtab` from `bytes` at `offset` with `len` size as the backing string table, using `delim` as the delimiter. |
| 66 |
/// |
| 67 |
/// Errors if bytes are invalid UTF-8. |
| 68 |
/// Requires `feature = "alloc"` |
| 69 |
pub fn parse(bytes: &'a [u8], offset: usize, len: usize, delim: u8) -> error::Result<Self> { |
| 70 |
let (end, overflow) = offset.overflowing_add(len); |
| 71 |
if overflow || end > bytes.len() { |
| 72 |
return Err(error::Error::Malformed(format!( |
| 73 |
"Strtable size ({}) + offset ({}) is out of bounds for {} #bytes. Overflowed: {}", |
| 74 |
len, |
| 75 |
offset, |
| 76 |
bytes.len(), |
| 77 |
overflow |
| 78 |
))); |
| 79 |
} |
| 80 |
let mut result = Self::from_slice_unparsed(bytes, offset, len, delim); |
| 81 |
let mut i = 0; |
| 82 |
while i < result.bytes.len() { |
| 83 |
let string = get_str(i, result.bytes, result.delim)?; |
| 84 |
result.strings.push((i, string)); |
| 85 |
i += string.len() + 1; |
| 86 |
} |
| 87 |
Ok(result) |
| 88 |
} |
| 89 |
#[cfg(feature = "alloc")] |
| 90 |
/// Parses a `Strtab` with `bytes` as the backing string table, using `delim` as the delimiter between entries. |
| 91 |
/// |
| 92 |
/// Requires `feature = "alloc"` |
| 93 |
pub fn new_preparsed(bytes: &'a [u8], delim: u8) -> error::Result<Self> { |
| 94 |
Self::parse(bytes, 0, bytes.len(), delim) |
| 95 |
} |
| 96 |
#[cfg(feature = "alloc")] |
| 97 |
/// Converts the string table to a vector of parsed strings. |
| 98 |
/// |
| 99 |
/// Note: This method is used to check the parsed contents of `strtab`. |
| 100 |
/// If you want to get the correct contents of `strtab` as `Vec`, use the following example. |
| 101 |
/// |
| 102 |
/// # Examples |
| 103 |
/// ```rust |
| 104 |
/// use goblin::error::Error; |
| 105 |
/// |
| 106 |
/// pub fn show_shdr_strtab(bytes: &[u8]) -> Result<(), Error> { |
| 107 |
/// let elf = goblin::elf::Elf::parse(&bytes)?; |
| 108 |
/// |
| 109 |
/// for section in elf.section_headers { |
| 110 |
/// println!("{}", elf.shdr_strtab.get_at(section.sh_name).unwrap_or("")); |
| 111 |
/// } |
| 112 |
/// |
| 113 |
/// Ok(()) |
| 114 |
/// } |
| 115 |
/// ``` |
| 116 |
/// |
| 117 |
/// Requires `feature = "alloc"` |
| 118 |
pub fn to_vec(&self) -> error::Result<Vec<&'a str>> { |
| 119 |
// Fallback in case `Strtab` was created using `from_slice_unparsed()`. |
| 120 |
if self.strings.is_empty() { |
| 121 |
let mut result = Vec::new(); |
| 122 |
let mut i = 0; |
| 123 |
while i < self.bytes.len() { |
| 124 |
let string = get_str(i, self.bytes, self.delim)?; |
| 125 |
result.push(string); |
| 126 |
i += string.len() + 1; |
| 127 |
} |
| 128 |
return Ok(result); |
| 129 |
} |
| 130 |
Ok(self.strings.iter().map(|&(_key, value)| value).collect()) |
| 131 |
} |
| 132 |
#[cfg(feature = "alloc")] |
| 133 |
/// Safely gets a str reference from the parsed table starting at byte `offset`. |
| 134 |
/// |
| 135 |
/// If the index is out of bounds, `None` is returned. |
| 136 |
/// Requires `feature = "alloc"` |
| 137 |
pub fn get_at(&self, offset: usize) -> Option<&'a str> { |
| 138 |
match self |
| 139 |
.strings |
| 140 |
.binary_search_by_key(&offset, |&(key, _value)| key) |
| 141 |
{ |
| 142 |
Ok(index) => Some(self.strings[index].1), |
| 143 |
Err(index) => { |
| 144 |
if index == 0 { |
| 145 |
return None; |
| 146 |
} |
| 147 |
let (string_begin_offset, entire_string) = self.strings[index - 1]; |
| 148 |
entire_string.get(offset - string_begin_offset..) |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
#[deprecated(since = "0.4.2", note = "Use from_slice_unparsed() instead")] |
| 153 |
/// Construct a strtab from a `ptr`, and a `size`, using `delim` as the delimiter |
| 154 |
/// |
| 155 |
/// # Safety |
| 156 |
/// This function creates a `Strtab` directly from a raw pointer and size |
| 157 |
pub unsafe fn from_raw(ptr: *const u8, len: usize, delim: u8) -> Strtab<'a> { |
| 158 |
Self::from_slice_unparsed(core::slice::from_raw_parts(ptr, len), 0, len, delim) |
| 159 |
} |
| 160 |
#[deprecated(since = "0.4.2", note = "Bad performance, use get_at() instead")] |
| 161 |
#[cfg(feature = "alloc")] |
| 162 |
/// Parses a str reference from the parsed table starting at byte `offset`. |
| 163 |
/// |
| 164 |
/// If the index is out of bounds, `None` is returned. |
| 165 |
/// Requires `feature = "alloc"` |
| 166 |
pub fn get(&self, offset: usize) -> Option<error::Result<&'a str>> { |
| 167 |
if offset >= self.bytes.len() { |
| 168 |
None |
| 169 |
} else { |
| 170 |
Some(get_str(offset, self.bytes, self.delim).map_err(core::convert::Into::into)) |
| 171 |
} |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
impl<'a> fmt::Debug for Strtab<'a> { |
| 176 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 177 |
f.debug_struct("Strtab") |
| 178 |
.field("delim", &self.delim) |
| 179 |
.field("bytes", &str::from_utf8(self.bytes)) |
| 180 |
.finish() |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
impl<'a> Default for Strtab<'a> { |
| 185 |
fn default() -> Self { |
| 186 |
Self { |
| 187 |
delim: ctx::StrCtx::default(), |
| 188 |
bytes: &[], |
| 189 |
#[cfg(feature = "alloc")] |
| 190 |
strings: Vec::new(), |
| 191 |
} |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
impl<'a> Index<usize> for Strtab<'a> { |
| 196 |
type Output = str; |
| 197 |
/// Gets str reference at starting at byte `offset`. |
| 198 |
/// **NB**: this will panic if the underlying bytes are not valid utf8, or the offset is invalid |
| 199 |
#[inline(always)] |
| 200 |
fn index(&self, offset: usize) -> &Self::Output { |
| 201 |
// This can't delegate to get() because get() requires #[cfg(features = "alloc")] |
| 202 |
// It's also slightly less useful than get() because the lifetime -- specified by the Index |
| 203 |
// trait -- matches &self, even though we could return &'a instead |
| 204 |
get_str(offset, self.bytes, self.delim).unwrap() |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
#[test] |
| 209 |
fn as_vec_no_final_null() { |
| 210 |
let strtab = Strtab::new_preparsed(b"\0printf\0memmove\0busta", 0x0).unwrap(); |
| 211 |
let vec = strtab.to_vec().unwrap(); |
| 212 |
assert_eq!(vec.len(), 4); |
| 213 |
assert_eq!(vec, vec!["", "printf", "memmove", "busta"]); |
| 214 |
} |
| 215 |
|
| 216 |
#[test] |
| 217 |
fn as_vec_no_first_null_no_final_null() { |
| 218 |
let strtab = Strtab::new_preparsed(b"printf\0memmove\0busta", 0x0).unwrap(); |
| 219 |
let vec = strtab.to_vec().unwrap(); |
| 220 |
assert_eq!(vec.len(), 3); |
| 221 |
assert_eq!(vec, vec!["printf", "memmove", "busta"]); |
| 222 |
} |
| 223 |
|
| 224 |
#[test] |
| 225 |
fn to_vec_final_null() { |
| 226 |
let strtab = Strtab::new_preparsed(b"\0printf\0memmove\0busta\0", 0x0).unwrap(); |
| 227 |
let vec = strtab.to_vec().unwrap(); |
| 228 |
assert_eq!(vec.len(), 4); |
| 229 |
assert_eq!(vec, vec!["", "printf", "memmove", "busta"]); |
| 230 |
} |
| 231 |
|
| 232 |
#[test] |
| 233 |
fn to_vec_newline_delim() { |
| 234 |
let strtab = Strtab::new_preparsed(b"\nprintf\nmemmove\nbusta\n", b'\n').unwrap(); |
| 235 |
let vec = strtab.to_vec().unwrap(); |
| 236 |
assert_eq!(vec.len(), 4); |
| 237 |
assert_eq!(vec, vec!["", "printf", "memmove", "busta"]); |
| 238 |
} |
| 239 |
|
| 240 |
#[test] |
| 241 |
fn parse_utf8() { |
| 242 |
assert!(match Strtab::new_preparsed(&[0x80, 0x80], b'\n') { |
| 243 |
Err(error::Error::Scroll(scroll::Error::BadInput { |
| 244 |
size: 2, |
| 245 |
msg: "invalid utf8", |
| 246 |
})) => true, |
| 247 |
_ => false, |
| 248 |
}); |
| 249 |
assert!( |
| 250 |
match Strtab::new_preparsed(&[0xC6, 0x92, 0x6F, 0x6F], b'\n') { |
| 251 |
Ok(_) => true, |
| 252 |
_ => false, |
| 253 |
} |
| 254 |
); |
| 255 |
} |
| 256 |
|
| 257 |
#[test] |
| 258 |
fn get_at_utf8() { |
| 259 |
let strtab = Strtab::new_preparsed("\nƒoo\nmemmove\n🅱️usta\n".as_bytes(), b'\n').unwrap(); |
| 260 |
assert_eq!(strtab.get_at(0), Some("")); |
| 261 |
assert_eq!(strtab.get_at(5), Some("")); |
| 262 |
assert_eq!(strtab.get_at(6), Some("memmove")); |
| 263 |
assert_eq!(strtab.get_at(14), Some("\u{1f171}\u{fe0f}usta")); |
| 264 |
assert_eq!(strtab.get_at(16), None); |
| 265 |
assert_eq!(strtab.get_at(18), Some("\u{fe0f}usta")); |
| 266 |
assert_eq!(strtab.get_at(21), Some("usta")); |
| 267 |
assert_eq!(strtab.get_at(25), Some("")); |
| 268 |
assert_eq!(strtab.get_at(26), None); |
| 269 |
} |