| 1 |
//! This module provides a [`Builder`] for reading, modifying, and then writing ELF files. |
| 2 |
use alloc::vec::Vec; |
| 3 |
use core::convert::TryInto; |
| 4 |
use core::fmt; |
| 5 |
use core::marker::PhantomData; |
| 6 |
#[cfg(not(feature = "std"))] |
| 7 |
use hashbrown::HashMap; |
| 8 |
#[cfg(feature = "std")] |
| 9 |
use std::collections::HashMap; |
| 10 |
|
| 11 |
use crate::build::{ByteString, Bytes, Error, Id, IdPrivate, Item, Result, Table}; |
| 12 |
use crate::elf; |
| 13 |
use crate::read::elf::{Dyn, FileHeader, ProgramHeader, Rela, SectionHeader, Sym}; |
| 14 |
use crate::read::{self, FileKind, ReadRef}; |
| 15 |
use crate::write; |
| 16 |
use crate::Endianness; |
| 17 |
|
| 18 |
/// A builder for reading, modifying, and then writing ELF files. |
| 19 |
/// |
| 20 |
/// Public fields are available for modifying the values that will be written. |
| 21 |
/// Methods are available to add elements to tables, and elements can be deleted |
| 22 |
/// from tables by setting the `delete` field in the element. |
| 23 |
#[derive(Debug)] |
| 24 |
pub struct Builder<'data> { |
| 25 |
/// The endianness. |
| 26 |
/// |
| 27 |
/// Used to set the data encoding when writing the ELF file. |
| 28 |
pub endian: Endianness, |
| 29 |
/// Whether file is 64-bit. |
| 30 |
/// |
| 31 |
/// Use to set the file class when writing the ELF file. |
| 32 |
pub is_64: bool, |
| 33 |
/// The alignment of [`elf::PT_LOAD`] segments. |
| 34 |
/// |
| 35 |
/// This is an informational field and is not used when writing the ELF file. |
| 36 |
/// It can optionally be used when calling [`Segments::add_load_segment`]. |
| 37 |
/// |
| 38 |
/// It is determined heuristically when reading the ELF file. Currently, |
| 39 |
/// if all load segments have the same alignment, that alignment is used, |
| 40 |
/// otherwise it is set to 1. |
| 41 |
pub load_align: u64, |
| 42 |
/// The file header. |
| 43 |
pub header: Header, |
| 44 |
/// The segment table. |
| 45 |
pub segments: Segments<'data>, |
| 46 |
/// The section table. |
| 47 |
pub sections: Sections<'data>, |
| 48 |
/// The symbol table. |
| 49 |
pub symbols: Symbols<'data>, |
| 50 |
/// The dynamic symbol table. |
| 51 |
pub dynamic_symbols: DynamicSymbols<'data>, |
| 52 |
/// The base version for the GNU version definitions. |
| 53 |
/// |
| 54 |
/// This will be written as a version definition with index 1. |
| 55 |
pub version_base: Option<ByteString<'data>>, |
| 56 |
/// The GNU version definitions and dependencies. |
| 57 |
pub versions: Versions<'data>, |
| 58 |
/// The filenames used in the GNU version definitions. |
| 59 |
pub version_files: VersionFiles<'data>, |
| 60 |
/// The bucket count parameter for the hash table. |
| 61 |
pub hash_bucket_count: u32, |
| 62 |
/// The bloom shift parameter for the GNU hash table. |
| 63 |
pub gnu_hash_bloom_shift: u32, |
| 64 |
/// The bloom count parameter for the GNU hash table. |
| 65 |
pub gnu_hash_bloom_count: u32, |
| 66 |
/// The bucket count parameter for the GNU hash table. |
| 67 |
pub gnu_hash_bucket_count: u32, |
| 68 |
marker: PhantomData<()>, |
| 69 |
} |
| 70 |
|
| 71 |
impl<'data> Builder<'data> { |
| 72 |
/// Create a new ELF builder. |
| 73 |
pub fn new(endian: Endianness, is_64: bool) -> Self { |
| 74 |
Self { |
| 75 |
endian, |
| 76 |
is_64, |
| 77 |
load_align: 1, |
| 78 |
header: Header::default(), |
| 79 |
segments: Segments::new(), |
| 80 |
sections: Sections::new(), |
| 81 |
symbols: Symbols::new(), |
| 82 |
dynamic_symbols: Symbols::new(), |
| 83 |
version_base: None, |
| 84 |
versions: Versions::new(), |
| 85 |
version_files: VersionFiles::new(), |
| 86 |
hash_bucket_count: 0, |
| 87 |
gnu_hash_bloom_shift: 0, |
| 88 |
gnu_hash_bloom_count: 0, |
| 89 |
gnu_hash_bucket_count: 0, |
| 90 |
marker: PhantomData, |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
/// Read the ELF file from file data. |
| 95 |
pub fn read<R: ReadRef<'data>>(data: R) -> Result<Self> { |
| 96 |
match FileKind::parse(data)? { |
| 97 |
FileKind::Elf32 => Self::read32(data), |
| 98 |
FileKind::Elf64 => Self::read64(data), |
| 99 |
#[allow(unreachable_patterns)] |
| 100 |
_ => Err(Error::new("Not an ELF file")), |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
/// Read a 32-bit ELF file from file data. |
| 105 |
pub fn read32<R: ReadRef<'data>>(data: R) -> Result<Self> { |
| 106 |
Self::read_file::<elf::FileHeader32<Endianness>, R>(data) |
| 107 |
} |
| 108 |
|
| 109 |
/// Read a 64-bit ELF file from file data. |
| 110 |
pub fn read64<R: ReadRef<'data>>(data: R) -> Result<Self> { |
| 111 |
Self::read_file::<elf::FileHeader64<Endianness>, R>(data) |
| 112 |
} |
| 113 |
|
| 114 |
fn read_file<Elf, R>(data: R) -> Result<Self> |
| 115 |
where |
| 116 |
Elf: FileHeader<Endian = Endianness>, |
| 117 |
R: ReadRef<'data>, |
| 118 |
{ |
| 119 |
let header = Elf::parse(data)?; |
| 120 |
let endian = header.endian()?; |
| 121 |
let is_mips64el = header.is_mips64el(endian); |
| 122 |
let section_strings_index = header.section_strings_index(endian, data)?; |
| 123 |
let segments = header.program_headers(endian, data)?; |
| 124 |
let sections = header.sections(endian, data)?; |
| 125 |
let symbols = sections.symbols(endian, data, elf::SHT_SYMTAB)?; |
| 126 |
let dynamic_symbols = sections.symbols(endian, data, elf::SHT_DYNSYM)?; |
| 127 |
|
| 128 |
let mut builder = Builder { |
| 129 |
endian, |
| 130 |
is_64: header.is_type_64(), |
| 131 |
load_align: 0, |
| 132 |
header: Header { |
| 133 |
os_abi: header.e_ident().os_abi, |
| 134 |
abi_version: header.e_ident().abi_version, |
| 135 |
e_type: header.e_type(endian), |
| 136 |
e_machine: header.e_machine(endian), |
| 137 |
e_entry: header.e_entry(endian).into(), |
| 138 |
e_flags: header.e_flags(endian), |
| 139 |
e_phoff: header.e_phoff(endian).into(), |
| 140 |
}, |
| 141 |
segments: Segments::new(), |
| 142 |
sections: Sections::new(), |
| 143 |
symbols: Symbols::new(), |
| 144 |
dynamic_symbols: Symbols::new(), |
| 145 |
version_base: None, |
| 146 |
versions: Versions::new(), |
| 147 |
version_files: VersionFiles::new(), |
| 148 |
hash_bucket_count: 0, |
| 149 |
gnu_hash_bloom_shift: 0, |
| 150 |
gnu_hash_bloom_count: 0, |
| 151 |
gnu_hash_bucket_count: 0, |
| 152 |
marker: PhantomData, |
| 153 |
}; |
| 154 |
|
| 155 |
for segment in segments { |
| 156 |
if segment.p_type(endian) == elf::PT_LOAD { |
| 157 |
let p_align = segment.p_align(endian).into(); |
| 158 |
if builder.load_align == 0 { |
| 159 |
builder.load_align = p_align; |
| 160 |
} else if builder.load_align != p_align { |
| 161 |
builder.load_align = 1; |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
let id = builder.segments.next_id(); |
| 166 |
builder.segments.push(Segment { |
| 167 |
id, |
| 168 |
delete: false, |
| 169 |
p_type: segment.p_type(endian), |
| 170 |
p_flags: segment.p_flags(endian), |
| 171 |
p_offset: segment.p_offset(endian).into(), |
| 172 |
p_vaddr: segment.p_vaddr(endian).into(), |
| 173 |
p_paddr: segment.p_paddr(endian).into(), |
| 174 |
p_filesz: segment.p_filesz(endian).into(), |
| 175 |
p_memsz: segment.p_memsz(endian).into(), |
| 176 |
p_align: segment.p_align(endian).into(), |
| 177 |
sections: Vec::new(), |
| 178 |
marker: PhantomData, |
| 179 |
}); |
| 180 |
} |
| 181 |
if builder.load_align == 0 { |
| 182 |
builder.load_align = 1; |
| 183 |
} |
| 184 |
|
| 185 |
for (index, section) in sections.enumerate().skip(1) { |
| 186 |
let id = SectionId(index.0 - 1); |
| 187 |
let relocations = if let Some((rels, link)) = section.rel(endian, data)? { |
| 188 |
Self::read_relocations( |
| 189 |
index, |
| 190 |
endian, |
| 191 |
is_mips64el, |
| 192 |
section, |
| 193 |
rels, |
| 194 |
link, |
| 195 |
&symbols, |
| 196 |
&dynamic_symbols, |
| 197 |
)? |
| 198 |
} else if let Some((rels, link)) = section.rela(endian, data)? { |
| 199 |
Self::read_relocations( |
| 200 |
index, |
| 201 |
endian, |
| 202 |
is_mips64el, |
| 203 |
section, |
| 204 |
rels, |
| 205 |
link, |
| 206 |
&symbols, |
| 207 |
&dynamic_symbols, |
| 208 |
)? |
| 209 |
} else { |
| 210 |
SectionData::Data(Bytes::default()) |
| 211 |
}; |
| 212 |
if let Some(hash) = section.hash_header(endian, data)? { |
| 213 |
builder.hash_bucket_count = hash.bucket_count.get(endian); |
| 214 |
} |
| 215 |
if let Some(hash) = section.gnu_hash_header(endian, data)? { |
| 216 |
builder.gnu_hash_bloom_shift = hash.bloom_shift.get(endian); |
| 217 |
builder.gnu_hash_bloom_count = hash.bloom_count.get(endian); |
| 218 |
builder.gnu_hash_bucket_count = hash.bucket_count.get(endian); |
| 219 |
} |
| 220 |
let data = match section.sh_type(endian) { |
| 221 |
elf::SHT_NOBITS => SectionData::UninitializedData(section.sh_size(endian).into()), |
| 222 |
elf::SHT_PROGBITS |
| 223 |
| elf::SHT_INIT_ARRAY |
| 224 |
| elf::SHT_FINI_ARRAY |
| 225 |
| elf::SHT_PREINIT_ARRAY => SectionData::Data(section.data(endian, data)?.into()), |
| 226 |
elf::SHT_REL | elf::SHT_RELA => relocations, |
| 227 |
elf::SHT_SYMTAB => { |
| 228 |
if index == symbols.section() { |
| 229 |
SectionData::Symbol |
| 230 |
} else { |
| 231 |
return Err(Error(format!( |
| 232 |
"Unsupported SHT_SYMTAB section at index {}", |
| 233 |
index |
| 234 |
))); |
| 235 |
} |
| 236 |
} |
| 237 |
elf::SHT_SYMTAB_SHNDX => { |
| 238 |
if index == symbols.shndx_section() { |
| 239 |
SectionData::SymbolSectionIndex |
| 240 |
} else { |
| 241 |
return Err(Error(format!( |
| 242 |
"Unsupported SHT_SYMTAB_SHNDX section at index {}", |
| 243 |
index |
| 244 |
))); |
| 245 |
} |
| 246 |
} |
| 247 |
elf::SHT_DYNSYM => { |
| 248 |
if index == dynamic_symbols.section() { |
| 249 |
SectionData::DynamicSymbol |
| 250 |
} else { |
| 251 |
return Err(Error(format!( |
| 252 |
"Unsupported SHT_DYNSYM section at index {}", |
| 253 |
index |
| 254 |
))); |
| 255 |
} |
| 256 |
} |
| 257 |
elf::SHT_STRTAB => { |
| 258 |
if index == symbols.string_section() { |
| 259 |
SectionData::String |
| 260 |
} else if index == dynamic_symbols.string_section() { |
| 261 |
SectionData::DynamicString |
| 262 |
} else if index == section_strings_index { |
| 263 |
SectionData::SectionString |
| 264 |
} else { |
| 265 |
return Err(Error(format!( |
| 266 |
"Unsupported SHT_STRTAB section at index {}", |
| 267 |
index |
| 268 |
))); |
| 269 |
} |
| 270 |
} |
| 271 |
elf::SHT_NOTE => SectionData::Note(section.data(endian, data)?.into()), |
| 272 |
elf::SHT_DYNAMIC => { |
| 273 |
let (dyns, link) = section.dynamic(endian, data)?.unwrap(); |
| 274 |
let dynamic_strings = sections.strings(endian, data, link)?; |
| 275 |
Self::read_dynamics::<Elf, _>(endian, dyns, dynamic_strings)? |
| 276 |
} |
| 277 |
elf::SHT_GNU_ATTRIBUTES => { |
| 278 |
let attributes = section.attributes(endian, data)?; |
| 279 |
Self::read_attributes(index, attributes, sections.len(), symbols.len())? |
| 280 |
} |
| 281 |
elf::SHT_HASH => SectionData::Hash, |
| 282 |
elf::SHT_GNU_HASH => SectionData::GnuHash, |
| 283 |
elf::SHT_GNU_VERSYM => SectionData::GnuVersym, |
| 284 |
elf::SHT_GNU_VERDEF => SectionData::GnuVerdef, |
| 285 |
elf::SHT_GNU_VERNEED => SectionData::GnuVerneed, |
| 286 |
other => match (builder.header.e_machine, other) { |
| 287 |
(elf::EM_ARM, elf::SHT_ARM_ATTRIBUTES) |
| 288 |
| (elf::EM_AARCH64, elf::SHT_AARCH64_ATTRIBUTES) |
| 289 |
| (elf::EM_CSKY, elf::SHT_CSKY_ATTRIBUTES) |
| 290 |
| (elf::EM_RISCV, elf::SHT_RISCV_ATTRIBUTES) => { |
| 291 |
let attributes = section.attributes(endian, data)?; |
| 292 |
Self::read_attributes(index, attributes, sections.len(), symbols.len())? |
| 293 |
} |
| 294 |
// Some section types that we can't parse but that are safe to copy. |
| 295 |
// Lots of types missing, add as needed. We can't default to copying |
| 296 |
// everything because some types are not safe to copy. |
| 297 |
(elf::EM_ARM, elf::SHT_ARM_EXIDX) |
| 298 |
| (elf::EM_IA_64, elf::SHT_IA_64_UNWIND) |
| 299 |
| (elf::EM_MIPS, elf::SHT_MIPS_REGINFO) |
| 300 |
| (elf::EM_MIPS, elf::SHT_MIPS_DWARF) |
| 301 |
| (elf::EM_X86_64, elf::SHT_X86_64_UNWIND) => { |
| 302 |
SectionData::Data(section.data(endian, data)?.into()) |
| 303 |
} |
| 304 |
_ => return Err(Error(format!("Unsupported section type {:x}", other))), |
| 305 |
}, |
| 306 |
}; |
| 307 |
let sh_flags = section.sh_flags(endian).into(); |
| 308 |
let sh_link = section.sh_link(endian); |
| 309 |
let sh_link_section = if sh_link == 0 { |
| 310 |
None |
| 311 |
} else { |
| 312 |
if sh_link as usize >= sections.len() { |
| 313 |
return Err(Error(format!( |
| 314 |
"Invalid sh_link {} in section at index {}", |
| 315 |
sh_link, index |
| 316 |
))); |
| 317 |
} |
| 318 |
Some(SectionId(sh_link as usize - 1)) |
| 319 |
}; |
| 320 |
let sh_info = section.sh_info(endian); |
| 321 |
let sh_info_section = if sh_info == 0 || sh_flags & u64::from(elf::SHF_INFO_LINK) == 0 { |
| 322 |
None |
| 323 |
} else { |
| 324 |
if sh_info as usize >= sections.len() { |
| 325 |
return Err(Error(format!( |
| 326 |
"Invalid sh_info link {} in section at index {}", |
| 327 |
sh_info, index |
| 328 |
))); |
| 329 |
} |
| 330 |
Some(SectionId(sh_info as usize - 1)) |
| 331 |
}; |
| 332 |
let sh_flags = section.sh_flags(endian).into(); |
| 333 |
let sh_addr = section.sh_addr(endian).into(); |
| 334 |
if sh_flags & u64::from(elf::SHF_ALLOC) != 0 { |
| 335 |
for segment in &mut builder.segments { |
| 336 |
if segment.contains_address(sh_addr) { |
| 337 |
segment.sections.push(id); |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
builder.sections.push(Section { |
| 342 |
id, |
| 343 |
delete: false, |
| 344 |
name: sections.section_name(endian, section)?.into(), |
| 345 |
sh_type: section.sh_type(endian), |
| 346 |
sh_flags, |
| 347 |
sh_addr, |
| 348 |
sh_offset: section.sh_offset(endian).into(), |
| 349 |
sh_size: section.sh_size(endian).into(), |
| 350 |
sh_link_section, |
| 351 |
sh_info, |
| 352 |
sh_info_section, |
| 353 |
sh_addralign: section.sh_addralign(endian).into(), |
| 354 |
sh_entsize: section.sh_entsize(endian).into(), |
| 355 |
data, |
| 356 |
}); |
| 357 |
} |
| 358 |
|
| 359 |
Self::read_symbols( |
| 360 |
endian, |
| 361 |
&symbols, |
| 362 |
&mut builder.symbols, |
| 363 |
builder.sections.len(), |
| 364 |
)?; |
| 365 |
Self::read_symbols( |
| 366 |
endian, |
| 367 |
&dynamic_symbols, |
| 368 |
&mut builder.dynamic_symbols, |
| 369 |
builder.sections.len(), |
| 370 |
)?; |
| 371 |
builder.read_gnu_versions(endian, data, §ions, &dynamic_symbols)?; |
| 372 |
|
| 373 |
Ok(builder) |
| 374 |
} |
| 375 |
|
| 376 |
#[allow(clippy::too_many_arguments)] |
| 377 |
fn read_relocations<Elf, Rel, R>( |
| 378 |
index: read::SectionIndex, |
| 379 |
endian: Elf::Endian, |
| 380 |
is_mips64el: bool, |
| 381 |
section: &'data Elf::SectionHeader, |
| 382 |
rels: &'data [Rel], |
| 383 |
link: read::SectionIndex, |
| 384 |
symbols: &read::elf::SymbolTable<'data, Elf, R>, |
| 385 |
dynamic_symbols: &read::elf::SymbolTable<'data, Elf, R>, |
| 386 |
) -> Result<SectionData<'data>> |
| 387 |
where |
| 388 |
Elf: FileHeader<Endian = Endianness>, |
| 389 |
Rel: Copy + Into<Elf::Rela>, |
| 390 |
R: ReadRef<'data>, |
| 391 |
{ |
| 392 |
if link == dynamic_symbols.section() { |
| 393 |
Self::read_relocations_impl::<Elf, Rel, true>( |
| 394 |
index, |
| 395 |
endian, |
| 396 |
is_mips64el, |
| 397 |
rels, |
| 398 |
dynamic_symbols.len(), |
| 399 |
) |
| 400 |
.map(SectionData::DynamicRelocation) |
| 401 |
} else if link.0 == 0 || section.sh_flags(endian).into() & u64::from(elf::SHF_ALLOC) != 0 { |
| 402 |
// If there's no link, then none of the relocations may reference symbols. |
| 403 |
// Assume that these are dynamic relocations, but don't use the dynamic |
| 404 |
// symbol table when parsing. |
| 405 |
// |
| 406 |
// Additionally, sometimes there is an allocated section that links to |
| 407 |
// the static symbol table. We don't currently support this case in general, |
| 408 |
// but if none of the relocation entries reference a symbol then it is |
| 409 |
// safe to treat it as a dynamic relocation section. |
| 410 |
// |
| 411 |
// For both of these cases, if there is a reference to a symbol then |
| 412 |
// an error will be returned when parsing the relocations. |
| 413 |
Self::read_relocations_impl::<Elf, Rel, true>(index, endian, is_mips64el, rels, 0) |
| 414 |
.map(SectionData::DynamicRelocation) |
| 415 |
} else if link == symbols.section() { |
| 416 |
Self::read_relocations_impl::<Elf, Rel, false>( |
| 417 |
index, |
| 418 |
endian, |
| 419 |
is_mips64el, |
| 420 |
rels, |
| 421 |
symbols.len(), |
| 422 |
) |
| 423 |
.map(SectionData::Relocation) |
| 424 |
} else { |
| 425 |
return Err(Error(format!( |
| 426 |
"Invalid sh_link {} in relocation section at index {}", |
| 427 |
link.0, index, |
| 428 |
))); |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
fn read_relocations_impl<Elf, Rel, const DYNAMIC: bool>( |
| 433 |
index: read::SectionIndex, |
| 434 |
endian: Elf::Endian, |
| 435 |
is_mips64el: bool, |
| 436 |
rels: &'data [Rel], |
| 437 |
symbols_len: usize, |
| 438 |
) -> Result<Vec<Relocation<DYNAMIC>>> |
| 439 |
where |
| 440 |
Elf: FileHeader<Endian = Endianness>, |
| 441 |
Rel: Copy + Into<Elf::Rela>, |
| 442 |
{ |
| 443 |
let mut relocations = Vec::new(); |
| 444 |
for rel in rels { |
| 445 |
let rel = (*rel).into(); |
| 446 |
let symbol = if let Some(symbol) = rel.symbol(endian, is_mips64el) { |
| 447 |
if symbol.0 >= symbols_len { |
| 448 |
return Err(Error(format!( |
| 449 |
"Invalid symbol index {} in relocation section at index {}", |
| 450 |
symbol, index, |
| 451 |
))); |
| 452 |
} |
| 453 |
Some(SymbolId(symbol.0 - 1)) |
| 454 |
} else { |
| 455 |
None |
| 456 |
}; |
| 457 |
relocations.push(Relocation { |
| 458 |
r_offset: rel.r_offset(endian).into(), |
| 459 |
symbol, |
| 460 |
r_type: rel.r_type(endian, is_mips64el), |
| 461 |
r_addend: rel.r_addend(endian).into(), |
| 462 |
}); |
| 463 |
} |
| 464 |
Ok(relocations) |
| 465 |
} |
| 466 |
|
| 467 |
fn read_dynamics<Elf, R>( |
| 468 |
endian: Elf::Endian, |
| 469 |
dyns: &'data [Elf::Dyn], |
| 470 |
strings: read::StringTable<'data, R>, |
| 471 |
) -> Result<SectionData<'data>> |
| 472 |
where |
| 473 |
Elf: FileHeader<Endian = Endianness>, |
| 474 |
R: ReadRef<'data>, |
| 475 |
{ |
| 476 |
let mut dynamics = Vec::with_capacity(dyns.len()); |
| 477 |
for d in dyns { |
| 478 |
let tag = d.d_tag(endian).into().try_into().map_err(|_| { |
| 479 |
Error(format!( |
| 480 |
"Unsupported dynamic tag 0x{:x}", |
| 481 |
d.d_tag(endian).into() |
| 482 |
)) |
| 483 |
})?; |
| 484 |
if tag == elf::DT_NULL { |
| 485 |
break; |
| 486 |
} |
| 487 |
let val = d.d_val(endian).into(); |
| 488 |
dynamics.push(if d.is_string(endian) { |
| 489 |
let val = |
| 490 |
strings |
| 491 |
.get(val.try_into().map_err(|_| { |
| 492 |
Error(format!("Unsupported dynamic string 0x{:x}", val)) |
| 493 |
})?) |
| 494 |
.map_err(|_| Error(format!("Invalid dynamic string 0x{:x}", val)))?; |
| 495 |
Dynamic::String { |
| 496 |
tag, |
| 497 |
val: val.into(), |
| 498 |
} |
| 499 |
} else { |
| 500 |
match tag { |
| 501 |
elf::DT_SYMTAB |
| 502 |
| elf::DT_STRTAB |
| 503 |
| elf::DT_STRSZ |
| 504 |
| elf::DT_HASH |
| 505 |
| elf::DT_GNU_HASH |
| 506 |
| elf::DT_VERSYM |
| 507 |
| elf::DT_VERDEF |
| 508 |
| elf::DT_VERDEFNUM |
| 509 |
| elf::DT_VERNEED |
| 510 |
| elf::DT_VERNEEDNUM => Dynamic::Auto { tag }, |
| 511 |
_ => Dynamic::Integer { tag, val }, |
| 512 |
} |
| 513 |
}); |
| 514 |
} |
| 515 |
Ok(SectionData::Dynamic(dynamics)) |
| 516 |
} |
| 517 |
|
| 518 |
fn read_symbols<Elf, R, const DYNAMIC: bool>( |
| 519 |
endian: Elf::Endian, |
| 520 |
symbols: &read::elf::SymbolTable<'data, Elf, R>, |
| 521 |
builder_symbols: &mut Symbols<'data, DYNAMIC>, |
| 522 |
sections_len: usize, |
| 523 |
) -> Result<()> |
| 524 |
where |
| 525 |
Elf: FileHeader<Endian = Endianness>, |
| 526 |
R: ReadRef<'data>, |
| 527 |
{ |
| 528 |
for (index, symbol) in symbols.enumerate().skip(1) { |
| 529 |
let id = SymbolId(index.0 - 1); |
| 530 |
let section = |
| 531 |
if let Some(section_index) = symbols.symbol_section(endian, symbol, index)? { |
| 532 |
let section_id = section_index.0.wrapping_sub(1); |
| 533 |
if section_id >= sections_len { |
| 534 |
return Err(Error::new("Invalid symbol section index")); |
| 535 |
} |
| 536 |
Some(SectionId(section_id)) |
| 537 |
} else { |
| 538 |
None |
| 539 |
}; |
| 540 |
builder_symbols.push(Symbol { |
| 541 |
id, |
| 542 |
delete: false, |
| 543 |
name: symbols.symbol_name(endian, symbol)?.into(), |
| 544 |
section, |
| 545 |
st_info: symbol.st_info(), |
| 546 |
st_other: symbol.st_other(), |
| 547 |
st_shndx: symbol.st_shndx(endian), |
| 548 |
st_value: symbol.st_value(endian).into(), |
| 549 |
st_size: symbol.st_size(endian).into(), |
| 550 |
version: VersionId::local(), |
| 551 |
version_hidden: false, |
| 552 |
}); |
| 553 |
} |
| 554 |
Ok(()) |
| 555 |
} |
| 556 |
|
| 557 |
fn read_attributes<Elf>( |
| 558 |
index: read::SectionIndex, |
| 559 |
attributes: read::elf::AttributesSection<'data, Elf>, |
| 560 |
sections_len: usize, |
| 561 |
symbols_len: usize, |
| 562 |
) -> Result<SectionData<'data>> |
| 563 |
where |
| 564 |
Elf: FileHeader<Endian = Endianness>, |
| 565 |
{ |
| 566 |
let mut builder_attributes = AttributesSection::new(); |
| 567 |
let mut subsections = attributes.subsections()?; |
| 568 |
while let Some(subsection) = subsections.next()? { |
| 569 |
let mut builder_subsection = AttributesSubsection::new(subsection.vendor().into()); |
| 570 |
let mut subsubsections = subsection.subsubsections(); |
| 571 |
while let Some(subsubsection) = subsubsections.next()? { |
| 572 |
let tag = match subsubsection.tag() { |
| 573 |
elf::Tag_File => AttributeTag::File, |
| 574 |
elf::Tag_Section => { |
| 575 |
let mut tag_sections = Vec::new(); |
| 576 |
let mut indices = subsubsection.indices(); |
| 577 |
while let Some(index) = indices.next()? { |
| 578 |
let index = index as usize; |
| 579 |
if index >= sections_len { |
| 580 |
return Err(Error(format!( |
| 581 |
"Invalid section index {} in attribute", |
| 582 |
index |
| 583 |
))); |
| 584 |
} |
| 585 |
tag_sections.push(SectionId(index - 1)); |
| 586 |
} |
| 587 |
AttributeTag::Section(tag_sections) |
| 588 |
} |
| 589 |
elf::Tag_Symbol => { |
| 590 |
let mut tag_symbols = Vec::new(); |
| 591 |
let mut indices = subsubsection.indices(); |
| 592 |
while let Some(index) = indices.next()? { |
| 593 |
let index = index as usize; |
| 594 |
if index >= symbols_len { |
| 595 |
return Err(Error(format!( |
| 596 |
"Invalid symbol index {} in attribute", |
| 597 |
index |
| 598 |
))); |
| 599 |
} |
| 600 |
tag_symbols.push(SymbolId(index - 1)); |
| 601 |
} |
| 602 |
AttributeTag::Symbol(tag_symbols) |
| 603 |
} |
| 604 |
tag => { |
| 605 |
return Err(Error(format!( |
| 606 |
"Unsupported attribute tag 0x{:x} in section at index {}", |
| 607 |
tag, index, |
| 608 |
))) |
| 609 |
} |
| 610 |
}; |
| 611 |
let data = subsubsection.attributes_data().into(); |
| 612 |
builder_subsection |
| 613 |
.subsubsections |
| 614 |
.push(AttributesSubsubsection { tag, data }); |
| 615 |
} |
| 616 |
builder_attributes.subsections.push(builder_subsection); |
| 617 |
} |
| 618 |
Ok(SectionData::Attributes(builder_attributes)) |
| 619 |
} |
| 620 |
|
| 621 |
fn read_gnu_versions<Elf, R>( |
| 622 |
&mut self, |
| 623 |
endian: Elf::Endian, |
| 624 |
data: R, |
| 625 |
sections: &read::elf::SectionTable<'data, Elf, R>, |
| 626 |
dynamic_symbols: &read::elf::SymbolTable<'data, Elf, R>, |
| 627 |
) -> Result<()> |
| 628 |
where |
| 629 |
Elf: FileHeader<Endian = Endianness>, |
| 630 |
R: ReadRef<'data>, |
| 631 |
{ |
| 632 |
let strings = dynamic_symbols.strings(); |
| 633 |
let mut ids = HashMap::new(); |
| 634 |
ids.insert(0, VersionId::local()); |
| 635 |
ids.insert(1, VersionId::global()); |
| 636 |
|
| 637 |
if let Some((mut verdefs, link)) = sections.gnu_verdef(endian, data)? { |
| 638 |
if link != dynamic_symbols.string_section() { |
| 639 |
return Err(Error::new("Invalid SHT_GNU_VERDEF section")); |
| 640 |
} |
| 641 |
while let Some((verdef, mut verdauxs)) = verdefs.next()? { |
| 642 |
let flags = verdef.vd_flags.get(endian); |
| 643 |
if flags & elf::VER_FLG_BASE != 0 { |
| 644 |
if flags != elf::VER_FLG_BASE |
| 645 |
|| verdef.vd_ndx.get(endian) != 1 |
| 646 |
|| verdef.vd_cnt.get(endian) != 1 |
| 647 |
{ |
| 648 |
return Err(Error::new("Unsupported VER_FLG_BASE in SHT_GNU_VERDEF")); |
| 649 |
} |
| 650 |
if self.version_base.is_some() { |
| 651 |
return Err(Error::new("Duplicate VER_FLG_BASE in SHT_GNU_VERDEF")); |
| 652 |
} |
| 653 |
let verdaux = verdauxs.next()?.ok_or_else(|| { |
| 654 |
Error::new("Missing name for VER_FLG_BASE in SHT_GNU_VERDEF") |
| 655 |
})?; |
| 656 |
self.version_base = Some(verdaux.name(endian, strings)?.into()); |
| 657 |
continue; |
| 658 |
} |
| 659 |
|
| 660 |
let index = verdef.vd_ndx.get(endian) & elf::VERSYM_VERSION; |
| 661 |
let id = self.versions.next_id(); |
| 662 |
if ids.insert(index, id).is_some() { |
| 663 |
return Err(Error(format!("Duplicate SHT_GNU_VERDEF index {}", index))); |
| 664 |
} |
| 665 |
|
| 666 |
let mut names = Vec::new(); |
| 667 |
while let Some(verdaux) = verdauxs.next()? { |
| 668 |
names.push(verdaux.name(endian, strings)?.into()); |
| 669 |
} |
| 670 |
|
| 671 |
let data = VersionData::Def(VersionDef { flags, names }); |
| 672 |
self.versions.push(Version { |
| 673 |
id, |
| 674 |
delete: false, |
| 675 |
data, |
| 676 |
}); |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
if let Some((mut verneeds, link)) = sections.gnu_verneed(endian, data)? { |
| 681 |
if link != dynamic_symbols.string_section() { |
| 682 |
return Err(Error::new("Invalid SHT_GNU_VERNEED section")); |
| 683 |
} |
| 684 |
while let Some((verneed, mut vernauxs)) = verneeds.next()? { |
| 685 |
let file = VersionFileId(self.version_files.len()); |
| 686 |
self.version_files.push(VersionFile { |
| 687 |
id: file, |
| 688 |
delete: false, |
| 689 |
name: verneed.file(endian, strings)?.into(), |
| 690 |
}); |
| 691 |
while let Some(vernaux) = vernauxs.next()? { |
| 692 |
let index = vernaux.vna_other.get(endian) & elf::VERSYM_VERSION; |
| 693 |
let id = self.versions.next_id(); |
| 694 |
if ids.insert(index, id).is_some() { |
| 695 |
return Err(Error(format!("Duplicate SHT_GNU_VERNEED index {}", index))); |
| 696 |
} |
| 697 |
|
| 698 |
let data = VersionData::Need(VersionNeed { |
| 699 |
flags: vernaux.vna_flags.get(endian), |
| 700 |
name: vernaux.name(endian, strings)?.into(), |
| 701 |
file, |
| 702 |
}); |
| 703 |
self.versions.push(Version { |
| 704 |
id, |
| 705 |
delete: false, |
| 706 |
data, |
| 707 |
}); |
| 708 |
} |
| 709 |
} |
| 710 |
} |
| 711 |
|
| 712 |
if let Some((versyms, link)) = sections.gnu_versym(endian, data)? { |
| 713 |
if versyms.len() != dynamic_symbols.len() || link != dynamic_symbols.section() { |
| 714 |
return Err(Error::new("Invalid SHT_GNU_VERSYM section")); |
| 715 |
} |
| 716 |
for (id, versym) in versyms.iter().skip(1).enumerate() { |
| 717 |
let index = versym.0.get(endian); |
| 718 |
let symbol = self.dynamic_symbols.get_mut(SymbolId(id)); |
| 719 |
symbol.version = *ids |
| 720 |
.get(&(index & elf::VERSYM_VERSION)) |
| 721 |
.ok_or_else(|| Error(format!("Invalid SHT_GNU_VERSYM index {:x}", index)))?; |
| 722 |
symbol.version_hidden = index & elf::VERSYM_HIDDEN != 0; |
| 723 |
} |
| 724 |
} |
| 725 |
Ok(()) |
| 726 |
} |
| 727 |
|
| 728 |
/// Write the ELF file to the buffer. |
| 729 |
pub fn write(mut self, buffer: &mut dyn write::WritableBuffer) -> Result<()> { |
| 730 |
struct SectionOut { |
| 731 |
id: SectionId, |
| 732 |
name: Option<write::StringId>, |
| 733 |
offset: usize, |
| 734 |
attributes: Vec<u8>, |
| 735 |
} |
| 736 |
|
| 737 |
struct SymbolOut { |
| 738 |
id: SymbolId, |
| 739 |
name: Option<write::StringId>, |
| 740 |
} |
| 741 |
|
| 742 |
struct DynamicSymbolOut { |
| 743 |
id: DynamicSymbolId, |
| 744 |
name: Option<write::StringId>, |
| 745 |
hash: Option<u32>, |
| 746 |
gnu_hash: Option<u32>, |
| 747 |
} |
| 748 |
|
| 749 |
#[derive(Default, Clone)] |
| 750 |
struct VersionFileOut { |
| 751 |
versions: Vec<VersionId>, |
| 752 |
} |
| 753 |
|
| 754 |
// TODO: require the caller to do this? |
| 755 |
self.delete_orphans(); |
| 756 |
self.delete_unused_versions(); |
| 757 |
|
| 758 |
let mut writer = write::elf::Writer::new(self.endian, self.is_64, buffer); |
| 759 |
|
| 760 |
// Find metadata sections, and assign section indices. |
| 761 |
let mut shstrtab_id = None; |
| 762 |
let mut symtab_id = None; |
| 763 |
let mut symtab_shndx_id = None; |
| 764 |
let mut strtab_id = None; |
| 765 |
let mut dynsym_id = None; |
| 766 |
let mut dynstr_id = None; |
| 767 |
let mut hash_id = None; |
| 768 |
let mut gnu_hash_id = None; |
| 769 |
let mut gnu_versym_id = None; |
| 770 |
let mut gnu_verdef_id = None; |
| 771 |
let mut gnu_verneed_id = None; |
| 772 |
let mut out_sections = Vec::with_capacity(self.sections.len()); |
| 773 |
let mut out_sections_index = vec![None; self.sections.len()]; |
| 774 |
if !self.sections.is_empty() { |
| 775 |
writer.reserve_null_section_index(); |
| 776 |
} |
| 777 |
for section in &self.sections { |
| 778 |
let index = match §ion.data { |
| 779 |
SectionData::Data(_) |
| 780 |
| SectionData::UninitializedData(_) |
| 781 |
| SectionData::Relocation(_) |
| 782 |
| SectionData::DynamicRelocation(_) |
| 783 |
| SectionData::Note(_) |
| 784 |
| SectionData::Dynamic(_) |
| 785 |
| SectionData::Attributes(_) => writer.reserve_section_index(), |
| 786 |
SectionData::SectionString => { |
| 787 |
if shstrtab_id.is_some() { |
| 788 |
return Err(Error::new("Multiple .shstrtab sections")); |
| 789 |
} |
| 790 |
shstrtab_id = Some(section.id); |
| 791 |
writer.reserve_shstrtab_section_index_with_name(§ion.name) |
| 792 |
} |
| 793 |
SectionData::Symbol => { |
| 794 |
if symtab_id.is_some() { |
| 795 |
return Err(Error::new("Multiple .symtab sections")); |
| 796 |
} |
| 797 |
symtab_id = Some(section.id); |
| 798 |
writer.reserve_symtab_section_index_with_name(§ion.name) |
| 799 |
} |
| 800 |
SectionData::SymbolSectionIndex => { |
| 801 |
if symtab_shndx_id.is_some() { |
| 802 |
return Err(Error::new("Multiple .symtab_shndx sections")); |
| 803 |
} |
| 804 |
symtab_shndx_id = Some(section.id); |
| 805 |
writer.reserve_symtab_shndx_section_index_with_name(§ion.name) |
| 806 |
} |
| 807 |
SectionData::String => { |
| 808 |
if strtab_id.is_some() { |
| 809 |
return Err(Error::new("Multiple .strtab sections")); |
| 810 |
} |
| 811 |
strtab_id = Some(section.id); |
| 812 |
writer.reserve_strtab_section_index_with_name(§ion.name) |
| 813 |
} |
| 814 |
SectionData::DynamicSymbol => { |
| 815 |
if dynsym_id.is_some() { |
| 816 |
return Err(Error::new("Multiple .dynsym sections")); |
| 817 |
} |
| 818 |
dynsym_id = Some(section.id); |
| 819 |
writer.reserve_dynsym_section_index_with_name(§ion.name) |
| 820 |
} |
| 821 |
SectionData::DynamicString => { |
| 822 |
if dynstr_id.is_some() { |
| 823 |
return Err(Error::new("Multiple .dynstr sections")); |
| 824 |
} |
| 825 |
dynstr_id = Some(section.id); |
| 826 |
writer.reserve_dynstr_section_index_with_name(§ion.name) |
| 827 |
} |
| 828 |
SectionData::Hash => { |
| 829 |
if hash_id.is_some() { |
| 830 |
return Err(Error::new("Multiple .hash sections")); |
| 831 |
} |
| 832 |
hash_id = Some(section.id); |
| 833 |
writer.reserve_hash_section_index_with_name(§ion.name) |
| 834 |
} |
| 835 |
SectionData::GnuHash => { |
| 836 |
if gnu_hash_id.is_some() { |
| 837 |
return Err(Error::new("Multiple .gnu.hash sections")); |
| 838 |
} |
| 839 |
gnu_hash_id = Some(section.id); |
| 840 |
writer.reserve_gnu_hash_section_index_with_name(§ion.name) |
| 841 |
} |
| 842 |
SectionData::GnuVersym => { |
| 843 |
if gnu_versym_id.is_some() { |
| 844 |
return Err(Error::new("Multiple .gnu.version sections")); |
| 845 |
} |
| 846 |
gnu_versym_id = Some(section.id); |
| 847 |
writer.reserve_gnu_versym_section_index_with_name(§ion.name) |
| 848 |
} |
| 849 |
SectionData::GnuVerdef => { |
| 850 |
if gnu_verdef_id.is_some() { |
| 851 |
return Err(Error::new("Multiple .gnu.version_d sections")); |
| 852 |
} |
| 853 |
gnu_verdef_id = Some(section.id); |
| 854 |
writer.reserve_gnu_verdef_section_index_with_name(§ion.name) |
| 855 |
} |
| 856 |
SectionData::GnuVerneed => { |
| 857 |
if gnu_verneed_id.is_some() { |
| 858 |
return Err(Error::new("Multiple .gnu.version_r sections")); |
| 859 |
} |
| 860 |
gnu_verneed_id = Some(section.id); |
| 861 |
writer.reserve_gnu_verneed_section_index_with_name(§ion.name) |
| 862 |
} |
| 863 |
}; |
| 864 |
out_sections_index[section.id.0] = Some(index); |
| 865 |
|
| 866 |
let name = if section.name.is_empty() { |
| 867 |
None |
| 868 |
} else { |
| 869 |
Some(writer.add_section_name(§ion.name)) |
| 870 |
}; |
| 871 |
out_sections.push(SectionOut { |
| 872 |
id: section.id, |
| 873 |
name, |
| 874 |
offset: 0, |
| 875 |
attributes: Vec::new(), |
| 876 |
}); |
| 877 |
} |
| 878 |
|
| 879 |
// Assign dynamic strings. |
| 880 |
for section in &self.sections { |
| 881 |
if let SectionData::Dynamic(dynamics) = §ion.data { |
| 882 |
for dynamic in dynamics { |
| 883 |
if let Dynamic::String { val, .. } = dynamic { |
| 884 |
writer.add_dynamic_string(val); |
| 885 |
} |
| 886 |
} |
| 887 |
} |
| 888 |
} |
| 889 |
|
| 890 |
// Assign dynamic symbol indices. |
| 891 |
let mut out_dynsyms = Vec::with_capacity(self.dynamic_symbols.len()); |
| 892 |
// Local symbols must come before global. |
| 893 |
let local_symbols = self |
| 894 |
.dynamic_symbols |
| 895 |
.into_iter() |
| 896 |
.filter(|symbol| symbol.st_bind() == elf::STB_LOCAL); |
| 897 |
let global_symbols = self |
| 898 |
.dynamic_symbols |
| 899 |
.into_iter() |
| 900 |
.filter(|symbol| symbol.st_bind() != elf::STB_LOCAL); |
| 901 |
for symbol in local_symbols.chain(global_symbols) { |
| 902 |
let mut name = None; |
| 903 |
let mut hash = None; |
| 904 |
let mut gnu_hash = None; |
| 905 |
if !symbol.name.is_empty() { |
| 906 |
name = Some(writer.add_dynamic_string(&symbol.name)); |
| 907 |
if hash_id.is_some() { |
| 908 |
hash = Some(elf::hash(&symbol.name)); |
| 909 |
} |
| 910 |
if gnu_hash_id.is_some() |
| 911 |
&& (symbol.section.is_some() || symbol.st_shndx != elf::SHN_UNDEF) |
| 912 |
{ |
| 913 |
gnu_hash = Some(elf::gnu_hash(&symbol.name)); |
| 914 |
} |
| 915 |
} |
| 916 |
out_dynsyms.push(DynamicSymbolOut { |
| 917 |
id: symbol.id, |
| 918 |
name, |
| 919 |
hash, |
| 920 |
gnu_hash, |
| 921 |
}); |
| 922 |
} |
| 923 |
let num_local_dynamic = out_dynsyms |
| 924 |
.iter() |
| 925 |
.take_while(|sym| self.dynamic_symbols.get(sym.id).st_bind() == elf::STB_LOCAL) |
| 926 |
.count(); |
| 927 |
// We must sort for GNU hash before allocating symbol indices. |
| 928 |
let mut gnu_hash_symbol_count = 0; |
| 929 |
if gnu_hash_id.is_some() { |
| 930 |
if self.gnu_hash_bucket_count == 0 { |
| 931 |
return Err(Error::new(".gnu.hash bucket count is zero")); |
| 932 |
} |
| 933 |
// TODO: recalculate bucket_count? |
| 934 |
out_dynsyms[num_local_dynamic..].sort_by_key(|sym| match sym.gnu_hash { |
| 935 |
None => (0, 0), |
| 936 |
Some(hash) => (1, hash % self.gnu_hash_bucket_count), |
| 937 |
}); |
| 938 |
gnu_hash_symbol_count = out_dynsyms |
| 939 |
.iter() |
| 940 |
.skip(num_local_dynamic) |
| 941 |
.skip_while(|sym| sym.gnu_hash.is_none()) |
| 942 |
.count() as u32; |
| 943 |
} |
| 944 |
let mut out_dynsyms_index = vec![None; self.dynamic_symbols.len()]; |
| 945 |
if dynsym_id.is_some() { |
| 946 |
writer.reserve_null_dynamic_symbol_index(); |
| 947 |
} |
| 948 |
for out_dynsym in &mut out_dynsyms { |
| 949 |
out_dynsyms_index[out_dynsym.id.0] = Some(writer.reserve_dynamic_symbol_index()); |
| 950 |
} |
| 951 |
|
| 952 |
// Hash parameters. |
| 953 |
let hash_index_base = 1; // Null symbol. |
| 954 |
let hash_chain_count = hash_index_base + out_dynsyms.len() as u32; |
| 955 |
|
| 956 |
// GNU hash parameters. |
| 957 |
let gnu_hash_index_base = if gnu_hash_symbol_count == 0 { |
| 958 |
0 |
| 959 |
} else { |
| 960 |
out_dynsyms.len() as u32 - gnu_hash_symbol_count |
| 961 |
}; |
| 962 |
let gnu_hash_symbol_base = gnu_hash_index_base + 1; // Null symbol. |
| 963 |
|
| 964 |
// Assign symbol indices. |
| 965 |
let mut out_syms = Vec::with_capacity(self.symbols.len()); |
| 966 |
// Local symbols must come before global. |
| 967 |
let local_symbols = self |
| 968 |
.symbols |
| 969 |
.into_iter() |
| 970 |
.filter(|symbol| symbol.st_bind() == elf::STB_LOCAL); |
| 971 |
let global_symbols = self |
| 972 |
.symbols |
| 973 |
.into_iter() |
| 974 |
.filter(|symbol| symbol.st_bind() != elf::STB_LOCAL); |
| 975 |
for symbol in local_symbols.chain(global_symbols) { |
| 976 |
let name = if symbol.name.is_empty() { |
| 977 |
None |
| 978 |
} else { |
| 979 |
Some(writer.add_string(&symbol.name)) |
| 980 |
}; |
| 981 |
|
| 982 |
out_syms.push(SymbolOut { |
| 983 |
id: symbol.id, |
| 984 |
name, |
| 985 |
}); |
| 986 |
} |
| 987 |
let num_local = out_syms |
| 988 |
.iter() |
| 989 |
.take_while(|sym| self.symbols.get(sym.id).st_bind() == elf::STB_LOCAL) |
| 990 |
.count(); |
| 991 |
let mut out_syms_index = vec![None; self.symbols.len()]; |
| 992 |
if symtab_id.is_some() { |
| 993 |
writer.reserve_null_symbol_index(); |
| 994 |
} |
| 995 |
for out_sym in out_syms.iter_mut() { |
| 996 |
out_syms_index[out_sym.id.0] = Some(writer.reserve_symbol_index(None)); |
| 997 |
} |
| 998 |
|
| 999 |
// Count the versions and add version strings. |
| 1000 |
let mut verdef_count = 0; |
| 1001 |
let mut verdaux_count = 0; |
| 1002 |
let mut verdef_shared_base = false; |
| 1003 |
let mut verneed_count = 0; |
| 1004 |
let mut vernaux_count = 0; |
| 1005 |
let mut out_version_files = vec![VersionFileOut::default(); self.version_files.len()]; |
| 1006 |
if let Some(version_base) = &self.version_base { |
| 1007 |
verdef_count += 1; |
| 1008 |
verdaux_count += 1; |
| 1009 |
writer.add_dynamic_string(version_base); |
| 1010 |
} |
| 1011 |
for version in &self.versions { |
| 1012 |
match &version.data { |
| 1013 |
VersionData::Def(def) => { |
| 1014 |
if def.is_shared(verdef_count, self.version_base.as_ref()) { |
| 1015 |
verdef_shared_base = true; |
| 1016 |
} else { |
| 1017 |
verdaux_count += def.names.len(); |
| 1018 |
for name in &def.names { |
| 1019 |
writer.add_dynamic_string(name); |
| 1020 |
} |
| 1021 |
} |
| 1022 |
verdef_count += 1; |
| 1023 |
} |
| 1024 |
VersionData::Need(need) => { |
| 1025 |
vernaux_count += 1; |
| 1026 |
writer.add_dynamic_string(&need.name); |
| 1027 |
out_version_files[need.file.0].versions.push(version.id); |
| 1028 |
} |
| 1029 |
} |
| 1030 |
} |
| 1031 |
for file in &self.version_files { |
| 1032 |
verneed_count += 1; |
| 1033 |
writer.add_dynamic_string(&file.name); |
| 1034 |
} |
| 1035 |
|
| 1036 |
// Build the attributes sections. |
| 1037 |
for out_section in &mut out_sections { |
| 1038 |
let SectionData::Attributes(attributes) = &self.sections.get(out_section.id).data |
| 1039 |
else { |
| 1040 |
continue; |
| 1041 |
}; |
| 1042 |
if attributes.subsections.is_empty() { |
| 1043 |
continue; |
| 1044 |
} |
| 1045 |
let mut writer = writer.attributes_writer(); |
| 1046 |
for subsection in &attributes.subsections { |
| 1047 |
writer.start_subsection(&subsection.vendor); |
| 1048 |
for subsubsection in &subsection.subsubsections { |
| 1049 |
writer.start_subsubsection(subsubsection.tag.tag()); |
| 1050 |
match &subsubsection.tag { |
| 1051 |
AttributeTag::File => {} |
| 1052 |
AttributeTag::Section(sections) => { |
| 1053 |
for id in sections { |
| 1054 |
if let Some(index) = out_sections_index[id.0] { |
| 1055 |
writer.write_subsubsection_index(index.0); |
| 1056 |
} |
| 1057 |
} |
| 1058 |
writer.write_subsubsection_index(0); |
| 1059 |
} |
| 1060 |
AttributeTag::Symbol(symbols) => { |
| 1061 |
for id in symbols { |
| 1062 |
if let Some(index) = out_syms_index[id.0] { |
| 1063 |
writer.write_subsubsection_index(index.0); |
| 1064 |
} |
| 1065 |
} |
| 1066 |
writer.write_subsubsection_index(0); |
| 1067 |
} |
| 1068 |
} |
| 1069 |
writer.write_subsubsection_attributes(&subsubsection.data); |
| 1070 |
writer.end_subsubsection(); |
| 1071 |
} |
| 1072 |
writer.end_subsection(); |
| 1073 |
} |
| 1074 |
out_section.attributes = writer.data(); |
| 1075 |
} |
| 1076 |
|
| 1077 |
// TODO: support section headers in strtab |
| 1078 |
if shstrtab_id.is_none() && !out_sections.is_empty() { |
| 1079 |
return Err(Error::new(".shstrtab section is needed but not present")); |
| 1080 |
} |
| 1081 |
if symtab_id.is_none() && !out_syms.is_empty() { |
| 1082 |
return Err(Error::new(".symtab section is needed but not present")); |
| 1083 |
} |
| 1084 |
if symtab_shndx_id.is_none() && writer.symtab_shndx_needed() { |
| 1085 |
return Err(Error::new( |
| 1086 |
".symtab.shndx section is needed but not present", |
| 1087 |
)); |
| 1088 |
} else if symtab_shndx_id.is_some() { |
| 1089 |
writer.require_symtab_shndx(); |
| 1090 |
} |
| 1091 |
if strtab_id.is_none() && writer.strtab_needed() { |
| 1092 |
return Err(Error::new(".strtab section is needed but not present")); |
| 1093 |
} else if strtab_id.is_some() { |
| 1094 |
writer.require_strtab(); |
| 1095 |
} |
| 1096 |
if dynsym_id.is_none() && !out_dynsyms.is_empty() { |
| 1097 |
return Err(Error::new(".dynsym section is needed but not present")); |
| 1098 |
} |
| 1099 |
if dynstr_id.is_none() && writer.dynstr_needed() { |
| 1100 |
return Err(Error::new(".dynstr section is needed but not present")); |
| 1101 |
} else if dynstr_id.is_some() { |
| 1102 |
writer.require_dynstr(); |
| 1103 |
} |
| 1104 |
if gnu_verdef_id.is_none() && verdef_count > 0 { |
| 1105 |
return Err(Error::new( |
| 1106 |
".gnu.version_d section is needed but not present", |
| 1107 |
)); |
| 1108 |
} |
| 1109 |
if gnu_verneed_id.is_none() && verneed_count > 0 { |
| 1110 |
return Err(Error::new( |
| 1111 |
".gnu.version_r section is needed but not present", |
| 1112 |
)); |
| 1113 |
} |
| 1114 |
|
| 1115 |
// Start reserving file ranges. |
| 1116 |
writer.reserve_file_header(); |
| 1117 |
|
| 1118 |
let mut dynsym_addr = None; |
| 1119 |
let mut dynstr_addr = None; |
| 1120 |
let mut hash_addr = None; |
| 1121 |
let mut gnu_hash_addr = None; |
| 1122 |
let mut versym_addr = None; |
| 1123 |
let mut verdef_addr = None; |
| 1124 |
let mut verneed_addr = None; |
| 1125 |
|
| 1126 |
if !self.segments.is_empty() { |
| 1127 |
// TODO: support program headers in other locations. |
| 1128 |
if self.header.e_phoff != writer.reserved_len() as u64 { |
| 1129 |
return Err(Error(format!( |
| 1130 |
"Unsupported e_phoff value 0x{:x}", |
| 1131 |
self.header.e_phoff |
| 1132 |
))); |
| 1133 |
} |
| 1134 |
writer.reserve_program_headers(self.segments.count() as u32); |
| 1135 |
} |
| 1136 |
|
| 1137 |
let mut alloc_sections = Vec::new(); |
| 1138 |
if !self.segments.is_empty() { |
| 1139 |
// Reserve alloc sections at original offsets. |
| 1140 |
alloc_sections = out_sections |
| 1141 |
.iter() |
| 1142 |
.enumerate() |
| 1143 |
.filter_map(|(index, out_section)| { |
| 1144 |
let section = self.sections.get(out_section.id); |
| 1145 |
if section.is_alloc() { |
| 1146 |
Some(index) |
| 1147 |
} else { |
| 1148 |
None |
| 1149 |
} |
| 1150 |
}) |
| 1151 |
.collect(); |
| 1152 |
// The data for alloc sections may need to be written in a different order |
| 1153 |
// from their section headers. |
| 1154 |
alloc_sections.sort_by_key(|index| { |
| 1155 |
let section = &self.sections.get(out_sections[*index].id); |
| 1156 |
// Empty sections need to come before other sections at the same offset. |
| 1157 |
(section.sh_offset, section.sh_size) |
| 1158 |
}); |
| 1159 |
for index in &alloc_sections { |
| 1160 |
let out_section = &mut out_sections[*index]; |
| 1161 |
let section = &self.sections.get(out_section.id); |
| 1162 |
|
| 1163 |
if section.sh_type == elf::SHT_NOBITS { |
| 1164 |
// sh_offset is meaningless for SHT_NOBITS, so preserve the input |
| 1165 |
// value without checking it. |
| 1166 |
out_section.offset = section.sh_offset as usize; |
| 1167 |
continue; |
| 1168 |
} |
| 1169 |
|
| 1170 |
if section.sh_offset < writer.reserved_len() as u64 { |
| 1171 |
return Err(Error(format!( |
| 1172 |
"Unsupported sh_offset value 0x{:x} for section '{}', expected at least 0x{:x}", |
| 1173 |
section.sh_offset, |
| 1174 |
section.name, |
| 1175 |
writer.reserved_len(), |
| 1176 |
))); |
| 1177 |
} |
| 1178 |
// The input sh_offset needs to be preserved so that offsets in program |
| 1179 |
// headers are correct. |
| 1180 |
writer.reserve_until(section.sh_offset as usize); |
| 1181 |
out_section.offset = match §ion.data { |
| 1182 |
SectionData::Data(data) => { |
| 1183 |
writer.reserve(data.len(), section.sh_addralign as usize) |
| 1184 |
} |
| 1185 |
SectionData::DynamicRelocation(relocations) => writer |
| 1186 |
.reserve_relocations(relocations.len(), section.sh_type == elf::SHT_RELA), |
| 1187 |
SectionData::Note(data) => { |
| 1188 |
writer.reserve(data.len(), section.sh_addralign as usize) |
| 1189 |
} |
| 1190 |
SectionData::Dynamic(dynamics) => writer.reserve_dynamics(1 + dynamics.len()), |
| 1191 |
SectionData::DynamicSymbol => { |
| 1192 |
dynsym_addr = Some(section.sh_addr); |
| 1193 |
writer.reserve_dynsym() |
| 1194 |
} |
| 1195 |
SectionData::DynamicString => { |
| 1196 |
dynstr_addr = Some(section.sh_addr); |
| 1197 |
writer.reserve_dynstr() |
| 1198 |
} |
| 1199 |
SectionData::Hash => { |
| 1200 |
hash_addr = Some(section.sh_addr); |
| 1201 |
writer.reserve_hash(self.hash_bucket_count, hash_chain_count) |
| 1202 |
} |
| 1203 |
SectionData::GnuHash => { |
| 1204 |
gnu_hash_addr = Some(section.sh_addr); |
| 1205 |
writer.reserve_gnu_hash( |
| 1206 |
self.gnu_hash_bloom_count, |
| 1207 |
self.gnu_hash_bucket_count, |
| 1208 |
gnu_hash_symbol_count, |
| 1209 |
) |
| 1210 |
} |
| 1211 |
SectionData::GnuVersym => { |
| 1212 |
versym_addr = Some(section.sh_addr); |
| 1213 |
writer.reserve_gnu_versym() |
| 1214 |
} |
| 1215 |
SectionData::GnuVerdef => { |
| 1216 |
verdef_addr = Some(section.sh_addr); |
| 1217 |
writer.reserve_gnu_verdef(verdef_count, verdaux_count) |
| 1218 |
} |
| 1219 |
SectionData::GnuVerneed => { |
| 1220 |
verneed_addr = Some(section.sh_addr); |
| 1221 |
writer.reserve_gnu_verneed(verneed_count, vernaux_count) |
| 1222 |
} |
| 1223 |
_ => { |
| 1224 |
return Err(Error(format!( |
| 1225 |
"Unsupported alloc section type {:x} for section '{}'", |
| 1226 |
section.sh_type, section.name, |
| 1227 |
))); |
| 1228 |
} |
| 1229 |
}; |
| 1230 |
if out_section.offset as u64 != section.sh_offset { |
| 1231 |
return Err(Error(format!( |
| 1232 |
"Unaligned sh_offset value 0x{:x} for section '{}', expected 0x{:x}", |
| 1233 |
section.sh_offset, section.name, out_section.offset, |
| 1234 |
))); |
| 1235 |
} |
| 1236 |
} |
| 1237 |
} |
| 1238 |
|
| 1239 |
// Reserve non-alloc sections at any offset. |
| 1240 |
for out_section in &mut out_sections { |
| 1241 |
let section = self.sections.get(out_section.id); |
| 1242 |
if !self.segments.is_empty() && section.is_alloc() { |
| 1243 |
continue; |
| 1244 |
} |
| 1245 |
out_section.offset = match §ion.data { |
| 1246 |
SectionData::Data(data) => { |
| 1247 |
writer.reserve(data.len(), section.sh_addralign as usize) |
| 1248 |
} |
| 1249 |
SectionData::UninitializedData(_) => writer.reserved_len(), |
| 1250 |
SectionData::Note(data) => { |
| 1251 |
writer.reserve(data.len(), section.sh_addralign as usize) |
| 1252 |
} |
| 1253 |
SectionData::Attributes(_) => { |
| 1254 |
writer.reserve(out_section.attributes.len(), section.sh_addralign as usize) |
| 1255 |
} |
| 1256 |
// These are handled elsewhere. |
| 1257 |
SectionData::Relocation(_) |
| 1258 |
| SectionData::SectionString |
| 1259 |
| SectionData::Symbol |
| 1260 |
| SectionData::SymbolSectionIndex |
| 1261 |
| SectionData::String => { |
| 1262 |
continue; |
| 1263 |
} |
| 1264 |
_ => { |
| 1265 |
return Err(Error(format!( |
| 1266 |
"Unsupported non-alloc section type {:x}", |
| 1267 |
section.sh_type |
| 1268 |
))); |
| 1269 |
} |
| 1270 |
}; |
| 1271 |
} |
| 1272 |
|
| 1273 |
writer.reserve_symtab(); |
| 1274 |
writer.reserve_symtab_shndx(); |
| 1275 |
writer.reserve_strtab(); |
| 1276 |
|
| 1277 |
// Reserve non-alloc relocations. |
| 1278 |
for out_section in &mut out_sections { |
| 1279 |
let section = self.sections.get(out_section.id); |
| 1280 |
if !self.segments.is_empty() && section.is_alloc() { |
| 1281 |
continue; |
| 1282 |
} |
| 1283 |
let SectionData::Relocation(relocations) = §ion.data else { |
| 1284 |
continue; |
| 1285 |
}; |
| 1286 |
out_section.offset = |
| 1287 |
writer.reserve_relocations(relocations.len(), section.sh_type == elf::SHT_RELA); |
| 1288 |
} |
| 1289 |
|
| 1290 |
writer.reserve_shstrtab(); |
| 1291 |
writer.reserve_section_headers(); |
| 1292 |
|
| 1293 |
// Start writing. |
| 1294 |
writer.write_file_header(&write::elf::FileHeader { |
| 1295 |
os_abi: self.header.os_abi, |
| 1296 |
abi_version: self.header.abi_version, |
| 1297 |
e_type: self.header.e_type, |
| 1298 |
e_machine: self.header.e_machine, |
| 1299 |
e_entry: self.header.e_entry, |
| 1300 |
e_flags: self.header.e_flags, |
| 1301 |
})?; |
| 1302 |
|
| 1303 |
if !self.segments.is_empty() { |
| 1304 |
writer.write_align_program_headers(); |
| 1305 |
for segment in &self.segments { |
| 1306 |
writer.write_program_header(&write::elf::ProgramHeader { |
| 1307 |
p_type: segment.p_type, |
| 1308 |
p_flags: segment.p_flags, |
| 1309 |
p_offset: segment.p_offset, |
| 1310 |
p_vaddr: segment.p_vaddr, |
| 1311 |
p_paddr: segment.p_paddr, |
| 1312 |
p_filesz: segment.p_filesz, |
| 1313 |
p_memsz: segment.p_memsz, |
| 1314 |
p_align: segment.p_align, |
| 1315 |
}); |
| 1316 |
} |
| 1317 |
} |
| 1318 |
|
| 1319 |
// Write alloc sections. |
| 1320 |
if !self.segments.is_empty() { |
| 1321 |
for index in &alloc_sections { |
| 1322 |
let out_section = &mut out_sections[*index]; |
| 1323 |
let section = self.sections.get(out_section.id); |
| 1324 |
|
| 1325 |
if section.sh_type == elf::SHT_NOBITS { |
| 1326 |
continue; |
| 1327 |
} |
| 1328 |
|
| 1329 |
writer.pad_until(out_section.offset); |
| 1330 |
match §ion.data { |
| 1331 |
SectionData::Data(data) => { |
| 1332 |
writer.write(data); |
| 1333 |
} |
| 1334 |
SectionData::DynamicRelocation(relocations) => { |
| 1335 |
for rel in relocations { |
| 1336 |
let r_sym = if let Some(symbol) = rel.symbol { |
| 1337 |
out_dynsyms_index[symbol.0].unwrap().0 |
| 1338 |
} else { |
| 1339 |
0 |
| 1340 |
}; |
| 1341 |
writer.write_relocation( |
| 1342 |
section.sh_type == elf::SHT_RELA, |
| 1343 |
&write::elf::Rel { |
| 1344 |
r_offset: rel.r_offset, |
| 1345 |
r_sym, |
| 1346 |
r_type: rel.r_type, |
| 1347 |
r_addend: rel.r_addend, |
| 1348 |
}, |
| 1349 |
); |
| 1350 |
} |
| 1351 |
} |
| 1352 |
SectionData::Note(data) => { |
| 1353 |
writer.write(data); |
| 1354 |
} |
| 1355 |
SectionData::Dynamic(dynamics) => { |
| 1356 |
for d in dynamics { |
| 1357 |
match *d { |
| 1358 |
Dynamic::Auto { tag } => { |
| 1359 |
// TODO: support more values |
| 1360 |
let val = match tag { |
| 1361 |
elf::DT_SYMTAB => dynsym_addr.ok_or(Error::new( |
| 1362 |
"Missing .dynsym section for DT_SYMTAB", |
| 1363 |
))?, |
| 1364 |
elf::DT_STRTAB => dynstr_addr.ok_or(Error::new( |
| 1365 |
"Missing .dynstr section for DT_STRTAB", |
| 1366 |
))?, |
| 1367 |
elf::DT_STRSZ => writer.dynstr_len() as u64, |
| 1368 |
elf::DT_HASH => hash_addr.ok_or(Error::new( |
| 1369 |
"Missing .hash section for DT_HASH", |
| 1370 |
))?, |
| 1371 |
elf::DT_GNU_HASH => gnu_hash_addr.ok_or(Error::new( |
| 1372 |
"Missing .gnu.hash section for DT_GNU_HASH", |
| 1373 |
))?, |
| 1374 |
elf::DT_VERSYM => versym_addr.ok_or(Error::new( |
| 1375 |
"Missing .gnu.version section for DT_VERSYM", |
| 1376 |
))?, |
| 1377 |
elf::DT_VERDEF => verdef_addr.ok_or(Error::new( |
| 1378 |
"Missing .gnu.version_d section for DT_VERDEF", |
| 1379 |
))?, |
| 1380 |
elf::DT_VERDEFNUM => verdef_count as u64, |
| 1381 |
elf::DT_VERNEED => verneed_addr.ok_or(Error::new( |
| 1382 |
"Missing .gnu.version_r section for DT_VERNEED", |
| 1383 |
))?, |
| 1384 |
elf::DT_VERNEEDNUM => verneed_count as u64, |
| 1385 |
_ => { |
| 1386 |
return Err(Error(format!( |
| 1387 |
"Cannot generate value for dynamic tag 0x{:x}", |
| 1388 |
tag |
| 1389 |
))) |
| 1390 |
} |
| 1391 |
}; |
| 1392 |
writer.write_dynamic(tag, val); |
| 1393 |
} |
| 1394 |
Dynamic::Integer { tag, val } => { |
| 1395 |
writer.write_dynamic(tag, val); |
| 1396 |
} |
| 1397 |
Dynamic::String { tag, ref val } => { |
| 1398 |
let val = writer.get_dynamic_string(val); |
| 1399 |
writer.write_dynamic_string(tag, val); |
| 1400 |
} |
| 1401 |
} |
| 1402 |
} |
| 1403 |
writer.write_dynamic(elf::DT_NULL, 0); |
| 1404 |
} |
| 1405 |
SectionData::DynamicSymbol => { |
| 1406 |
writer.write_null_dynamic_symbol(); |
| 1407 |
for out_dynsym in &out_dynsyms { |
| 1408 |
let symbol = self.dynamic_symbols.get(out_dynsym.id); |
| 1409 |
let section = |
| 1410 |
symbol.section.map(|id| out_sections_index[id.0].unwrap()); |
| 1411 |
writer.write_dynamic_symbol(&write::elf::Sym { |
| 1412 |
name: out_dynsym.name, |
| 1413 |
section, |
| 1414 |
st_info: symbol.st_info, |
| 1415 |
st_other: symbol.st_other, |
| 1416 |
st_shndx: symbol.st_shndx, |
| 1417 |
st_value: symbol.st_value, |
| 1418 |
st_size: symbol.st_size, |
| 1419 |
}); |
| 1420 |
} |
| 1421 |
} |
| 1422 |
SectionData::DynamicString => { |
| 1423 |
writer.write_dynstr(); |
| 1424 |
} |
| 1425 |
SectionData::Hash => { |
| 1426 |
if self.hash_bucket_count == 0 { |
| 1427 |
return Err(Error::new(".hash bucket count is zero")); |
| 1428 |
} |
| 1429 |
writer.write_hash(self.hash_bucket_count, hash_chain_count, |index| { |
| 1430 |
out_dynsyms |
| 1431 |
.get(index.checked_sub(hash_index_base)? as usize)? |
| 1432 |
.hash |
| 1433 |
}); |
| 1434 |
} |
| 1435 |
SectionData::GnuHash => { |
| 1436 |
if self.gnu_hash_bucket_count == 0 { |
| 1437 |
return Err(Error::new(".gnu.hash bucket count is zero")); |
| 1438 |
} |
| 1439 |
writer.write_gnu_hash( |
| 1440 |
gnu_hash_symbol_base, |
| 1441 |
self.gnu_hash_bloom_shift, |
| 1442 |
self.gnu_hash_bloom_count, |
| 1443 |
self.gnu_hash_bucket_count, |
| 1444 |
gnu_hash_symbol_count, |
| 1445 |
|index| { |
| 1446 |
out_dynsyms[(gnu_hash_index_base + index) as usize] |
| 1447 |
.gnu_hash |
| 1448 |
.unwrap() |
| 1449 |
}, |
| 1450 |
); |
| 1451 |
} |
| 1452 |
SectionData::GnuVersym => { |
| 1453 |
writer.write_null_gnu_versym(); |
| 1454 |
for out_dynsym in &out_dynsyms { |
| 1455 |
let symbol = self.dynamic_symbols.get(out_dynsym.id); |
| 1456 |
let mut index = symbol.version.0 as u16; |
| 1457 |
if symbol.version_hidden { |
| 1458 |
index |= elf::VERSYM_HIDDEN; |
| 1459 |
} |
| 1460 |
writer.write_gnu_versym(index); |
| 1461 |
} |
| 1462 |
} |
| 1463 |
SectionData::GnuVerdef => { |
| 1464 |
writer.write_align_gnu_verdef(); |
| 1465 |
if let Some(version_base) = &self.version_base { |
| 1466 |
let verdef = write::elf::Verdef { |
| 1467 |
version: elf::VER_DEF_CURRENT, |
| 1468 |
flags: elf::VER_FLG_BASE, |
| 1469 |
index: 1, |
| 1470 |
aux_count: 1, |
| 1471 |
name: writer.get_dynamic_string(version_base), |
| 1472 |
}; |
| 1473 |
if verdef_shared_base { |
| 1474 |
writer.write_gnu_verdef_shared(&verdef); |
| 1475 |
} else { |
| 1476 |
writer.write_gnu_verdef(&verdef); |
| 1477 |
} |
| 1478 |
} |
| 1479 |
for version in &self.versions { |
| 1480 |
if let VersionData::Def(def) = &version.data { |
| 1481 |
let mut names = def.names.iter(); |
| 1482 |
let name = names.next().ok_or_else(|| { |
| 1483 |
Error(format!("Missing SHT_GNU_VERDEF name {}", version.id.0)) |
| 1484 |
})?; |
| 1485 |
writer.write_gnu_verdef(&write::elf::Verdef { |
| 1486 |
version: elf::VER_DEF_CURRENT, |
| 1487 |
flags: def.flags, |
| 1488 |
index: version.id.0 as u16, |
| 1489 |
aux_count: def.names.len() as u16, |
| 1490 |
name: writer.get_dynamic_string(name), |
| 1491 |
}); |
| 1492 |
for name in names { |
| 1493 |
writer.write_gnu_verdaux(writer.get_dynamic_string(name)); |
| 1494 |
} |
| 1495 |
} |
| 1496 |
} |
| 1497 |
} |
| 1498 |
SectionData::GnuVerneed => { |
| 1499 |
writer.write_align_gnu_verneed(); |
| 1500 |
for file in &self.version_files { |
| 1501 |
let out_file = &out_version_files[file.id.0]; |
| 1502 |
if out_file.versions.is_empty() { |
| 1503 |
continue; |
| 1504 |
} |
| 1505 |
writer.write_gnu_verneed(&write::elf::Verneed { |
| 1506 |
version: elf::VER_NEED_CURRENT, |
| 1507 |
aux_count: out_file.versions.len() as u16, |
| 1508 |
file: writer.get_dynamic_string(&file.name), |
| 1509 |
}); |
| 1510 |
for id in &out_file.versions { |
| 1511 |
let version = self.versions.get(*id); |
| 1512 |
// This will always match. |
| 1513 |
if let VersionData::Need(need) = &version.data { |
| 1514 |
debug_assert_eq!(*id, version.id); |
| 1515 |
writer.write_gnu_vernaux(&write::elf::Vernaux { |
| 1516 |
flags: need.flags, |
| 1517 |
index: version.id.0 as u16, |
| 1518 |
name: writer.get_dynamic_string(&need.name), |
| 1519 |
}); |
| 1520 |
} |
| 1521 |
} |
| 1522 |
} |
| 1523 |
} |
| 1524 |
_ => { |
| 1525 |
return Err(Error(format!( |
| 1526 |
"Unsupported alloc section type {:x}", |
| 1527 |
section.sh_type |
| 1528 |
))); |
| 1529 |
} |
| 1530 |
} |
| 1531 |
} |
| 1532 |
} |
| 1533 |
|
| 1534 |
// Write non-alloc sections. |
| 1535 |
for out_section in &mut out_sections { |
| 1536 |
let section = self.sections.get(out_section.id); |
| 1537 |
if !self.segments.is_empty() && section.is_alloc() { |
| 1538 |
continue; |
| 1539 |
} |
| 1540 |
match §ion.data { |
| 1541 |
SectionData::Data(data) => { |
| 1542 |
writer.write_align(section.sh_addralign as usize); |
| 1543 |
debug_assert_eq!(out_section.offset, writer.len()); |
| 1544 |
writer.write(data); |
| 1545 |
} |
| 1546 |
SectionData::UninitializedData(_) => { |
| 1547 |
// Nothing to do. |
| 1548 |
} |
| 1549 |
SectionData::Note(data) => { |
| 1550 |
writer.write_align(section.sh_addralign as usize); |
| 1551 |
debug_assert_eq!(out_section.offset, writer.len()); |
| 1552 |
writer.write(data); |
| 1553 |
} |
| 1554 |
SectionData::Attributes(_) => { |
| 1555 |
writer.write_align(section.sh_addralign as usize); |
| 1556 |
debug_assert_eq!(out_section.offset, writer.len()); |
| 1557 |
writer.write(&out_section.attributes); |
| 1558 |
} |
| 1559 |
// These are handled elsewhere. |
| 1560 |
SectionData::Relocation(_) |
| 1561 |
| SectionData::SectionString |
| 1562 |
| SectionData::Symbol |
| 1563 |
| SectionData::SymbolSectionIndex |
| 1564 |
| SectionData::String => {} |
| 1565 |
_ => { |
| 1566 |
return Err(Error(format!( |
| 1567 |
"Unsupported non-alloc section type {:x}", |
| 1568 |
section.sh_type |
| 1569 |
))); |
| 1570 |
} |
| 1571 |
} |
| 1572 |
} |
| 1573 |
|
| 1574 |
writer.write_null_symbol(); |
| 1575 |
for out_sym in &out_syms { |
| 1576 |
let symbol = self.symbols.get(out_sym.id); |
| 1577 |
let section = symbol.section.map(|id| out_sections_index[id.0].unwrap()); |
| 1578 |
writer.write_symbol(&write::elf::Sym { |
| 1579 |
name: out_sym.name, |
| 1580 |
section, |
| 1581 |
st_info: symbol.st_info, |
| 1582 |
st_other: symbol.st_other, |
| 1583 |
st_shndx: symbol.st_shndx, |
| 1584 |
st_value: symbol.st_value, |
| 1585 |
st_size: symbol.st_size, |
| 1586 |
}); |
| 1587 |
} |
| 1588 |
writer.write_symtab_shndx(); |
| 1589 |
writer.write_strtab(); |
| 1590 |
|
| 1591 |
// Write non-alloc relocations. |
| 1592 |
for section in &self.sections { |
| 1593 |
if !self.segments.is_empty() && section.is_alloc() { |
| 1594 |
continue; |
| 1595 |
} |
| 1596 |
let SectionData::Relocation(relocations) = §ion.data else { |
| 1597 |
continue; |
| 1598 |
}; |
| 1599 |
writer.write_align_relocation(); |
| 1600 |
for rel in relocations { |
| 1601 |
let r_sym = if let Some(id) = rel.symbol { |
| 1602 |
out_syms_index[id.0].unwrap().0 |
| 1603 |
} else { |
| 1604 |
0 |
| 1605 |
}; |
| 1606 |
writer.write_relocation( |
| 1607 |
section.sh_type == elf::SHT_RELA, |
| 1608 |
&write::elf::Rel { |
| 1609 |
r_offset: rel.r_offset, |
| 1610 |
r_sym, |
| 1611 |
r_type: rel.r_type, |
| 1612 |
r_addend: rel.r_addend, |
| 1613 |
}, |
| 1614 |
); |
| 1615 |
} |
| 1616 |
} |
| 1617 |
|
| 1618 |
writer.write_shstrtab(); |
| 1619 |
|
| 1620 |
writer.write_null_section_header(); |
| 1621 |
for out_section in &out_sections { |
| 1622 |
let section = self.sections.get(out_section.id); |
| 1623 |
match §ion.data { |
| 1624 |
SectionData::Data(_) |
| 1625 |
| SectionData::UninitializedData(_) |
| 1626 |
| SectionData::Relocation(_) |
| 1627 |
| SectionData::DynamicRelocation(_) |
| 1628 |
| SectionData::Note(_) |
| 1629 |
| SectionData::Dynamic(_) |
| 1630 |
| SectionData::Attributes(_) => { |
| 1631 |
let sh_size = match §ion.data { |
| 1632 |
SectionData::Data(data) => data.len() as u64, |
| 1633 |
SectionData::UninitializedData(len) => *len, |
| 1634 |
SectionData::Relocation(relocations) => { |
| 1635 |
(relocations.len() |
| 1636 |
* self.class().rel_size(section.sh_type == elf::SHT_RELA)) |
| 1637 |
as u64 |
| 1638 |
} |
| 1639 |
SectionData::DynamicRelocation(relocations) => { |
| 1640 |
(relocations.len() |
| 1641 |
* self.class().rel_size(section.sh_type == elf::SHT_RELA)) |
| 1642 |
as u64 |
| 1643 |
} |
| 1644 |
SectionData::Note(data) => data.len() as u64, |
| 1645 |
SectionData::Dynamic(dynamics) => { |
| 1646 |
((1 + dynamics.len()) * self.class().dyn_size()) as u64 |
| 1647 |
} |
| 1648 |
SectionData::Attributes(_) => out_section.attributes.len() as u64, |
| 1649 |
_ => { |
| 1650 |
return Err(Error(format!( |
| 1651 |
"Unimplemented size for section type {:x}", |
| 1652 |
section.sh_type |
| 1653 |
))) |
| 1654 |
} |
| 1655 |
}; |
| 1656 |
let sh_link = if let Some(id) = section.sh_link_section { |
| 1657 |
if let Some(index) = out_sections_index[id.0] { |
| 1658 |
index.0 |
| 1659 |
} else { |
| 1660 |
return Err(Error(format!( |
| 1661 |
"Invalid sh_link from section '{}' to deleted section '{}'", |
| 1662 |
section.name, |
| 1663 |
self.sections.get(id).name, |
| 1664 |
))); |
| 1665 |
} |
| 1666 |
} else { |
| 1667 |
0 |
| 1668 |
}; |
| 1669 |
let sh_info = if let Some(id) = section.sh_info_section { |
| 1670 |
if let Some(index) = out_sections_index[id.0] { |
| 1671 |
index.0 |
| 1672 |
} else { |
| 1673 |
return Err(Error(format!( |
| 1674 |
"Invalid sh_info link from section '{}' to deleted section '{}'", |
| 1675 |
section.name, |
| 1676 |
self.sections.get(id).name, |
| 1677 |
))); |
| 1678 |
} |
| 1679 |
} else { |
| 1680 |
section.sh_info |
| 1681 |
}; |
| 1682 |
writer.write_section_header(&write::elf::SectionHeader { |
| 1683 |
name: out_section.name, |
| 1684 |
sh_type: section.sh_type, |
| 1685 |
sh_flags: section.sh_flags, |
| 1686 |
sh_addr: section.sh_addr, |
| 1687 |
sh_offset: out_section.offset as u64, |
| 1688 |
sh_size, |
| 1689 |
sh_link, |
| 1690 |
sh_info, |
| 1691 |
sh_addralign: section.sh_addralign, |
| 1692 |
sh_entsize: section.sh_entsize, |
| 1693 |
}); |
| 1694 |
} |
| 1695 |
SectionData::SectionString => { |
| 1696 |
writer.write_shstrtab_section_header(); |
| 1697 |
} |
| 1698 |
SectionData::Symbol => { |
| 1699 |
writer.write_symtab_section_header(1 + num_local as u32); |
| 1700 |
} |
| 1701 |
SectionData::SymbolSectionIndex => { |
| 1702 |
writer.write_symtab_shndx_section_header(); |
| 1703 |
} |
| 1704 |
SectionData::String => { |
| 1705 |
writer.write_strtab_section_header(); |
| 1706 |
} |
| 1707 |
SectionData::DynamicString => { |
| 1708 |
writer.write_dynstr_section_header(section.sh_addr); |
| 1709 |
} |
| 1710 |
SectionData::DynamicSymbol => { |
| 1711 |
writer |
| 1712 |
.write_dynsym_section_header(section.sh_addr, 1 + num_local_dynamic as u32); |
| 1713 |
} |
| 1714 |
SectionData::Hash => { |
| 1715 |
writer.write_hash_section_header(section.sh_addr); |
| 1716 |
} |
| 1717 |
SectionData::GnuHash => { |
| 1718 |
writer.write_gnu_hash_section_header(section.sh_addr); |
| 1719 |
} |
| 1720 |
SectionData::GnuVersym => { |
| 1721 |
writer.write_gnu_versym_section_header(section.sh_addr); |
| 1722 |
} |
| 1723 |
SectionData::GnuVerdef => { |
| 1724 |
writer.write_gnu_verdef_section_header(section.sh_addr); |
| 1725 |
} |
| 1726 |
SectionData::GnuVerneed => { |
| 1727 |
writer.write_gnu_verneed_section_header(section.sh_addr); |
| 1728 |
} |
| 1729 |
} |
| 1730 |
} |
| 1731 |
debug_assert_eq!(writer.reserved_len(), writer.len()); |
| 1732 |
Ok(()) |
| 1733 |
} |
| 1734 |
|
| 1735 |
/// Delete segments, symbols, relocations, and dynamics that refer |
| 1736 |
/// to deleted items. |
| 1737 |
/// |
| 1738 |
/// This calls `delete_orphan_segments`, `delete_orphan_symbols`, |
| 1739 |
/// `delete_orphan_relocations`, and `delete_orphan_dynamics`. |
| 1740 |
pub fn delete_orphans(&mut self) { |
| 1741 |
self.delete_orphan_segments(); |
| 1742 |
self.delete_orphan_symbols(); |
| 1743 |
self.delete_orphan_relocations(); |
| 1744 |
self.delete_orphan_dynamics(); |
| 1745 |
} |
| 1746 |
|
| 1747 |
/// Set the delete flag for segments that only refer to deleted sections. |
| 1748 |
pub fn delete_orphan_segments(&mut self) { |
| 1749 |
let sections = &self.sections; |
| 1750 |
for segment in &mut self.segments { |
| 1751 |
// We only delete segments that have become empty due to section deletions. |
| 1752 |
if segment.sections.is_empty() { |
| 1753 |
continue; |
| 1754 |
} |
| 1755 |
segment.sections.retain(|id| !sections.get(*id).delete); |
| 1756 |
segment.delete = segment.sections.is_empty(); |
| 1757 |
} |
| 1758 |
} |
| 1759 |
|
| 1760 |
/// Set the delete flag for symbols that refer to deleted sections. |
| 1761 |
pub fn delete_orphan_symbols(&mut self) { |
| 1762 |
for symbol in &mut self.symbols { |
| 1763 |
if let Some(section) = symbol.section { |
| 1764 |
if self.sections.get_mut(section).delete { |
| 1765 |
symbol.delete = true; |
| 1766 |
} |
| 1767 |
} |
| 1768 |
} |
| 1769 |
for symbol in &mut self.dynamic_symbols { |
| 1770 |
if let Some(section) = symbol.section { |
| 1771 |
if self.sections.get_mut(section).delete { |
| 1772 |
symbol.delete = true; |
| 1773 |
} |
| 1774 |
} |
| 1775 |
} |
| 1776 |
} |
| 1777 |
|
| 1778 |
/// Delete relocations that refer to deleted symbols. |
| 1779 |
pub fn delete_orphan_relocations(&mut self) { |
| 1780 |
let symbols = &self.symbols; |
| 1781 |
let dynamic_symbols = &self.dynamic_symbols; |
| 1782 |
for section in &mut self.sections { |
| 1783 |
match &mut section.data { |
| 1784 |
SectionData::Relocation(relocations) => { |
| 1785 |
relocations.retain(|relocation| match relocation.symbol { |
| 1786 |
None => true, |
| 1787 |
Some(id) => !symbols.get(id).delete, |
| 1788 |
}); |
| 1789 |
} |
| 1790 |
SectionData::DynamicRelocation(relocations) => { |
| 1791 |
relocations.retain(|relocation| match relocation.symbol { |
| 1792 |
None => true, |
| 1793 |
Some(id) => !dynamic_symbols.get(id).delete, |
| 1794 |
}); |
| 1795 |
} |
| 1796 |
_ => {} |
| 1797 |
} |
| 1798 |
} |
| 1799 |
} |
| 1800 |
|
| 1801 |
/// Delete dynamic entries that refer to deleted sections. |
| 1802 |
pub fn delete_orphan_dynamics(&mut self) { |
| 1803 |
let mut have_dynsym = false; |
| 1804 |
let mut have_dynstr = false; |
| 1805 |
let mut have_hash = false; |
| 1806 |
let mut have_gnu_hash = false; |
| 1807 |
let mut have_versym = false; |
| 1808 |
let mut have_verdef = false; |
| 1809 |
let mut have_verneed = false; |
| 1810 |
for section in &self.sections { |
| 1811 |
match §ion.data { |
| 1812 |
SectionData::DynamicSymbol => have_dynsym = true, |
| 1813 |
SectionData::DynamicString => have_dynstr = true, |
| 1814 |
SectionData::Hash => have_hash = true, |
| 1815 |
SectionData::GnuHash => have_gnu_hash = true, |
| 1816 |
SectionData::GnuVersym => have_versym = true, |
| 1817 |
SectionData::GnuVerdef => have_verdef = true, |
| 1818 |
SectionData::GnuVerneed => have_verneed = true, |
| 1819 |
_ => {} |
| 1820 |
} |
| 1821 |
} |
| 1822 |
for section in &mut self.sections { |
| 1823 |
if let SectionData::Dynamic(dynamics) = &mut section.data { |
| 1824 |
dynamics.retain(|dynamic| match dynamic { |
| 1825 |
Dynamic::Auto { |
| 1826 |
tag: elf::DT_SYMTAB, |
| 1827 |
} => have_dynsym, |
| 1828 |
Dynamic::Auto { |
| 1829 |
tag: elf::DT_STRTAB, |
| 1830 |
} |
| 1831 |
| Dynamic::Auto { tag: elf::DT_STRSZ } => have_dynstr, |
| 1832 |
Dynamic::Auto { tag: elf::DT_HASH } => have_hash, |
| 1833 |
Dynamic::Auto { |
| 1834 |
tag: elf::DT_GNU_HASH, |
| 1835 |
} => have_gnu_hash, |
| 1836 |
Dynamic::Auto { |
| 1837 |
tag: elf::DT_VERSYM, |
| 1838 |
} => have_versym, |
| 1839 |
Dynamic::Auto { |
| 1840 |
tag: elf::DT_VERNEED, |
| 1841 |
} |
| 1842 |
| Dynamic::Auto { |
| 1843 |
tag: elf::DT_VERNEEDNUM, |
| 1844 |
} => have_verneed, |
| 1845 |
Dynamic::Auto { |
| 1846 |
tag: elf::DT_VERDEF, |
| 1847 |
} |
| 1848 |
| Dynamic::Auto { |
| 1849 |
tag: elf::DT_VERDEFNUM, |
| 1850 |
} => have_verdef, |
| 1851 |
_ => true, |
| 1852 |
}); |
| 1853 |
} |
| 1854 |
} |
| 1855 |
} |
| 1856 |
|
| 1857 |
/// Delete unused GNU version entries. |
| 1858 |
pub fn delete_unused_versions(&mut self) { |
| 1859 |
let mut version_used = vec![false; self.versions.len() + VERSION_ID_BASE]; |
| 1860 |
for symbol in &self.dynamic_symbols { |
| 1861 |
version_used[symbol.version.0] = true; |
| 1862 |
} |
| 1863 |
let mut version_file_used = vec![false; self.version_files.len()]; |
| 1864 |
for version in &mut self.versions { |
| 1865 |
if !version_used[version.id.0] { |
| 1866 |
version.delete = true; |
| 1867 |
continue; |
| 1868 |
} |
| 1869 |
if let VersionData::Need(need) = &version.data { |
| 1870 |
version_file_used[need.file.0] = true; |
| 1871 |
} |
| 1872 |
} |
| 1873 |
for file in &mut self.version_files { |
| 1874 |
if !version_file_used[file.id.0] { |
| 1875 |
file.delete = true; |
| 1876 |
} |
| 1877 |
} |
| 1878 |
} |
| 1879 |
|
| 1880 |
/// Return the ELF file class that will be written. |
| 1881 |
/// |
| 1882 |
/// This can be useful for calculating sizes. |
| 1883 |
pub fn class(&self) -> write::elf::Class { |
| 1884 |
write::elf::Class { is_64: self.is_64 } |
| 1885 |
} |
| 1886 |
|
| 1887 |
/// Calculate the size of the file header. |
| 1888 |
pub fn file_header_size(&self) -> usize { |
| 1889 |
self.class().file_header_size() |
| 1890 |
} |
| 1891 |
|
| 1892 |
/// Calculate the size of the program headers. |
| 1893 |
pub fn program_headers_size(&self) -> usize { |
| 1894 |
self.segments.count() * self.class().program_header_size() |
| 1895 |
} |
| 1896 |
|
| 1897 |
/// Calculate the size of the dynamic symbol table. |
| 1898 |
/// |
| 1899 |
/// To get an accurate result, you may need to first call |
| 1900 |
/// [`Self::delete_orphan_symbols`]. |
| 1901 |
pub fn dynamic_symbol_size(&self) -> usize { |
| 1902 |
(1 + self.dynamic_symbols.count()) * self.class().sym_size() |
| 1903 |
} |
| 1904 |
|
| 1905 |
/// Calculate the size of the dynamic string table. |
| 1906 |
/// |
| 1907 |
/// This adds all of the currently used dynamic strings to a string table, |
| 1908 |
/// calculates the size of the string table, and discards the string table. |
| 1909 |
/// |
| 1910 |
/// To get an accurate result, you may need to first call |
| 1911 |
/// [`Self::delete_orphan_symbols`] and [`Self::delete_unused_versions`]. |
| 1912 |
pub fn dynamic_string_size(&self) -> usize { |
| 1913 |
let mut dynstr = write::string::StringTable::default(); |
| 1914 |
for section in &self.sections { |
| 1915 |
if let SectionData::Dynamic(dynamics) = §ion.data { |
| 1916 |
for dynamic in dynamics { |
| 1917 |
if let Dynamic::String { val, .. } = dynamic { |
| 1918 |
dynstr.add(val); |
| 1919 |
} |
| 1920 |
} |
| 1921 |
} |
| 1922 |
} |
| 1923 |
for symbol in &self.dynamic_symbols { |
| 1924 |
dynstr.add(&symbol.name); |
| 1925 |
} |
| 1926 |
if let Some(version_base) = &self.version_base { |
| 1927 |
dynstr.add(version_base); |
| 1928 |
} |
| 1929 |
for version in &self.versions { |
| 1930 |
match &version.data { |
| 1931 |
VersionData::Def(def) => { |
| 1932 |
for name in &def.names { |
| 1933 |
dynstr.add(name); |
| 1934 |
} |
| 1935 |
} |
| 1936 |
VersionData::Need(need) => { |
| 1937 |
dynstr.add(&need.name); |
| 1938 |
} |
| 1939 |
} |
| 1940 |
} |
| 1941 |
for file in &self.version_files { |
| 1942 |
dynstr.add(&file.name); |
| 1943 |
} |
| 1944 |
dynstr.size(1) |
| 1945 |
} |
| 1946 |
|
| 1947 |
/// Calculate the size of the hash table. |
| 1948 |
/// |
| 1949 |
/// To get an accurate result, you may need to first call |
| 1950 |
/// [`Self::delete_orphan_symbols`]. |
| 1951 |
pub fn hash_size(&self) -> usize { |
| 1952 |
let chain_count = 1 + self.dynamic_symbols.count(); |
| 1953 |
self.class() |
| 1954 |
.hash_size(self.hash_bucket_count, chain_count as u32) |
| 1955 |
} |
| 1956 |
|
| 1957 |
/// Calculate the size of the GNU hash table. |
| 1958 |
/// |
| 1959 |
/// To get an accurate result, you may need to first call |
| 1960 |
/// [`Self::delete_orphan_symbols`]. |
| 1961 |
pub fn gnu_hash_size(&self) -> usize { |
| 1962 |
let symbol_count = self.dynamic_symbols.count_defined(); |
| 1963 |
self.class().gnu_hash_size( |
| 1964 |
self.gnu_hash_bloom_count, |
| 1965 |
self.gnu_hash_bucket_count, |
| 1966 |
symbol_count as u32, |
| 1967 |
) |
| 1968 |
} |
| 1969 |
|
| 1970 |
/// Calculate the size of the GNU symbol version section. |
| 1971 |
/// |
| 1972 |
/// To get an accurate result, you may need to first call |
| 1973 |
/// [`Self::delete_orphan_symbols`] and [`Self::delete_unused_versions`]. |
| 1974 |
pub fn gnu_versym_size(&self) -> usize { |
| 1975 |
let symbol_count = 1 + self.dynamic_symbols.count(); |
| 1976 |
self.class().gnu_versym_size(symbol_count) |
| 1977 |
} |
| 1978 |
|
| 1979 |
/// Calculate the size of the GNU version definition section. |
| 1980 |
/// |
| 1981 |
/// To get an accurate result, you may need to first call |
| 1982 |
/// [`Self::delete_orphan_symbols`] and [`Self::delete_unused_versions`]. |
| 1983 |
pub fn gnu_verdef_size(&self) -> usize { |
| 1984 |
let mut verdef_count = 0; |
| 1985 |
let mut verdaux_count = 0; |
| 1986 |
if self.version_base.is_some() { |
| 1987 |
verdef_count += 1; |
| 1988 |
verdaux_count += 1; |
| 1989 |
} |
| 1990 |
for version in &self.versions { |
| 1991 |
if let VersionData::Def(def) = &version.data { |
| 1992 |
if !def.is_shared(verdef_count, self.version_base.as_ref()) { |
| 1993 |
verdaux_count += def.names.len(); |
| 1994 |
} |
| 1995 |
verdef_count += 1; |
| 1996 |
} |
| 1997 |
} |
| 1998 |
self.class().gnu_verdef_size(verdef_count, verdaux_count) |
| 1999 |
} |
| 2000 |
|
| 2001 |
/// Calculate the size of the GNU version dependency section. |
| 2002 |
/// |
| 2003 |
/// To get an accurate result, you may need to first call |
| 2004 |
/// [`Self::delete_orphan_symbols`] and [`Self::delete_unused_versions`]. |
| 2005 |
pub fn gnu_verneed_size(&self) -> usize { |
| 2006 |
let verneed_count = self.version_files.count(); |
| 2007 |
let mut vernaux_count = 0; |
| 2008 |
for version in &self.versions { |
| 2009 |
if let VersionData::Need(_) = &version.data { |
| 2010 |
vernaux_count += 1; |
| 2011 |
} |
| 2012 |
} |
| 2013 |
self.class().gnu_verneed_size(verneed_count, vernaux_count) |
| 2014 |
} |
| 2015 |
|
| 2016 |
/// Calculate the memory size of a section. |
| 2017 |
/// |
| 2018 |
/// Returns 0 for sections that are deleted or aren't allocated. |
| 2019 |
/// |
| 2020 |
/// To get an accurate result, you may need to first call |
| 2021 |
/// [`Self::delete_orphan_symbols`] and [`Self::delete_unused_versions`]. |
| 2022 |
pub fn section_size(&self, section: &Section<'_>) -> usize { |
| 2023 |
if section.delete || !section.is_alloc() { |
| 2024 |
return 0; |
| 2025 |
} |
| 2026 |
match §ion.data { |
| 2027 |
SectionData::Data(data) => data.len(), |
| 2028 |
SectionData::UninitializedData(len) => *len as usize, |
| 2029 |
SectionData::Relocation(relocations) => { |
| 2030 |
relocations.len() * self.class().rel_size(section.sh_type == elf::SHT_RELA) |
| 2031 |
} |
| 2032 |
SectionData::DynamicRelocation(relocations) => { |
| 2033 |
relocations.len() * self.class().rel_size(section.sh_type == elf::SHT_RELA) |
| 2034 |
} |
| 2035 |
SectionData::Note(data) => data.len(), |
| 2036 |
SectionData::Dynamic(dynamics) => (1 + dynamics.len()) * self.class().dyn_size(), |
| 2037 |
SectionData::DynamicString => self.dynamic_string_size(), |
| 2038 |
SectionData::DynamicSymbol => self.dynamic_symbol_size(), |
| 2039 |
SectionData::Hash => self.hash_size(), |
| 2040 |
SectionData::GnuHash => self.gnu_hash_size(), |
| 2041 |
SectionData::GnuVersym => self.gnu_versym_size(), |
| 2042 |
SectionData::GnuVerdef => self.gnu_verdef_size(), |
| 2043 |
SectionData::GnuVerneed => self.gnu_verneed_size(), |
| 2044 |
// None of these should be allocated. |
| 2045 |
SectionData::SectionString |
| 2046 |
| SectionData::Symbol |
| 2047 |
| SectionData::SymbolSectionIndex |
| 2048 |
| SectionData::String |
| 2049 |
| SectionData::Attributes(_) => 0, |
| 2050 |
} |
| 2051 |
} |
| 2052 |
|
| 2053 |
/// Set the `sh_size` field for every allocated section. |
| 2054 |
/// |
| 2055 |
/// This is useful to call prior to doing memory layout. |
| 2056 |
/// |
| 2057 |
/// To get an accurate result, you may need to first call |
| 2058 |
/// [`Self::delete_orphan_symbols`] and [`Self::delete_unused_versions`]. |
| 2059 |
pub fn set_section_sizes(&mut self) { |
| 2060 |
for id in (0..self.sections.len()).map(SectionId) { |
| 2061 |
let section = self.sections.get(id); |
| 2062 |
if section.delete || !section.is_alloc() { |
| 2063 |
continue; |
| 2064 |
} |
| 2065 |
self.sections.get_mut(id).sh_size = self.section_size(section) as u64; |
| 2066 |
} |
| 2067 |
} |
| 2068 |
|
| 2069 |
/// Find the section containing the dynamic table. |
| 2070 |
/// |
| 2071 |
/// This uses the `PT_DYNAMIC` program header to find the dynamic section. |
| 2072 |
pub fn dynamic_section(&self) -> Option<SectionId> { |
| 2073 |
let segment = self |
| 2074 |
.segments |
| 2075 |
.iter() |
| 2076 |
.find(|segment| segment.p_type == elf::PT_DYNAMIC)?; |
| 2077 |
// TODO: handle multiple sections in the segment? |
| 2078 |
segment.sections.iter().copied().next() |
| 2079 |
} |
| 2080 |
|
| 2081 |
/// Find the dynamic table entries. |
| 2082 |
/// |
| 2083 |
/// This uses the `PT_DYNAMIC` program header to find the dynamic section, |
| 2084 |
pub fn dynamic_data(&self) -> Option<&[Dynamic<'data>]> { |
| 2085 |
let section = self.dynamic_section()?; |
| 2086 |
match &self.sections.get(section).data { |
| 2087 |
SectionData::Dynamic(dynamics) => Some(dynamics), |
| 2088 |
_ => None, |
| 2089 |
} |
| 2090 |
} |
| 2091 |
|
| 2092 |
/// Find the dynamic table entries. |
| 2093 |
/// |
| 2094 |
/// This uses the `PT_DYNAMIC` program header to find the dynamic section, |
| 2095 |
pub fn dynamic_data_mut(&mut self) -> Option<&mut Vec<Dynamic<'data>>> { |
| 2096 |
let section = self.dynamic_section()?; |
| 2097 |
match &mut self.sections.get_mut(section).data { |
| 2098 |
SectionData::Dynamic(dynamics) => Some(dynamics), |
| 2099 |
_ => None, |
| 2100 |
} |
| 2101 |
} |
| 2102 |
|
| 2103 |
/// Find the section containing the interpreter path. |
| 2104 |
/// |
| 2105 |
/// This uses the `PT_INTERP` program header to find the interp section. |
| 2106 |
pub fn interp_section(&self) -> Option<SectionId> { |
| 2107 |
let segment = self |
| 2108 |
.segments |
| 2109 |
.iter() |
| 2110 |
.find(|segment| segment.p_type == elf::PT_INTERP)?; |
| 2111 |
// TODO: handle multiple sections in the segment? |
| 2112 |
segment.sections.iter().copied().next() |
| 2113 |
} |
| 2114 |
|
| 2115 |
/// Find the interpreter path. |
| 2116 |
/// |
| 2117 |
/// This uses the `PT_INTERP` program header to find the interp section. |
| 2118 |
pub fn interp_data(&self) -> Option<&[u8]> { |
| 2119 |
let section = self.interp_section()?; |
| 2120 |
match &self.sections.get(section).data { |
| 2121 |
SectionData::Data(data) => Some(data), |
| 2122 |
_ => None, |
| 2123 |
} |
| 2124 |
} |
| 2125 |
|
| 2126 |
/// Find the interpreter path. |
| 2127 |
/// |
| 2128 |
/// This uses the `PT_INTERP` program header to find the interp section. |
| 2129 |
pub fn interp_data_mut(&mut self) -> Option<&mut Bytes<'data>> { |
| 2130 |
let section = self.interp_section()?; |
| 2131 |
match &mut self.sections.get_mut(section).data { |
| 2132 |
SectionData::Data(data) => Some(data), |
| 2133 |
_ => None, |
| 2134 |
} |
| 2135 |
} |
| 2136 |
} |
| 2137 |
|
| 2138 |
/// ELF file header. |
| 2139 |
/// |
| 2140 |
/// This corresponds to fields in [`elf::FileHeader32`] or [`elf::FileHeader64`]. |
| 2141 |
/// This only contains the ELF file header fields that can be modified. |
| 2142 |
/// The other fields are automatically calculated. |
| 2143 |
#[derive(Debug, Default)] |
| 2144 |
pub struct Header { |
| 2145 |
/// The OS ABI field in the file header. |
| 2146 |
/// |
| 2147 |
/// One of the `ELFOSABI*` constants. |
| 2148 |
pub os_abi: u8, |
| 2149 |
/// The ABI version field in the file header. |
| 2150 |
/// |
| 2151 |
/// The meaning of this field depends on the `os_abi` value. |
| 2152 |
pub abi_version: u8, |
| 2153 |
/// The object file type in the file header. |
| 2154 |
/// |
| 2155 |
/// One of the `ET_*` constants. |
| 2156 |
pub e_type: u16, |
| 2157 |
/// The architecture in the file header. |
| 2158 |
/// |
| 2159 |
/// One of the `EM_*` constants. |
| 2160 |
pub e_machine: u16, |
| 2161 |
/// Entry point virtual address in the file header. |
| 2162 |
pub e_entry: u64, |
| 2163 |
/// The processor-specific flags in the file header. |
| 2164 |
/// |
| 2165 |
/// A combination of the `EF_*` constants. |
| 2166 |
pub e_flags: u32, |
| 2167 |
/// The file offset of the program header table. |
| 2168 |
/// |
| 2169 |
/// Writing will fail if the program header table cannot be placed at this offset. |
| 2170 |
pub e_phoff: u64, |
| 2171 |
} |
| 2172 |
|
| 2173 |
/// An ID for referring to a segment in [`Segments`]. |
| 2174 |
#[derive(Clone, Copy, PartialEq, Eq)] |
| 2175 |
pub struct SegmentId(usize); |
| 2176 |
|
| 2177 |
impl fmt::Debug for SegmentId { |
| 2178 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2179 |
write!(f, "SegmentId({})", self.0) |
| 2180 |
} |
| 2181 |
} |
| 2182 |
|
| 2183 |
impl Id for SegmentId { |
| 2184 |
fn index(&self) -> usize { |
| 2185 |
self.0 |
| 2186 |
} |
| 2187 |
} |
| 2188 |
|
| 2189 |
impl IdPrivate for SegmentId { |
| 2190 |
fn new(id: usize) -> Self { |
| 2191 |
SegmentId(id) |
| 2192 |
} |
| 2193 |
} |
| 2194 |
|
| 2195 |
/// A segment in [`Segments`]. |
| 2196 |
/// |
| 2197 |
/// This corresponds to [`elf::ProgramHeader32`] or [`elf::ProgramHeader64`]. |
| 2198 |
#[derive(Debug)] |
| 2199 |
pub struct Segment<'data> { |
| 2200 |
id: SegmentId, |
| 2201 |
/// Ignore this segment when writing the ELF file. |
| 2202 |
pub delete: bool, |
| 2203 |
/// The `p_type` field in the ELF program header. |
| 2204 |
/// |
| 2205 |
/// One of the `PT_*` constants. |
| 2206 |
pub p_type: u32, |
| 2207 |
/// The `p_flags` field in the ELF program header. |
| 2208 |
/// |
| 2209 |
/// A combination of the `PF_*` constants. |
| 2210 |
pub p_flags: u32, |
| 2211 |
/// The `p_offset` field in the ELF program header. |
| 2212 |
/// |
| 2213 |
/// This is the file offset of the data in the segment. This should |
| 2214 |
/// correspond to the file offset of the sections that are placed in |
| 2215 |
/// this segment. Currently there is no support for section data |
| 2216 |
/// that is not contained in sections. |
| 2217 |
pub p_offset: u64, |
| 2218 |
/// The `p_vaddr` field in the ELF program header. |
| 2219 |
pub p_vaddr: u64, |
| 2220 |
/// The `p_paddr` field in the ELF program header. |
| 2221 |
pub p_paddr: u64, |
| 2222 |
/// The `p_filesz` field in the ELF program header. |
| 2223 |
pub p_filesz: u64, |
| 2224 |
/// The `p_memsz` field in the ELF program header. |
| 2225 |
pub p_memsz: u64, |
| 2226 |
/// The `p_align` field in the ELF program header. |
| 2227 |
pub p_align: u64, |
| 2228 |
/// The sections contained in this segment. |
| 2229 |
pub sections: Vec<SectionId>, |
| 2230 |
// Might need to add reference to data if no sections. |
| 2231 |
marker: PhantomData<&'data ()>, |
| 2232 |
} |
| 2233 |
|
| 2234 |
impl<'data> Item for Segment<'data> { |
| 2235 |
type Id = SegmentId; |
| 2236 |
|
| 2237 |
fn is_deleted(&self) -> bool { |
| 2238 |
self.delete |
| 2239 |
} |
| 2240 |
} |
| 2241 |
|
| 2242 |
impl<'data> Segment<'data> { |
| 2243 |
/// The ID used for referring to this segment. |
| 2244 |
pub fn id(&self) -> SegmentId { |
| 2245 |
self.id |
| 2246 |
} |
| 2247 |
|
| 2248 |
/// Returns true if the segment type is `PT_LOAD`. |
| 2249 |
pub fn is_load(&self) -> bool { |
| 2250 |
self.p_type == elf::PT_LOAD |
| 2251 |
} |
| 2252 |
|
| 2253 |
/// Returns true if the segment contains the given file offset. |
| 2254 |
pub fn contains_offset(&self, offset: u64) -> bool { |
| 2255 |
offset >= self.p_offset && offset - self.p_offset < self.p_filesz |
| 2256 |
} |
| 2257 |
|
| 2258 |
/// Return the address corresponding to the given file offset. |
| 2259 |
/// |
| 2260 |
/// This will return a meaningless value if `contains_offset` is false. |
| 2261 |
pub fn address_from_offset(&self, offset: u64) -> u64 { |
| 2262 |
self.p_vaddr |
| 2263 |
.wrapping_add(offset.wrapping_sub(self.p_offset)) |
| 2264 |
} |
| 2265 |
|
| 2266 |
/// Returns true if the segment contains the given address. |
| 2267 |
pub fn contains_address(&self, address: u64) -> bool { |
| 2268 |
address >= self.p_vaddr && address - self.p_vaddr < self.p_memsz |
| 2269 |
} |
| 2270 |
|
| 2271 |
/// Remove all sections from the segment, and set its size to zero. |
| 2272 |
pub fn remove_sections(&mut self) { |
| 2273 |
self.p_filesz = 0; |
| 2274 |
self.p_memsz = 0; |
| 2275 |
self.sections.clear(); |
| 2276 |
} |
| 2277 |
|
| 2278 |
/// Add a section to the segment. |
| 2279 |
/// |
| 2280 |
/// If this is a [`elf::PT_LOAD`] segment, then the file offset and address of the |
| 2281 |
/// section is changed to be at the end of the segment. |
| 2282 |
/// |
| 2283 |
/// The segment's file and address ranges are extended to include the section. |
| 2284 |
/// This uses the `sh_size` field of the section, not the size of the section data. |
| 2285 |
/// |
| 2286 |
/// The section's id is added to the segment's list of sections. |
| 2287 |
pub fn append_section(&mut self, section: &mut Section<'_>) { |
| 2288 |
debug_assert_eq!(self.p_filesz, self.p_memsz); |
| 2289 |
if self.p_type == elf::PT_LOAD { |
| 2290 |
let align = section.sh_addralign; |
| 2291 |
let offset = (self.p_offset + self.p_filesz + (align - 1)) & !(align - 1); |
| 2292 |
let addr = (self.p_paddr + self.p_memsz + (align - 1)) & !(align - 1); |
| 2293 |
section.sh_offset = offset; |
| 2294 |
section.sh_addr = addr; |
| 2295 |
} |
| 2296 |
self.append_section_range(section); |
| 2297 |
self.sections.push(section.id); |
| 2298 |
} |
| 2299 |
|
| 2300 |
/// Extend this segment's file and address ranges to include the given section. |
| 2301 |
/// |
| 2302 |
/// If the segment's `p_memsz` is zero, then this signifies that the segment |
| 2303 |
/// has no file or address range yet. In this case, the segment's file and address |
| 2304 |
/// ranges are set equal to the section. Otherwise, the segment's file and address |
| 2305 |
/// ranges are extended to include the section. |
| 2306 |
/// |
| 2307 |
/// This uses the `sh_size` field of the section, not the size of the section data. |
| 2308 |
pub fn append_section_range(&mut self, section: &Section<'_>) { |
| 2309 |
let section_filesize = if section.sh_type == elf::SHT_NOBITS { |
| 2310 |
0 |
| 2311 |
} else { |
| 2312 |
section.sh_size |
| 2313 |
}; |
| 2314 |
if self.p_memsz == 0 { |
| 2315 |
self.p_offset = section.sh_offset; |
| 2316 |
self.p_filesz = section_filesize; |
| 2317 |
self.p_vaddr = section.sh_addr; |
| 2318 |
self.p_paddr = section.sh_addr; |
| 2319 |
self.p_memsz = section.sh_size; |
| 2320 |
} else { |
| 2321 |
if self.p_offset > section.sh_offset { |
| 2322 |
self.p_offset = section.sh_offset; |
| 2323 |
} |
| 2324 |
let filesz = section.sh_offset + section_filesize - self.p_offset; |
| 2325 |
if self.p_filesz < filesz { |
| 2326 |
self.p_filesz = filesz; |
| 2327 |
} |
| 2328 |
if self.p_vaddr > section.sh_addr { |
| 2329 |
self.p_vaddr = section.sh_addr; |
| 2330 |
self.p_paddr = section.sh_addr; |
| 2331 |
} |
| 2332 |
let memsz = section.sh_addr + section.sh_size - self.p_vaddr; |
| 2333 |
if self.p_memsz < memsz { |
| 2334 |
self.p_memsz = memsz; |
| 2335 |
} |
| 2336 |
} |
| 2337 |
} |
| 2338 |
|
| 2339 |
/// Recalculate the file and address ranges of the segment. |
| 2340 |
/// |
| 2341 |
/// Resets the segment's file and address ranges to zero, and then |
| 2342 |
/// calls `append_section_range` for each section in the segment. |
| 2343 |
pub fn recalculate_ranges(&mut self, sections: &Sections<'data>) { |
| 2344 |
self.p_offset = 0; |
| 2345 |
self.p_filesz = 0; |
| 2346 |
self.p_vaddr = 0; |
| 2347 |
self.p_paddr = 0; |
| 2348 |
self.p_memsz = 0; |
| 2349 |
let ids = core::mem::take(&mut self.sections); |
| 2350 |
for id in &ids { |
| 2351 |
let section = sections.get(*id); |
| 2352 |
self.append_section_range(section); |
| 2353 |
} |
| 2354 |
self.sections = ids; |
| 2355 |
} |
| 2356 |
} |
| 2357 |
|
| 2358 |
/// A segment table. |
| 2359 |
pub type Segments<'data> = Table<Segment<'data>>; |
| 2360 |
|
| 2361 |
impl<'data> Segments<'data> { |
| 2362 |
/// Add a new segment to the table. |
| 2363 |
pub fn add(&mut self) -> &mut Segment<'data> { |
| 2364 |
let id = self.next_id(); |
| 2365 |
self.push(Segment { |
| 2366 |
id, |
| 2367 |
delete: false, |
| 2368 |
p_type: 0, |
| 2369 |
p_flags: 0, |
| 2370 |
p_offset: 0, |
| 2371 |
p_vaddr: 0, |
| 2372 |
p_paddr: 0, |
| 2373 |
p_filesz: 0, |
| 2374 |
p_memsz: 0, |
| 2375 |
p_align: 0, |
| 2376 |
sections: Vec::new(), |
| 2377 |
marker: PhantomData, |
| 2378 |
}); |
| 2379 |
self.get_mut(id) |
| 2380 |
} |
| 2381 |
|
| 2382 |
/// Find a `PT_LOAD` segment containing the given offset. |
| 2383 |
pub fn find_load_segment_from_offset(&self, offset: u64) -> Option<&Segment<'data>> { |
| 2384 |
self.iter() |
| 2385 |
.find(|segment| segment.is_load() && segment.contains_offset(offset)) |
| 2386 |
} |
| 2387 |
|
| 2388 |
/// Add a new `PT_LOAD` segment to the table. |
| 2389 |
/// |
| 2390 |
/// The file offset and address will be derived from the current maximum for any segment. |
| 2391 |
/// The address will be chosen so that `p_paddr % align == p_offset % align`. |
| 2392 |
/// You may wish to use [`Builder::load_align`] for the alignment. |
| 2393 |
pub fn add_load_segment(&mut self, flags: u32, align: u64) -> &mut Segment<'data> { |
| 2394 |
let mut max_offset = 0; |
| 2395 |
let mut max_addr = 0; |
| 2396 |
for segment in &*self { |
| 2397 |
let offset = segment.p_offset + segment.p_filesz; |
| 2398 |
if max_offset < offset { |
| 2399 |
max_offset = offset; |
| 2400 |
} |
| 2401 |
let addr = segment.p_vaddr + segment.p_memsz; |
| 2402 |
if max_addr < addr { |
| 2403 |
max_addr = addr; |
| 2404 |
} |
| 2405 |
} |
| 2406 |
// No alignment is required for the segment file offset because sections |
| 2407 |
// will add their alignment to the file offset when they are added. |
| 2408 |
let offset = max_offset; |
| 2409 |
// The address must be chosen so that addr % align == offset % align. |
| 2410 |
let addr = ((max_addr + (align - 1)) & !(align - 1)) + (offset & (align - 1)); |
| 2411 |
|
| 2412 |
let segment = self.add(); |
| 2413 |
segment.p_type = elf::PT_LOAD; |
| 2414 |
segment.p_flags = flags; |
| 2415 |
segment.p_offset = offset; |
| 2416 |
segment.p_vaddr = addr; |
| 2417 |
segment.p_paddr = addr; |
| 2418 |
segment.p_align = align; |
| 2419 |
segment |
| 2420 |
} |
| 2421 |
|
| 2422 |
/// Add a copy of a segment to the table. |
| 2423 |
/// |
| 2424 |
/// This will copy the segment type, flags and alignment. |
| 2425 |
/// |
| 2426 |
/// Additionally, if the segment type is `PT_LOAD`, then the file offset and address |
| 2427 |
/// will be set as in `add_load_segment`. |
| 2428 |
pub fn copy(&mut self, id: SegmentId) -> &mut Segment<'data> { |
| 2429 |
let segment = self.get(id); |
| 2430 |
let p_type = segment.p_type; |
| 2431 |
let p_flags = segment.p_flags; |
| 2432 |
let p_align = segment.p_align; |
| 2433 |
if p_type == elf::PT_LOAD { |
| 2434 |
self.add_load_segment(p_flags, p_align) |
| 2435 |
} else { |
| 2436 |
let segment = self.add(); |
| 2437 |
segment.p_type = p_type; |
| 2438 |
segment.p_flags = p_flags; |
| 2439 |
segment.p_align = p_align; |
| 2440 |
segment |
| 2441 |
} |
| 2442 |
} |
| 2443 |
} |
| 2444 |
|
| 2445 |
/// An ID for referring to a section in [`Sections`]. |
| 2446 |
#[derive(Clone, Copy, PartialEq, Eq)] |
| 2447 |
pub struct SectionId(usize); |
| 2448 |
|
| 2449 |
impl fmt::Debug for SectionId { |
| 2450 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2451 |
write!(f, "SectionId({})", self.0) |
| 2452 |
} |
| 2453 |
} |
| 2454 |
|
| 2455 |
impl Id for SectionId { |
| 2456 |
fn index(&self) -> usize { |
| 2457 |
self.0 |
| 2458 |
} |
| 2459 |
} |
| 2460 |
|
| 2461 |
impl IdPrivate for SectionId { |
| 2462 |
fn new(id: usize) -> Self { |
| 2463 |
SectionId(id) |
| 2464 |
} |
| 2465 |
} |
| 2466 |
|
| 2467 |
/// A section in [`Sections`]. |
| 2468 |
/// |
| 2469 |
/// This corresponds to [`elf::SectionHeader32`] or [`elf::SectionHeader64`]. |
| 2470 |
#[derive(Debug)] |
| 2471 |
pub struct Section<'data> { |
| 2472 |
id: SectionId, |
| 2473 |
/// Ignore this section when writing the ELF file. |
| 2474 |
pub delete: bool, |
| 2475 |
/// The name of the section. |
| 2476 |
/// |
| 2477 |
/// This is automatically added to the section header string table, |
| 2478 |
/// and the resulting string table offset is used to set the `sh_name` |
| 2479 |
/// field in the ELF section header. |
| 2480 |
pub name: ByteString<'data>, |
| 2481 |
/// The `sh_type` field in the ELF section header. |
| 2482 |
/// |
| 2483 |
/// One of the `SHT_*` constants. |
| 2484 |
pub sh_type: u32, |
| 2485 |
/// The `sh_flags` field in the ELF section header. |
| 2486 |
/// |
| 2487 |
/// A combination of the `SHF_*` constants. |
| 2488 |
pub sh_flags: u64, |
| 2489 |
/// The `sh_addr` field in the ELF section header. |
| 2490 |
pub sh_addr: u64, |
| 2491 |
/// The `sh_offset` field in the ELF section header. |
| 2492 |
/// |
| 2493 |
/// This is the file offset of the data in the section. |
| 2494 |
/// Writing will fail if the data cannot be placed at this offset. |
| 2495 |
/// |
| 2496 |
/// This is only used for sections that have `SHF_ALLOC` set. |
| 2497 |
/// For other sections, the section data is written at the next available |
| 2498 |
/// offset. |
| 2499 |
pub sh_offset: u64, |
| 2500 |
/// The `sh_size` field in the ELF section header. |
| 2501 |
/// |
| 2502 |
/// This size is not used when writing. The size of the `data` field is |
| 2503 |
/// used instead. |
| 2504 |
pub sh_size: u64, |
| 2505 |
/// The ID of the section linked to by the `sh_link` field in the ELF section header. |
| 2506 |
pub sh_link_section: Option<SectionId>, |
| 2507 |
/// The `sh_info` field in the ELF section header. |
| 2508 |
/// |
| 2509 |
/// Only used if `sh_info_section` is `None`. |
| 2510 |
pub sh_info: u32, |
| 2511 |
/// The ID of the section linked to by the `sh_info` field in the ELF section header. |
| 2512 |
pub sh_info_section: Option<SectionId>, |
| 2513 |
/// The `sh_addralign` field in the ELF section header. |
| 2514 |
pub sh_addralign: u64, |
| 2515 |
/// The `sh_entsize` field in the ELF section header. |
| 2516 |
pub sh_entsize: u64, |
| 2517 |
/// The section data. |
| 2518 |
pub data: SectionData<'data>, |
| 2519 |
} |
| 2520 |
|
| 2521 |
impl<'data> Item for Section<'data> { |
| 2522 |
type Id = SectionId; |
| 2523 |
|
| 2524 |
fn is_deleted(&self) -> bool { |
| 2525 |
self.delete |
| 2526 |
} |
| 2527 |
} |
| 2528 |
|
| 2529 |
impl<'data> Section<'data> { |
| 2530 |
/// The ID used for referring to this section. |
| 2531 |
pub fn id(&self) -> SectionId { |
| 2532 |
self.id |
| 2533 |
} |
| 2534 |
|
| 2535 |
/// Returns true if the section flags include `SHF_ALLOC`. |
| 2536 |
pub fn is_alloc(&self) -> bool { |
| 2537 |
self.sh_flags & u64::from(elf::SHF_ALLOC) != 0 |
| 2538 |
} |
| 2539 |
|
| 2540 |
/// Return the segment permission flags that are equivalent to the section flags. |
| 2541 |
pub fn p_flags(&self) -> u32 { |
| 2542 |
let mut p_flags = elf::PF_R; |
| 2543 |
if self.sh_flags & u64::from(elf::SHF_WRITE) != 0 { |
| 2544 |
p_flags |= elf::PF_W; |
| 2545 |
} |
| 2546 |
if self.sh_flags & u64::from(elf::SHF_EXECINSTR) != 0 { |
| 2547 |
p_flags |= elf::PF_X; |
| 2548 |
} |
| 2549 |
p_flags |
| 2550 |
} |
| 2551 |
} |
| 2552 |
|
| 2553 |
/// The data for a [`Section`]. |
| 2554 |
#[derive(Debug, Clone)] |
| 2555 |
pub enum SectionData<'data> { |
| 2556 |
/// The section contains the given raw data bytes. |
| 2557 |
Data(Bytes<'data>), |
| 2558 |
/// The section contains uninitialised data bytes of the given length. |
| 2559 |
UninitializedData(u64), |
| 2560 |
/// The section contains relocations. |
| 2561 |
Relocation(Vec<Relocation>), |
| 2562 |
/// The section contains dynamic relocations. |
| 2563 |
DynamicRelocation(Vec<DynamicRelocation>), |
| 2564 |
/// The section contains notes. |
| 2565 |
// TODO: parse notes |
| 2566 |
Note(Bytes<'data>), |
| 2567 |
/// The section contains dynamic entries. |
| 2568 |
Dynamic(Vec<Dynamic<'data>>), |
| 2569 |
/// The section contains attributes. |
| 2570 |
/// |
| 2571 |
/// This may be GNU attributes or other vendor-specific attributes. |
| 2572 |
Attributes(AttributesSection<'data>), |
| 2573 |
/// The section contains the strings for the section headers. |
| 2574 |
SectionString, |
| 2575 |
/// The section contains the symbol table. |
| 2576 |
Symbol, |
| 2577 |
/// The section contains the extended section index for the symbol table. |
| 2578 |
SymbolSectionIndex, |
| 2579 |
/// The section contains the strings for symbol table. |
| 2580 |
String, |
| 2581 |
/// The section contains the dynamic symbol table. |
| 2582 |
DynamicSymbol, |
| 2583 |
/// The section contains the dynamic string table. |
| 2584 |
DynamicString, |
| 2585 |
/// The section contains the hash table. |
| 2586 |
Hash, |
| 2587 |
/// The section contains the GNU hash table. |
| 2588 |
GnuHash, |
| 2589 |
/// The section contains the GNU symbol versions. |
| 2590 |
GnuVersym, |
| 2591 |
/// The section contains the GNU version definitions. |
| 2592 |
GnuVerdef, |
| 2593 |
/// The section contains the GNU version dependencies. |
| 2594 |
GnuVerneed, |
| 2595 |
} |
| 2596 |
|
| 2597 |
/// A section table. |
| 2598 |
pub type Sections<'data> = Table<Section<'data>>; |
| 2599 |
|
| 2600 |
impl<'data> Sections<'data> { |
| 2601 |
/// Add a new section to the table. |
| 2602 |
pub fn add(&mut self) -> &mut Section<'data> { |
| 2603 |
let id = self.next_id(); |
| 2604 |
self.push(Section { |
| 2605 |
id, |
| 2606 |
delete: false, |
| 2607 |
name: ByteString::default(), |
| 2608 |
sh_type: 0, |
| 2609 |
sh_flags: 0, |
| 2610 |
sh_addr: 0, |
| 2611 |
sh_offset: 0, |
| 2612 |
sh_size: 0, |
| 2613 |
sh_link_section: None, |
| 2614 |
sh_info: 0, |
| 2615 |
sh_info_section: None, |
| 2616 |
sh_addralign: 0, |
| 2617 |
sh_entsize: 0, |
| 2618 |
data: SectionData::Data(Bytes::default()), |
| 2619 |
}) |
| 2620 |
} |
| 2621 |
|
| 2622 |
/// Add a copy of a section to the table. |
| 2623 |
/// |
| 2624 |
/// This will set the file offset of the copy to zero. |
| 2625 |
/// [`Segment::append_section`] can be used to assign a valid file offset and a new address. |
| 2626 |
pub fn copy(&mut self, id: SectionId) -> &mut Section<'data> { |
| 2627 |
let section = self.get(id); |
| 2628 |
let id = self.next_id(); |
| 2629 |
let name = section.name.clone(); |
| 2630 |
let sh_type = section.sh_type; |
| 2631 |
let sh_flags = section.sh_flags; |
| 2632 |
let sh_addr = section.sh_addr; |
| 2633 |
let sh_size = section.sh_size; |
| 2634 |
let sh_link_section = section.sh_link_section; |
| 2635 |
let sh_info = section.sh_info; |
| 2636 |
let sh_info_section = section.sh_info_section; |
| 2637 |
let sh_addralign = section.sh_addralign; |
| 2638 |
let sh_entsize = section.sh_entsize; |
| 2639 |
let data = section.data.clone(); |
| 2640 |
self.push(Section { |
| 2641 |
id, |
| 2642 |
delete: false, |
| 2643 |
name, |
| 2644 |
sh_type, |
| 2645 |
sh_flags, |
| 2646 |
sh_addr, |
| 2647 |
sh_offset: 0, |
| 2648 |
sh_size, |
| 2649 |
sh_link_section, |
| 2650 |
sh_info, |
| 2651 |
sh_info_section, |
| 2652 |
sh_addralign, |
| 2653 |
sh_entsize, |
| 2654 |
data, |
| 2655 |
}) |
| 2656 |
} |
| 2657 |
} |
| 2658 |
|
| 2659 |
/// An ID for referring to a symbol in [`Symbols`]. |
| 2660 |
#[derive(Clone, Copy, PartialEq, Eq)] |
| 2661 |
pub struct SymbolId<const DYNAMIC: bool = false>(usize); |
| 2662 |
|
| 2663 |
impl<const DYNAMIC: bool> fmt::Debug for SymbolId<DYNAMIC> { |
| 2664 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2665 |
self.0.fmt(f) |
| 2666 |
} |
| 2667 |
} |
| 2668 |
|
| 2669 |
impl<const DYNAMIC: bool> Id for SymbolId<DYNAMIC> { |
| 2670 |
fn index(&self) -> usize { |
| 2671 |
self.0 |
| 2672 |
} |
| 2673 |
} |
| 2674 |
|
| 2675 |
impl<const DYNAMIC: bool> IdPrivate for SymbolId<DYNAMIC> { |
| 2676 |
fn new(id: usize) -> Self { |
| 2677 |
SymbolId(id) |
| 2678 |
} |
| 2679 |
} |
| 2680 |
|
| 2681 |
/// A symbol in [`Symbols`]. |
| 2682 |
/// |
| 2683 |
/// This corresponds to [`elf::Sym32`] or [`elf::Sym64`]. |
| 2684 |
#[derive(Debug)] |
| 2685 |
pub struct Symbol<'data, const DYNAMIC: bool = false> { |
| 2686 |
id: SymbolId<DYNAMIC>, |
| 2687 |
/// Ignore this symbol when writing the ELF file. |
| 2688 |
pub delete: bool, |
| 2689 |
/// The name of the symbol. |
| 2690 |
pub name: ByteString<'data>, |
| 2691 |
/// The section referenced by the symbol. |
| 2692 |
/// |
| 2693 |
/// Used to set the `st_shndx` field in the ELF symbol. |
| 2694 |
pub section: Option<SectionId>, |
| 2695 |
/// The `st_info` field in the ELF symbol. |
| 2696 |
pub st_info: u8, |
| 2697 |
/// The `st_other` field in the ELF symbol. |
| 2698 |
pub st_other: u8, |
| 2699 |
/// The `st_shndx` field in the ELF symbol. |
| 2700 |
/// |
| 2701 |
/// Only used if `Self::section` is `None`. |
| 2702 |
pub st_shndx: u16, |
| 2703 |
/// The `st_value` field in the ELF symbol. |
| 2704 |
pub st_value: u64, |
| 2705 |
/// The `st_size` field in the ELF symbol. |
| 2706 |
pub st_size: u64, |
| 2707 |
/// GNU version for dynamic symbols. |
| 2708 |
pub version: VersionId, |
| 2709 |
/// Set the [`elf::VERSYM_HIDDEN`] flag for this symbol. |
| 2710 |
pub version_hidden: bool, |
| 2711 |
} |
| 2712 |
|
| 2713 |
impl<'data, const DYNAMIC: bool> Item for Symbol<'data, DYNAMIC> { |
| 2714 |
type Id = SymbolId<DYNAMIC>; |
| 2715 |
|
| 2716 |
fn is_deleted(&self) -> bool { |
| 2717 |
self.delete |
| 2718 |
} |
| 2719 |
} |
| 2720 |
|
| 2721 |
impl<'data, const DYNAMIC: bool> Symbol<'data, DYNAMIC> { |
| 2722 |
/// The ID used for referring to this symbol. |
| 2723 |
pub fn id(&self) -> SymbolId<DYNAMIC> { |
| 2724 |
self.id |
| 2725 |
} |
| 2726 |
|
| 2727 |
/// Get the `st_bind` component of the `st_info` field. |
| 2728 |
#[inline] |
| 2729 |
pub fn st_bind(&self) -> u8 { |
| 2730 |
self.st_info >> 4 |
| 2731 |
} |
| 2732 |
|
| 2733 |
/// Get the `st_type` component of the `st_info` field. |
| 2734 |
#[inline] |
| 2735 |
pub fn st_type(&self) -> u8 { |
| 2736 |
self.st_info & 0xf |
| 2737 |
} |
| 2738 |
|
| 2739 |
/// Set the `st_info` field given the `st_bind` and `st_type` components. |
| 2740 |
#[inline] |
| 2741 |
pub fn set_st_info(&mut self, st_bind: u8, st_type: u8) { |
| 2742 |
self.st_info = (st_bind << 4) + (st_type & 0xf); |
| 2743 |
} |
| 2744 |
} |
| 2745 |
|
| 2746 |
/// A symbol table. |
| 2747 |
pub type Symbols<'data, const DYNAMIC: bool = false> = Table<Symbol<'data, DYNAMIC>>; |
| 2748 |
|
| 2749 |
impl<'data, const DYNAMIC: bool> Symbols<'data, DYNAMIC> { |
| 2750 |
/// Number of defined symbols. |
| 2751 |
pub fn count_defined(&self) -> usize { |
| 2752 |
self.into_iter() |
| 2753 |
.filter(|symbol| symbol.st_shndx != elf::SHN_UNDEF) |
| 2754 |
.count() |
| 2755 |
} |
| 2756 |
|
| 2757 |
/// Add a new symbol to the table. |
| 2758 |
pub fn add(&mut self) -> &mut Symbol<'data, DYNAMIC> { |
| 2759 |
let id = self.next_id(); |
| 2760 |
self.push(Symbol { |
| 2761 |
id, |
| 2762 |
delete: false, |
| 2763 |
name: ByteString::default(), |
| 2764 |
section: None, |
| 2765 |
st_info: 0, |
| 2766 |
st_other: 0, |
| 2767 |
st_shndx: 0, |
| 2768 |
st_value: 0, |
| 2769 |
st_size: 0, |
| 2770 |
version: VersionId::local(), |
| 2771 |
version_hidden: false, |
| 2772 |
}) |
| 2773 |
} |
| 2774 |
} |
| 2775 |
|
| 2776 |
/// A relocation stored in a [`Section`]. |
| 2777 |
/// |
| 2778 |
/// This corresponds to [`elf::Rel32`], [`elf::Rela32`], [`elf::Rel64`] or [`elf::Rela64`]. |
| 2779 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 2780 |
pub struct Relocation<const DYNAMIC: bool = false> { |
| 2781 |
/// The `r_offset` field in the ELF relocation. |
| 2782 |
pub r_offset: u64, |
| 2783 |
/// The symbol referenced by the ELF relocation. |
| 2784 |
pub symbol: Option<SymbolId<DYNAMIC>>, |
| 2785 |
/// The `r_type` field in the ELF relocation. |
| 2786 |
pub r_type: u32, |
| 2787 |
/// The `r_addend` field in the ELF relocation. |
| 2788 |
/// |
| 2789 |
/// Only used if the section type is `SHT_RELA`. |
| 2790 |
pub r_addend: i64, |
| 2791 |
} |
| 2792 |
|
| 2793 |
/// A dynamic symbol ID. |
| 2794 |
pub type DynamicSymbolId = SymbolId<true>; |
| 2795 |
|
| 2796 |
/// A dynamic symbol. |
| 2797 |
pub type DynamicSymbol<'data> = Symbol<'data, true>; |
| 2798 |
|
| 2799 |
/// A dynamic symbol table. |
| 2800 |
pub type DynamicSymbols<'data> = Symbols<'data, true>; |
| 2801 |
|
| 2802 |
/// A dynamic relocation. |
| 2803 |
pub type DynamicRelocation = Relocation<true>; |
| 2804 |
|
| 2805 |
/// An entry in the dynamic section. |
| 2806 |
/// |
| 2807 |
/// This corresponds to [`elf::Dyn32`] or [`elf::Dyn64`]. |
| 2808 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 2809 |
pub enum Dynamic<'data> { |
| 2810 |
/// The value is an automatically generated integer. |
| 2811 |
/// |
| 2812 |
/// Writing will fail if the value cannot be automatically generated. |
| 2813 |
Auto { |
| 2814 |
/// The `d_tag` field in the dynamic entry. |
| 2815 |
/// |
| 2816 |
/// One of the `DT_*` values. |
| 2817 |
tag: u32, |
| 2818 |
}, |
| 2819 |
/// The value is an integer. |
| 2820 |
Integer { |
| 2821 |
/// The `d_tag` field in the dynamic entry. |
| 2822 |
/// |
| 2823 |
/// One of the `DT_*` values. |
| 2824 |
tag: u32, |
| 2825 |
/// The `d_val` field in the dynamic entry. |
| 2826 |
val: u64, |
| 2827 |
}, |
| 2828 |
/// The value is a string. |
| 2829 |
String { |
| 2830 |
/// The `d_tag` field in the dynamic entry. |
| 2831 |
/// |
| 2832 |
/// One of the `DT_*` values. |
| 2833 |
tag: u32, |
| 2834 |
/// The string value. |
| 2835 |
/// |
| 2836 |
/// This will be stored in the dynamic string section. |
| 2837 |
val: ByteString<'data>, |
| 2838 |
}, |
| 2839 |
} |
| 2840 |
|
| 2841 |
impl<'data> Dynamic<'data> { |
| 2842 |
/// The `d_tag` field in the dynamic entry. |
| 2843 |
/// |
| 2844 |
/// One of the `DT_*` values. |
| 2845 |
pub fn tag(&self) -> u32 { |
| 2846 |
match self { |
| 2847 |
Dynamic::Auto { tag } => *tag, |
| 2848 |
Dynamic::Integer { tag, .. } => *tag, |
| 2849 |
Dynamic::String { tag, .. } => *tag, |
| 2850 |
} |
| 2851 |
} |
| 2852 |
} |
| 2853 |
|
| 2854 |
/// An ID for referring to a filename in [`VersionFiles`]. |
| 2855 |
#[derive(Clone, Copy, PartialEq, Eq)] |
| 2856 |
pub struct VersionFileId(usize); |
| 2857 |
|
| 2858 |
impl fmt::Debug for VersionFileId { |
| 2859 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2860 |
write!(f, "VersionFileId({})", self.0) |
| 2861 |
} |
| 2862 |
} |
| 2863 |
|
| 2864 |
impl Id for VersionFileId { |
| 2865 |
fn index(&self) -> usize { |
| 2866 |
self.0 |
| 2867 |
} |
| 2868 |
} |
| 2869 |
|
| 2870 |
impl IdPrivate for VersionFileId { |
| 2871 |
fn new(id: usize) -> Self { |
| 2872 |
VersionFileId(id) |
| 2873 |
} |
| 2874 |
} |
| 2875 |
|
| 2876 |
/// A filename used for GNU versioning. |
| 2877 |
/// |
| 2878 |
/// Stored in [`VersionFiles`]. |
| 2879 |
#[derive(Debug)] |
| 2880 |
pub struct VersionFile<'data> { |
| 2881 |
id: VersionFileId, |
| 2882 |
/// Ignore this file when writing the ELF file. |
| 2883 |
pub delete: bool, |
| 2884 |
/// The filename. |
| 2885 |
pub name: ByteString<'data>, |
| 2886 |
} |
| 2887 |
|
| 2888 |
impl<'data> Item for VersionFile<'data> { |
| 2889 |
type Id = VersionFileId; |
| 2890 |
|
| 2891 |
fn is_deleted(&self) -> bool { |
| 2892 |
self.delete |
| 2893 |
} |
| 2894 |
} |
| 2895 |
|
| 2896 |
impl<'data> VersionFile<'data> { |
| 2897 |
/// The ID used for referring to this filename. |
| 2898 |
pub fn id(&self) -> VersionFileId { |
| 2899 |
self.id |
| 2900 |
} |
| 2901 |
} |
| 2902 |
|
| 2903 |
/// A table of filenames used for GNU versioning. |
| 2904 |
pub type VersionFiles<'data> = Table<VersionFile<'data>>; |
| 2905 |
|
| 2906 |
impl<'data> VersionFiles<'data> { |
| 2907 |
/// Add a new filename to the table. |
| 2908 |
pub fn add(&mut self, name: ByteString<'data>) -> VersionFileId { |
| 2909 |
let id = self.next_id(); |
| 2910 |
self.push(VersionFile { |
| 2911 |
id, |
| 2912 |
name, |
| 2913 |
delete: false, |
| 2914 |
}); |
| 2915 |
id |
| 2916 |
} |
| 2917 |
} |
| 2918 |
|
| 2919 |
const VERSION_ID_BASE: usize = 2; |
| 2920 |
|
| 2921 |
/// An ID for referring to a version in [`Versions`]. |
| 2922 |
#[derive(Clone, Copy, PartialEq, Eq)] |
| 2923 |
pub struct VersionId(usize); |
| 2924 |
|
| 2925 |
impl fmt::Debug for VersionId { |
| 2926 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2927 |
write!(f, "VersionId({})", self.0) |
| 2928 |
} |
| 2929 |
} |
| 2930 |
|
| 2931 |
impl Id for VersionId { |
| 2932 |
fn index(&self) -> usize { |
| 2933 |
self.0 - VERSION_ID_BASE |
| 2934 |
} |
| 2935 |
} |
| 2936 |
|
| 2937 |
impl IdPrivate for VersionId { |
| 2938 |
fn new(id: usize) -> Self { |
| 2939 |
VersionId(VERSION_ID_BASE + id) |
| 2940 |
} |
| 2941 |
} |
| 2942 |
|
| 2943 |
impl VersionId { |
| 2944 |
/// Return `True` if this is a special version that does not exist in the version table. |
| 2945 |
pub fn is_special(&self) -> bool { |
| 2946 |
self.0 < VERSION_ID_BASE |
| 2947 |
} |
| 2948 |
|
| 2949 |
/// Return the ID for a version index of [`elf::VER_NDX_LOCAL`]. |
| 2950 |
pub fn local() -> Self { |
| 2951 |
VersionId(elf::VER_NDX_LOCAL as usize) |
| 2952 |
} |
| 2953 |
|
| 2954 |
/// Return the ID for a version index of [`elf::VER_NDX_GLOBAL`]. |
| 2955 |
pub fn global() -> Self { |
| 2956 |
VersionId(elf::VER_NDX_GLOBAL as usize) |
| 2957 |
} |
| 2958 |
} |
| 2959 |
|
| 2960 |
/// A version for a symbol. |
| 2961 |
#[derive(Debug)] |
| 2962 |
pub struct Version<'data> { |
| 2963 |
id: VersionId, |
| 2964 |
/// The data for this version. |
| 2965 |
pub data: VersionData<'data>, |
| 2966 |
/// Ignore this version when writing the ELF file. |
| 2967 |
pub delete: bool, |
| 2968 |
} |
| 2969 |
|
| 2970 |
impl<'data> Item for Version<'data> { |
| 2971 |
type Id = VersionId; |
| 2972 |
|
| 2973 |
fn is_deleted(&self) -> bool { |
| 2974 |
self.delete |
| 2975 |
} |
| 2976 |
} |
| 2977 |
|
| 2978 |
impl<'data> Version<'data> { |
| 2979 |
/// The ID used for referring to this version. |
| 2980 |
pub fn id(&self) -> VersionId { |
| 2981 |
self.id |
| 2982 |
} |
| 2983 |
} |
| 2984 |
|
| 2985 |
/// The data for a version for a symbol. |
| 2986 |
#[derive(Debug)] |
| 2987 |
pub enum VersionData<'data> { |
| 2988 |
/// The version for a defined symbol. |
| 2989 |
Def(VersionDef<'data>), |
| 2990 |
/// The version for an undefined symbol. |
| 2991 |
Need(VersionNeed<'data>), |
| 2992 |
} |
| 2993 |
|
| 2994 |
/// A GNU version definition. |
| 2995 |
#[derive(Debug)] |
| 2996 |
pub struct VersionDef<'data> { |
| 2997 |
/// The names for the version. |
| 2998 |
/// |
| 2999 |
/// This usually has two elements. The first element is the name of this |
| 3000 |
/// version, and the second element is the name of the previous version |
| 3001 |
/// in the tree of versions. |
| 3002 |
pub names: Vec<ByteString<'data>>, |
| 3003 |
/// The version flags. |
| 3004 |
/// |
| 3005 |
/// A combination of the `VER_FLG_*` constants. |
| 3006 |
pub flags: u16, |
| 3007 |
} |
| 3008 |
|
| 3009 |
impl<'data> VersionDef<'data> { |
| 3010 |
/// Optimise for the common case where the first version is the same as the base version. |
| 3011 |
fn is_shared(&self, index: usize, base: Option<&ByteString<'_>>) -> bool { |
| 3012 |
index == 1 && self.names.len() == 1 && self.names.first() == base |
| 3013 |
} |
| 3014 |
} |
| 3015 |
|
| 3016 |
/// A GNU version dependency. |
| 3017 |
#[derive(Debug)] |
| 3018 |
pub struct VersionNeed<'data> { |
| 3019 |
/// The filename of the library providing this version. |
| 3020 |
pub file: VersionFileId, |
| 3021 |
/// The name of the version. |
| 3022 |
pub name: ByteString<'data>, |
| 3023 |
/// The version flags. |
| 3024 |
/// |
| 3025 |
/// A combination of the `VER_FLG_*` constants. |
| 3026 |
pub flags: u16, |
| 3027 |
} |
| 3028 |
|
| 3029 |
/// A table of versions that are referenced by symbols. |
| 3030 |
pub type Versions<'data> = Table<Version<'data>>; |
| 3031 |
|
| 3032 |
impl<'data> Versions<'data> { |
| 3033 |
/// Add a version. |
| 3034 |
pub fn add(&mut self, data: VersionData<'data>) -> VersionId { |
| 3035 |
let id = self.next_id(); |
| 3036 |
self.push(Version { |
| 3037 |
id, |
| 3038 |
data, |
| 3039 |
delete: false, |
| 3040 |
}); |
| 3041 |
id |
| 3042 |
} |
| 3043 |
} |
| 3044 |
|
| 3045 |
/// The contents of an attributes section. |
| 3046 |
#[derive(Debug, Default, Clone)] |
| 3047 |
pub struct AttributesSection<'data> { |
| 3048 |
/// The subsections. |
| 3049 |
pub subsections: Vec<AttributesSubsection<'data>>, |
| 3050 |
} |
| 3051 |
|
| 3052 |
impl<'data> AttributesSection<'data> { |
| 3053 |
/// Create a new attributes section. |
| 3054 |
pub fn new() -> Self { |
| 3055 |
Self::default() |
| 3056 |
} |
| 3057 |
} |
| 3058 |
|
| 3059 |
/// A subsection of an attributes section. |
| 3060 |
#[derive(Debug, Clone)] |
| 3061 |
pub struct AttributesSubsection<'data> { |
| 3062 |
/// The vendor namespace for these attributes. |
| 3063 |
pub vendor: ByteString<'data>, |
| 3064 |
/// The sub-subsections. |
| 3065 |
pub subsubsections: Vec<AttributesSubsubsection<'data>>, |
| 3066 |
} |
| 3067 |
|
| 3068 |
impl<'data> AttributesSubsection<'data> { |
| 3069 |
/// Create a new subsection. |
| 3070 |
pub fn new(vendor: ByteString<'data>) -> Self { |
| 3071 |
AttributesSubsection { |
| 3072 |
vendor, |
| 3073 |
subsubsections: Vec::new(), |
| 3074 |
} |
| 3075 |
} |
| 3076 |
} |
| 3077 |
|
| 3078 |
/// A sub-subsection in an attributes section. |
| 3079 |
#[derive(Debug, Clone)] |
| 3080 |
pub struct AttributesSubsubsection<'data> { |
| 3081 |
/// The sub-subsection tag. |
| 3082 |
pub tag: AttributeTag, |
| 3083 |
/// The data containing the attributes. |
| 3084 |
pub data: Bytes<'data>, |
| 3085 |
} |
| 3086 |
|
| 3087 |
/// The tag for a sub-subsection in an attributes section. |
| 3088 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 3089 |
pub enum AttributeTag { |
| 3090 |
/// The attributes apply to the whole file. |
| 3091 |
/// |
| 3092 |
/// Correspeonds to [`elf::Tag_File`]. |
| 3093 |
File, |
| 3094 |
/// The attributes apply to the given sections. |
| 3095 |
/// |
| 3096 |
/// Correspeonds to [`elf::Tag_Section`]. |
| 3097 |
Section(Vec<SectionId>), |
| 3098 |
/// The attributes apply to the given symbols. |
| 3099 |
/// |
| 3100 |
/// Correspeonds to [`elf::Tag_Symbol`]. |
| 3101 |
Symbol(Vec<SymbolId>), |
| 3102 |
} |
| 3103 |
|
| 3104 |
impl AttributeTag { |
| 3105 |
/// Return the corresponding `elf::Tag_*` value for this tag. |
| 3106 |
pub fn tag(&self) -> u8 { |
| 3107 |
match self { |
| 3108 |
AttributeTag::File => elf::Tag_File, |
| 3109 |
AttributeTag::Section(_) => elf::Tag_Section, |
| 3110 |
AttributeTag::Symbol(_) => elf::Tag_Symbol, |
| 3111 |
} |
| 3112 |
} |
| 3113 |
} |