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
//! Relocatable objects (`ET_REL`).
use super::consts::{
ELF_NOTE_GNU, EM_X86_64, ET_REL, NT_GNU_PROPERTY_TYPE_0, SHT_GROUP, SHT_NOTE, SHT_REL,
SHT_RELA, SHT_SYMTAB, SHT_SYMTAB_SHNDX, SHT_X86_64_UNWIND,
};
use super::eh_frame::{EhFrameEntry, split_eh_frame};
use super::file::ElfFile;
use super::format::{ElfFormat, RawRecord};
use super::group::Group;
use super::note::{GnuProperties, NoteIter};
use super::reloc::{RelaSlice, RelocationSection, Relocations};
use super::section::{CompressionHeader, SectionHeader};
use super::source::{Source, to_u64};
use super::symbol::{SectionIndex, SymbolTable};
use crate::error::Result;
use crate::target::Architecture;
/// Prefix of the sections holding GCC LTO IR.
pub const GCC_LTO_SECTION_PREFIX: &[u8] = b".gnu.lto_";
/// A parsed relocatable object file.
///
/// Parsing validates the headers, locates the symbol table with its string
/// table and extended index table, and stops: it reads O(number of sections)
/// fixed-size headers and allocates nothing. Section, symbol and relocation
/// counts are known immediately, so later stages can preallocate.
#[derive(Debug)]
pub struct ObjectFile<'a, F: ElfFormat> {
elf: ElfFile<'a, F>,
symbols: SymbolTable<'a, F>,
}
impl<F: ElfFormat> Clone for ObjectFile<'_, F> {
fn clone(&self) -> Self {
*self
}
}
impl<F: ElfFormat> Copy for ObjectFile<'_, F> {}
impl<'a, F: ElfFormat> ObjectFile<'a, F> {
/// Parses a relocatable object.
///
/// # Errors
///
/// Returns `Error::Malformed` if the file is not a valid `ET_REL` ELF file
/// of format `F`, has more than one `SHT_SYMTAB`, or its symbol table,
/// string table or extended index table is out of bounds or badly sized.
pub fn parse(data: &'a [u8], source: Source<'a>) -> Result<Self> {
let elf = ElfFile::<F>::parse(data, source)?;
if elf.header().e_type != ET_REL {
return Err(source.malformed(16, "ELF file type (expected a relocatable object)"));
}
let mut symtab: Option<(u32, SectionHeader)> = None;
let mut shndx: Option<(u32, SectionHeader)> = None;
for (index, hdr) in elf.enumerate_sections() {
match hdr.sh_type {
SHT_SYMTAB => {
if symtab.is_some() {
return Err(source.malformed(
elf.section_header_offset(index),
"symbol table (more than one SHT_SYMTAB)",
));
}
symtab = Some((index, hdr));
}
SHT_SYMTAB_SHNDX if shndx.is_none() => shndx = Some((index, hdr)),
_ => {}
}
}
let symbols = match symtab {
None => SymbolTable::empty(source),
Some((index, hdr)) => {
// Usually the only SHT_SYMTAB_SHNDX; otherwise search for
// the one linked to this symbol table.
let shndx = match shndx {
Some((_, s)) if s.sh_link == index => Some((0, s)),
Some(_) => elf
.enumerate_sections()
.find(|(_, s)| s.sh_type == SHT_SYMTAB_SHNDX && s.sh_link == index),
None => None,
};
elf.symbol_table_with_shndx(index, &hdr, shndx.map(|(_, h)| h))?
}
};
Ok(Self { elf, symbols })
}
/// The underlying ELF file view.
#[inline]
#[must_use]
pub fn elf(&self) -> &ElfFile<'a, F> {
&self.elf
}
/// The whole file.
#[inline]
#[must_use]
pub fn data(&self) -> &'a [u8] {
self.elf.data()
}
/// The file identity used in error messages.
#[inline]
#[must_use]
pub fn source(&self) -> Source<'a> {
self.elf.source()
}
/// The target architecture, if qld knows `e_machine`.
#[inline]
#[must_use]
pub fn architecture(&self) -> Option<Architecture> {
self.elf.architecture()
}
/// Number of sections, including section 0.
#[inline]
#[must_use]
pub fn section_count(&self) -> usize {
self.elf.section_count()
}
/// Decodes section header `index`.
///
/// # Errors
///
/// Returns `Error::Malformed` if `index` is out of range.
#[inline]
pub fn section_header(&self, index: u32) -> Result<SectionHeader> {
self.elf.section_header(index)
}
/// Returns the name of a section.
///
/// # Errors
///
/// Returns `Error::Malformed` if the name cannot be read.
#[inline]
pub fn section_name(&self, header: &SectionHeader) -> Result<&'a [u8]> {
self.elf.section_name(header)
}
/// Returns the contents of a section (empty for `SHT_NOBITS`).
///
/// For `SHF_COMPRESSED` sections this is the compression header followed
/// by the compressed stream; see [`compressed_data`](Self::compressed_data).
///
/// # Errors
///
/// Returns `Error::Malformed` if the contents lie outside the file.
#[inline]
pub fn section_data(&self, header: &SectionHeader) -> Result<&'a [u8]> {
self.elf.section_data(header)
}
/// The symbol table (empty if the object has none).
#[inline]
#[must_use]
pub fn symbols(&self) -> &SymbolTable<'a, F> {
&self.symbols
}
/// Number of symbols, including the null symbol.
#[inline]
#[must_use]
pub fn symbol_count(&self) -> usize {
self.symbols.len()
}
/// Reads the relocations of a `SHT_REL` or `SHT_RELA` section.
///
/// Returns `Ok(None)` for other section types.
///
/// # Errors
///
/// Returns `Error::Malformed` if the contents are out of bounds or not
/// a whole number of entries.
#[inline]
pub fn relocation_section(
&self,
index: u32,
header: &SectionHeader,
) -> Result<Option<RelocationSection<'a, F>>> {
self.elf.relocation_section(index, header)
}
/// Iterates over the `SHT_REL` / `SHT_RELA` sections.
pub fn relocation_sections(
&self,
) -> impl Iterator<Item = Result<RelocationSection<'a, F>>> + use<'a, F> {
let this = *self;
self.elf
.enumerate_sections()
.filter(|(_, hdr)| matches!(hdr.sh_type, SHT_REL | SHT_RELA))
.filter_map(move |(index, hdr)| this.relocation_section(index, &hdr).transpose())
}
/// Maps each section index to the index of the relocation section that
/// targets it, or 0 when none does.
///
/// # Errors
///
/// Returns `Error::Malformed` if a relocation section targets an
/// out-of-range section or a section already targeted by another one.
pub fn relocation_map(&self) -> Result<Vec<u32>> {
let mut map = vec![0u32; self.section_count()];
for (index, hdr) in self.elf.enumerate_sections() {
if !matches!(hdr.sh_type, SHT_REL | SHT_RELA) {
continue;
}
let offset = self.elf.section_header_offset(index);
let slot = usize::try_from(hdr.sh_info)
.ok()
.and_then(|t| map.get_mut(t))
.ok_or_else(|| {
self.source()
.malformed(offset, "relocation section target (out of range)")
})?;
if *slot != 0 {
return Err(self
.source()
.malformed(offset, "relocation section target (duplicate)"));
}
*slot = index;
}
Ok(map)
}
/// Reads the `SHT_GROUP` section `index`.
///
/// Returns `Ok(None)` if the section is not a group.
///
/// # Errors
///
/// Returns `Error::Malformed` if the contents are out of bounds, empty,
/// or not a whole number of 4-byte words.
pub fn group(&self, index: u32, header: &SectionHeader) -> Result<Option<Group<'a, F>>> {
if header.sh_type != SHT_GROUP {
return Ok(None);
}
let words = self
.elf
.section_records::<[u8; 4]>(header, "section group")?;
Group::new(index, *header, words).map(Some).ok_or_else(|| {
self.source()
.malformed(header.sh_offset, "section group (empty)")
})
}
/// Iterates over the `SHT_GROUP` sections.
pub fn groups(&self) -> impl Iterator<Item = Result<Group<'a, F>>> + use<'a, F> {
let this = *self;
self.elf
.enumerate_sections()
.filter(|(_, hdr)| hdr.sh_type == SHT_GROUP)
.filter_map(move |(index, hdr)| this.group(index, &hdr).transpose())
}
/// Returns the signature of a group: the name of its signature symbol, or
/// the name of the section for a section symbol with an empty name.
///
/// # Errors
///
/// Returns `Error::Malformed` if the group does not link to the object's
/// symbol table or the symbol cannot be read.
pub fn group_signature(&self, group: &Group<'a, F>) -> Result<&'a [u8]> {
if group.symtab != self.symbols.section_index() || self.symbols.is_empty() {
return Err(self
.source()
.malformed(group.header.sh_offset, "section group symbol table link"));
}
let index = usize::try_from(group.signature_symbol).unwrap_or(usize::MAX);
let symbol = self.symbols.get(index)?;
if symbol.name.is_empty()
&& symbol.is_section()
&& let SectionIndex::Section(section) = symbol.section
{
let header = self.section_header(section)?;
return self.section_name(&header);
}
Ok(symbol.name)
}
/// Splits a compressed section (`SHF_COMPRESSED`) into its compression
/// header and the compressed stream.
///
/// Returns `Ok(None)` if the section is not compressed.
///
/// # Errors
///
/// Returns `Error::Malformed` if the contents are out of bounds or too
/// small to hold a compression header.
pub fn compressed_data(
&self,
header: &SectionHeader,
) -> Result<Option<(CompressionHeader, &'a [u8])>> {
if !header.is_compressed() {
return Ok(None);
}
let data = self.section_data(header)?;
let (chdrs, _) = F::Chdr::slice_from(data);
let chdr = chdrs.first().ok_or_else(|| {
self.source()
.malformed(header.sh_offset, "compression header (truncated)")
})?;
let rest = data.get(F::Chdr::SIZE..).unwrap_or_default();
Ok(Some((F::decode_chdr(chdr), rest)))
}
/// Merges the GNU properties of every `SHT_NOTE` section named
/// `.note.gnu.property`.
///
/// # Errors
///
/// Returns `Error::Malformed` if a property note is malformed.
pub fn gnu_properties(&self) -> Result<GnuProperties> {
let mut props = GnuProperties::default();
let machine = self.elf.header().e_machine;
for (_, hdr) in self.elf.enumerate_sections() {
if hdr.sh_type != SHT_NOTE || self.section_name(&hdr)? != b".note.gnu.property" {
continue;
}
let data = self.section_data(&hdr)?;
for note in
NoteIter::<F::Endian>::new(data, hdr.sh_addralign, hdr.sh_offset, self.source())
{
let note = note?;
if note.name == ELF_NOTE_GNU && note.n_type == NT_GNU_PROPERTY_TYPE_0 {
let at = hdr.sh_offset.saturating_add(to_u64(note.offset));
props.merge_note::<F::Endian>(
note.desc,
F::WORD_SIZE,
machine,
at,
self.source(),
)?;
}
}
}
Ok(props)
}
/// Whether a section is an `.eh_frame` section (by name, or by the
/// x86-64 `SHT_X86_64_UNWIND` type).
///
/// # Errors
///
/// Returns `Error::Malformed` if the section name cannot be read.
pub fn is_eh_frame(&self, header: &SectionHeader) -> Result<bool> {
if header.sh_type == SHT_X86_64_UNWIND && self.elf.header().e_machine == EM_X86_64 {
return Ok(true);
}
Ok(self.section_name(header)? == b".eh_frame")
}
/// Splits `.eh_frame` section `index` into records, associating the
/// relocations of `relocations` (the relocation section targeting it, if
/// any) with each record.
///
/// # Errors
///
/// Returns `Error::Malformed` for malformed records or relocations; see
/// [`split_eh_frame`].
pub fn eh_frame(
&self,
header: &SectionHeader,
relocations: Option<&RelocationSection<'a, F>>,
) -> Result<Vec<EhFrameEntry<'a>>> {
let data = self.section_data(header)?;
let relocs = relocations.map_or(Relocations::Rela(RelaSlice::default()), |r| r.relocations);
split_eh_frame::<F>(data, relocs, header.sh_offset, self.source())
}
/// Whether the object contains GCC LTO IR (sections named `.gnu.lto_*`).
///
/// # Errors
///
/// Returns `Error::Malformed` if a section name cannot be read.
pub fn has_gcc_lto_ir(&self) -> Result<bool> {
for (_, hdr) in self.elf.enumerate_sections() {
if self.section_name(&hdr)?.starts_with(GCC_LTO_SECTION_PREFIX) {
return Ok(true);
}
}
Ok(false)
}
}