Debian Codegraph @

third_party/rust/goblin/src/elf/mod.rs

raw
1 //! The generic ELF module, which gives access to ELF constants and other helper functions, which are independent of ELF bithood. Also defines an `Elf` struct which implements a unified parser that returns a wrapped `Elf64` or `Elf32` binary.
2 //!
3 //! To access the exact 32-bit or 64-bit versions, use [goblin::elf32::Header](header/header32/struct.Header.html)/[goblin::elf64::Header](header/header64/struct.Header.html), etc., for the various 32/64-bit structs.
4 //!
5 //! # Example
6 //!
7 //! ```rust
8 //! use std::fs::File;
9 //!
10 //! pub fn read (bytes: &[u8]) {
11 //! match goblin::elf::Elf::parse(&bytes) {
12 //! Ok(binary) => {
13 //! let entry = binary.entry;
14 //! for ph in binary.program_headers {
15 //! if ph.p_type == goblin::elf::program_header::PT_LOAD {
16 //! // TODO: you should validate p_filesz before allocating.
17 //! let mut _buf = vec![0u8; ph.p_filesz as usize];
18 //! // read responsibly
19 //! }
20 //! }
21 //! },
22 //! Err(_) => ()
23 //! }
24 //! }
25 //! ```
26 //!
27 //! This will properly access the underlying 32-bit or 64-bit binary automatically. Note that since
28 //! 32-bit binaries typically have shorter 32-bit values in some cases (specifically for addresses and pointer
29 //! values), these values are upcasted to u64/i64s when appropriate.
30 //!
31 //! See [goblin::elf::Elf](struct.Elf.html) for more information.
32 //!
33 //! You are still free to use the specific 32-bit or 64-bit versions by accessing them through `goblin::elf64`, etc., but you will have to parse and/or construct the various components yourself.
34 //! In other words, there is no unified 32/64-bit `Elf` struct.
35 //!
36 //! # Note
37 //! To use the automagic ELF datatype union parser, you _must_ enable/opt-in to the `elf64`, `elf32`, and
38 //! `endian_fd` features if you disable `default`.
39
40 #[macro_use]
41 pub(crate) mod gnu_hash;
42
43 // These are shareable values for the 32/64 bit implementations.
44 //
45 // They are publicly re-exported by the pub-using module
46 pub mod compression_header;
47 pub mod header;
48 pub mod program_header;
49 pub mod section_header;
50 #[macro_use]
51 pub mod sym;
52 pub mod dynamic;
53 #[macro_use]
54 pub mod reloc;
55 pub mod note;
56 #[cfg(all(any(feature = "elf32", feature = "elf64"), feature = "alloc"))]
57 pub mod symver;
58
59 macro_rules! if_sylvan {
60 ($($i:item)*) => ($(
61 #[cfg(all(feature = "elf32", feature = "elf64", feature = "endian_fd"))]
62 $i
63 )*)
64 }
65
66 if_sylvan! {
67 use scroll::{ctx, Pread, Endian};
68 use crate::strtab::Strtab;
69 use crate::error;
70 use crate::container::{Container, Ctx};
71 use alloc::vec::Vec;
72 use core::cmp;
73
74 pub use header::Header;
75 pub use program_header::ProgramHeader;
76 pub use section_header::SectionHeader;
77 pub use sym::Symtab;
78 pub use sym::Sym;
79 pub use dynamic::Dyn;
80 pub use dynamic::Dynamic;
81 pub use reloc::Reloc;
82 pub use reloc::RelocSection;
83 pub use symver::{VersymSection, VerdefSection, VerneedSection};
84
85 pub type ProgramHeaders = Vec<ProgramHeader>;
86 pub type SectionHeaders = Vec<SectionHeader>;
87 pub type ShdrIdx = usize;
88
89 #[derive(Debug)]
90 /// An ELF binary. The underlying data structures are read according to the headers byte order and container size (32 or 64).
91 pub struct Elf<'a> {
92 /// The ELF header, which provides a rudimentary index into the rest of the binary
93 pub header: Header,
94 /// The program headers; they primarily tell the kernel and the dynamic linker
95 /// how to load this binary
96 pub program_headers: ProgramHeaders,
97 /// The sections headers. These are strippable, never count on them being
98 /// here unless you're a static linker!
99 pub section_headers: SectionHeaders,
100 /// The section header string table
101 pub shdr_strtab: Strtab<'a>,
102 /// The string table for the dynamically accessible symbols
103 pub dynstrtab: Strtab<'a>,
104 /// The dynamically accessible symbols, i.e., exports, imports.
105 /// This is what the dynamic linker uses to dynamically load and link your binary,
106 /// or find imported symbols for binaries which dynamically link against your library
107 pub dynsyms: Symtab<'a>,
108 /// The debugging symbol table
109 pub syms: Symtab<'a>,
110 /// The string table for the symbol table
111 pub strtab: Strtab<'a>,
112 /// Contains dynamic linking information, with the _DYNAMIC array + a preprocessed DynamicInfo for that array
113 pub dynamic: Option<Dynamic>,
114 /// The dynamic relocation entries (strings, copy-data, etc.) with an addend
115 pub dynrelas: RelocSection<'a>,
116 /// The dynamic relocation entries without an addend
117 pub dynrels: RelocSection<'a>,
118 /// The plt relocation entries (procedure linkage table). For 32-bit binaries these are usually Rel (no addend)
119 pub pltrelocs: RelocSection<'a>,
120 /// Section relocations by section index (only present if this is a relocatable object file)
121 pub shdr_relocs: Vec<(ShdrIdx, RelocSection<'a>)>,
122 /// The binary's soname, if it has one
123 pub soname: Option<&'a str>,
124 /// The binary's program interpreter (e.g., dynamic linker), if it has one
125 pub interpreter: Option<&'a str>,
126 /// A list of this binary's dynamic libraries it uses, if there are any
127 pub libraries: Vec<&'a str>,
128 /// A list of runtime search paths for this binary's dynamic libraries it uses, if there
129 /// are any. (deprecated)
130 pub rpaths: Vec<&'a str>,
131 /// A list of runtime search paths for this binary's dynamic libraries it uses, if there
132 /// are any.
133 pub runpaths: Vec<&'a str>,
134 /// Whether this is a 64-bit elf or not
135 pub is_64: bool,
136 /// Whether this is a shared object or not
137 pub is_lib: bool,
138 /// The binaries entry point address, if it has one
139 pub entry: u64,
140 /// Whether the binary is little endian or not
141 pub little_endian: bool,
142 /// Contains the symbol version information from the optional section
143 /// [`SHT_GNU_VERSYM`][section_header::SHT_GNU_VERSYM] (GNU extenstion).
144 pub versym : Option<VersymSection<'a>>,
145 /// Contains the version definition information from the optional section
146 /// [`SHT_GNU_VERDEF`][section_header::SHT_GNU_VERDEF] (GNU extenstion).
147 pub verdef : Option<VerdefSection<'a>>,
148 /// Contains the version needed information from the optional section
149 /// [`SHT_GNU_VERNEED`][section_header::SHT_GNU_VERNEED] (GNU extenstion).
150 pub verneed : Option<VerneedSection<'a>>,
151 ctx: Ctx,
152 }
153
154 impl<'a> Elf<'a> {
155 /// Try to iterate notes in PT_NOTE program headers; returns `None` if there aren't any note headers in this binary
156 pub fn iter_note_headers(&self, data: &'a [u8]) -> Option<note::NoteIterator<'a>> {
157 let mut iters = vec![];
158 for phdr in &self.program_headers {
159 if phdr.p_type == program_header::PT_NOTE {
160 let offset = phdr.p_offset as usize;
161 let alignment = phdr.p_align as usize;
162
163 iters.push(note::NoteDataIterator {
164 data,
165 offset,
166 size: offset.saturating_add(phdr.p_filesz as usize),
167 ctx: (alignment, self.ctx)
168 });
169 }
170 }
171
172 if iters.is_empty() {
173 None
174 } else {
175 Some(note::NoteIterator {
176 iters: iters,
177 index: 0,
178 })
179 }
180 }
181 /// Try to iterate notes in SHT_NOTE sections; returns `None` if there aren't any note sections in this binary
182 ///
183 /// If a section_name is given, only the section with the according name is iterated.
184 pub fn iter_note_sections(
185 &self,
186 data: &'a [u8],
187 section_name: Option<&str>,
188 ) -> Option<note::NoteIterator<'a>> {
189 let mut iters = vec![];
190 for sect in &self.section_headers {
191 if sect.sh_type != section_header::SHT_NOTE {
192 continue;
193 }
194
195 if section_name.is_some() && self.shdr_strtab.get_at(sect.sh_name) != section_name {
196 continue;
197 }
198
199 let offset = sect.sh_offset as usize;
200 let alignment = sect.sh_addralign as usize;
201 iters.push(note::NoteDataIterator {
202 data,
203 offset,
204 size: offset.saturating_add(sect.sh_size as usize),
205 ctx: (alignment, self.ctx)
206 });
207 }
208
209 if iters.is_empty() {
210 None
211 } else {
212 Some(note::NoteIterator {
213 iters: iters,
214 index: 0,
215 })
216 }
217 }
218 pub fn is_object_file(&self) -> bool {
219 self.header.e_type == header::ET_REL
220 }
221
222 /// Parses the contents to get the Header only. This `bytes` buffer should contain at least the length for parsing Header.
223 pub fn parse_header(bytes: &'a [u8]) -> error::Result<Header> {
224 bytes.pread::<Header>(0)
225 }
226
227 /// Lazy parse the ELF contents. This function mainly just assembles an Elf struct. Once we have the struct, we can choose to parse whatever we want.
228 pub fn lazy_parse(header: Header) -> error::Result<Self> {
229 let misc = parse_misc(&header)?;
230
231 Ok(Elf {
232 header,
233 program_headers: vec![],
234 section_headers: Default::default(),
235 shdr_strtab: Default::default(),
236 dynamic: None,
237 dynsyms: Default::default(),
238 dynstrtab: Strtab::default(),
239 syms: Default::default(),
240 strtab: Default::default(),
241 dynrelas: Default::default(),
242 dynrels: Default::default(),
243 pltrelocs: Default::default(),
244 shdr_relocs: Default::default(),
245 soname: None,
246 interpreter: None,
247 libraries: vec![],
248 rpaths: vec![],
249 runpaths: vec![],
250 is_64: misc.is_64,
251 is_lib: misc.is_lib,
252 entry: misc.entry,
253 little_endian: misc.little_endian,
254 ctx: misc.ctx,
255 versym: None,
256 verdef: None,
257 verneed: None,
258 })
259 }
260
261 /// Parses the contents of the byte stream in `bytes`, and maybe returns a unified binary
262 pub fn parse(bytes: &'a [u8]) -> error::Result<Self> {
263 let header = Self::parse_header(bytes)?;
264 let misc = parse_misc(&header)?;
265 let ctx = misc.ctx;
266
267 let program_headers = ProgramHeader::parse(bytes, header.e_phoff as usize, header.e_phnum as usize, ctx)?;
268
269 let mut interpreter = None;
270 for ph in &program_headers {
271 if ph.p_type == program_header::PT_INTERP && ph.p_filesz != 0 {
272 let count = (ph.p_filesz - 1) as usize;
273 let offset = ph.p_offset as usize;
274 interpreter = bytes.pread_with::<&str>(offset, ::scroll::ctx::StrCtx::Length(count)).ok();
275 }
276 }
277
278 let section_headers = SectionHeader::parse(bytes, header.e_shoff as usize, header.e_shnum as usize, ctx)?;
279
280 let get_strtab = |section_headers: &[SectionHeader], mut section_idx: usize| {
281 if section_idx == section_header::SHN_XINDEX as usize {
282 if section_headers.is_empty() {
283 return Ok(Strtab::default())
284 }
285 section_idx = section_headers[0].sh_link as usize;
286 }
287
288 if section_idx >= section_headers.len() {
289 // FIXME: warn! here
290 Ok(Strtab::default())
291 } else {
292 let shdr = &section_headers[section_idx];
293 shdr.check_size(bytes.len())?;
294 Strtab::parse(bytes, shdr.sh_offset as usize, shdr.sh_size as usize, 0x0)
295 }
296 };
297
298 let strtab_idx = header.e_shstrndx as usize;
299 let shdr_strtab = get_strtab(&section_headers, strtab_idx)?;
300
301 let mut syms = Symtab::default();
302 let mut strtab = Strtab::default();
303 if let Some(shdr) = section_headers.iter().rfind(|shdr| shdr.sh_type as u32 == section_header::SHT_SYMTAB) {
304 let size = shdr.sh_entsize;
305 let count = if size == 0 { 0 } else { shdr.sh_size / size };
306 syms = Symtab::parse(bytes, shdr.sh_offset as usize, count as usize, ctx)?;
307 strtab = get_strtab(&section_headers, shdr.sh_link as usize)?;
308 }
309
310 let mut is_pie = false;
311 let mut soname = None;
312 let mut libraries = vec![];
313 let mut rpaths = vec![];
314 let mut runpaths = vec![];
315 let mut dynsyms = Symtab::default();
316 let mut dynrelas = RelocSection::default();
317 let mut dynrels = RelocSection::default();
318 let mut pltrelocs = RelocSection::default();
319 let mut dynstrtab = Strtab::default();
320 let dynamic = Dynamic::parse(bytes, &program_headers, ctx)?;
321 if let Some(ref dynamic) = dynamic {
322 let dyn_info = &dynamic.info;
323
324 is_pie = dyn_info.flags_1 & dynamic::DF_1_PIE != 0;
325 dynstrtab = Strtab::parse(bytes,
326 dyn_info.strtab,
327 dyn_info.strsz,
328 0x0)?;
329
330 if dyn_info.soname != 0 {
331 // FIXME: warn! here
332 soname = dynstrtab.get_at(dyn_info.soname);
333 }
334 if dyn_info.needed_count > 0 {
335 libraries = dynamic.get_libraries(&dynstrtab);
336 }
337 for dyn_ in &dynamic.dyns {
338 if dyn_.d_tag == dynamic::DT_RPATH {
339 if let Some(path) = dynstrtab.get_at(dyn_.d_val as usize) {
340 rpaths.push(path);
341 }
342 } else if dyn_.d_tag == dynamic::DT_RUNPATH {
343 if let Some(path) = dynstrtab.get_at(dyn_.d_val as usize) {
344 runpaths.push(path);
345 }
346 }
347 }
348 // parse the dynamic relocations
349 dynrelas = RelocSection::parse(bytes, dyn_info.rela, dyn_info.relasz, true, ctx)?;
350 dynrels = RelocSection::parse(bytes, dyn_info.rel, dyn_info.relsz, false, ctx)?;
351 let is_rela = dyn_info.pltrel as u64 == dynamic::DT_RELA;
352 pltrelocs = RelocSection::parse(bytes, dyn_info.jmprel, dyn_info.pltrelsz, is_rela, ctx)?;
353
354 let mut num_syms = if let Some(gnu_hash) = dyn_info.gnu_hash {
355 gnu_hash_len(bytes, gnu_hash as usize, ctx)?
356 } else if let Some(hash) = dyn_info.hash {
357 hash_len(bytes, hash as usize, header.e_machine, ctx)?
358 } else {
359 0
360 };
361 let max_reloc_sym = dynrelas.iter()
362 .chain(dynrels.iter())
363 .chain(pltrelocs.iter())
364 .fold(0, |num, reloc| cmp::max(num, reloc.r_sym));
365 if max_reloc_sym != 0 {
366 num_syms = cmp::max(num_syms, max_reloc_sym + 1);
367 }
368 dynsyms = Symtab::parse(bytes, dyn_info.symtab, num_syms, ctx)?;
369 }
370
371 let mut shdr_relocs = vec![];
372 for (idx, section) in section_headers.iter().enumerate() {
373 let is_rela = section.sh_type == section_header::SHT_RELA;
374 if is_rela || section.sh_type == section_header::SHT_REL {
375 section.check_size(bytes.len())?;
376 let sh_relocs = RelocSection::parse(bytes, section.sh_offset as usize, section.sh_size as usize, is_rela, ctx)?;
377 shdr_relocs.push((idx, sh_relocs));
378 }
379 }
380
381 let versym = symver::VersymSection::parse(bytes, &section_headers, ctx)?;
382 let verdef = symver::VerdefSection::parse(bytes, &section_headers, ctx)?;
383 let verneed = symver::VerneedSection::parse(bytes, &section_headers, ctx)?;
384
385 let is_lib = misc.is_lib && !is_pie;
386
387 Ok(Elf {
388 header,
389 program_headers,
390 section_headers,
391 shdr_strtab,
392 dynamic,
393 dynsyms,
394 dynstrtab,
395 syms,
396 strtab,
397 dynrelas,
398 dynrels,
399 pltrelocs,
400 shdr_relocs,
401 soname,
402 interpreter,
403 libraries,
404 rpaths,
405 runpaths,
406 is_64: misc.is_64,
407 is_lib,
408 entry: misc.entry,
409 little_endian: misc.little_endian,
410 ctx: ctx,
411 versym,
412 verdef,
413 verneed,
414 })
415 }
416 }
417
418 impl<'a> ctx::TryFromCtx<'a, (usize, Endian)> for Elf<'a> {
419 type Error = crate::error::Error;
420 fn try_from_ctx(src: &'a [u8], (_, _): (usize, Endian)) -> Result<(Elf<'a>, usize), Self::Error> {
421 let elf = Elf::parse(src)?;
422 Ok((elf, src.len()))
423 }
424 }
425
426 fn gnu_hash_len(bytes: &[u8], offset: usize, ctx: Ctx) -> error::Result<usize> {
427 let buckets_num = bytes.pread_with::<u32>(offset, ctx.le)? as usize;
428 let min_chain = bytes.pread_with::<u32>(offset + 4, ctx.le)? as usize;
429 let bloom_size = bytes.pread_with::<u32>(offset + 8, ctx.le)? as usize;
430 // We could handle min_chain==0 if we really had to, but it shouldn't happen.
431 if buckets_num == 0 || min_chain == 0 || bloom_size == 0 {
432 return Err(error::Error::Malformed(format!("Invalid DT_GNU_HASH: buckets_num={} min_chain={} bloom_size={}",
433 buckets_num, min_chain, bloom_size)));
434 }
435 // Find the last bucket.
436 let buckets_offset = offset + 16 + bloom_size * if ctx.container.is_big() { 8 } else { 4 };
437 let mut max_chain = 0;
438 for bucket in 0..buckets_num {
439 let chain = bytes.pread_with::<u32>(buckets_offset + bucket * 4, ctx.le)? as usize;
440 if max_chain < chain {
441 max_chain = chain;
442 }
443 }
444 if max_chain < min_chain {
445 return Ok(0);
446 }
447 // Find the last chain within the bucket.
448 let mut chain_offset = buckets_offset + buckets_num * 4 + (max_chain - min_chain) * 4;
449 loop {
450 let hash = bytes.pread_with::<u32>(chain_offset, ctx.le)?;
451 max_chain += 1;
452 chain_offset += 4;
453 if hash & 1 != 0 {
454 return Ok(max_chain);
455 }
456 }
457 }
458
459 fn hash_len(bytes: &[u8], offset: usize, machine: u16, ctx: Ctx) -> error::Result<usize> {
460 // Based on readelf code.
461 let nchain = if (machine == header::EM_FAKE_ALPHA || machine == header::EM_S390) && ctx.container.is_big() {
462 bytes.pread_with::<u64>(offset.saturating_add(4), ctx.le)? as usize
463 } else {
464 bytes.pread_with::<u32>(offset.saturating_add(4), ctx.le)? as usize
465 };
466 Ok(nchain)
467 }
468
469 struct Misc {
470 is_64: bool,
471 is_lib: bool,
472 entry: u64,
473 little_endian: bool,
474 ctx: Ctx,
475 }
476
477 fn parse_misc(header: &Header) -> error::Result<Misc> {
478 let entry = header.e_entry as usize;
479 let is_lib = header.e_type == header::ET_DYN;
480 let is_lsb = header.e_ident[header::EI_DATA] == header::ELFDATA2LSB;
481 let endianness = scroll::Endian::from(is_lsb);
482 let class = header.e_ident[header::EI_CLASS];
483 if class != header::ELFCLASS64 && class != header::ELFCLASS32 {
484 return Err(error::Error::Malformed(format!("Unknown values in ELF ident header: class: {} endianness: {}",
485 class,
486 header.e_ident[header::EI_DATA])));
487 }
488 let is_64 = class == header::ELFCLASS64;
489 let container = if is_64 { Container::Big } else { Container::Little };
490 let ctx = Ctx::new(container, endianness);
491
492 Ok(Misc{
493 is_64,
494 is_lib,
495 entry: entry as u64,
496 little_endian:is_lsb,
497 ctx,
498 })
499 }
500 }
501
502 #[cfg(test)]
503 mod tests {
504 use super::*;
505
506 #[test]
507 fn parse_crt1_64bit() {
508 let crt1: Vec<u8> = include!("../../etc/crt1.rs");
509 match Elf::parse(&crt1) {
510 Ok(binary) => {
511 assert!(binary.is_64);
512 assert!(!binary.is_lib);
513 assert_eq!(binary.entry, 0);
514 assert!(binary.syms.get(1000).is_none());
515 assert!(binary.syms.get(5).is_some());
516 let syms = binary.syms.to_vec();
517 assert!(!binary.section_headers.is_empty());
518 for (i, sym) in syms.iter().enumerate() {
519 if i == 11 {
520 let symtab = binary.strtab;
521 println!("sym: {:?}", &sym);
522 assert_eq!(&symtab[sym.st_name], "_start");
523 break;
524 }
525 }
526 assert!(!syms.is_empty());
527 }
528 Err(err) => {
529 panic!("failed: {}", err);
530 }
531 }
532 }
533
534 #[test]
535 fn parse_crt1_32bit() {
536 let crt1: Vec<u8> = include!("../../etc/crt132.rs");
537 match Elf::parse(&crt1) {
538 Ok(binary) => {
539 assert!(!binary.is_64);
540 assert!(!binary.is_lib);
541 assert_eq!(binary.entry, 0);
542 assert!(binary.syms.get(1000).is_none());
543 assert!(binary.syms.get(5).is_some());
544 let syms = binary.syms.to_vec();
545 assert!(!binary.section_headers.is_empty());
546 for (i, sym) in syms.iter().enumerate() {
547 if i == 11 {
548 let symtab = binary.strtab;
549 println!("sym: {:?}", &sym);
550 assert_eq!(&symtab[sym.st_name], "__libc_csu_fini");
551 break;
552 }
553 }
554 assert!(!syms.is_empty());
555 }
556 Err(err) => {
557 panic!("failed: {}", err);
558 }
559 }
560 }
561
562 // See https://github.com/m4b/goblin/issues/257
563 #[test]
564 #[allow(unused)]
565 fn no_use_statement_conflict() {
566 use crate::elf::section_header::*;
567 use crate::elf::*;
568
569 fn f(_: SectionHeader) {}
570 }
571 }