Debian Codegraph @

third_party/rust/object/src/write/elf/object.rs

raw
1 use alloc::vec::Vec;
2
3 use crate::write::elf::writer::*;
4 use crate::write::string::StringId;
5 use crate::write::*;
6 use crate::{elf, pod};
7
8 #[derive(Clone, Copy)]
9 struct ComdatOffsets {
10 offset: usize,
11 str_id: StringId,
12 }
13
14 #[derive(Clone, Copy)]
15 struct SectionOffsets {
16 index: SectionIndex,
17 offset: usize,
18 str_id: StringId,
19 reloc_offset: usize,
20 reloc_str_id: Option<StringId>,
21 }
22
23 #[derive(Default, Clone, Copy)]
24 struct SymbolOffsets {
25 index: SymbolIndex,
26 str_id: Option<StringId>,
27 }
28
29 // Public methods.
30 impl<'a> Object<'a> {
31 /// Add a property with a u32 value to the ELF ".note.gnu.property" section.
32 ///
33 /// Requires `feature = "elf"`.
34 pub fn add_elf_gnu_property_u32(&mut self, property: u32, value: u32) {
35 if self.format != BinaryFormat::Elf {
36 return;
37 }
38
39 let align = if self.elf_is_64() { 8 } else { 4 };
40 let mut data = Vec::with_capacity(32);
41 let n_name = b"GNU\0";
42 data.extend_from_slice(pod::bytes_of(&elf::NoteHeader32 {
43 n_namesz: U32::new(self.endian, n_name.len() as u32),
44 n_descsz: U32::new(self.endian, util::align(3 * 4, align) as u32),
45 n_type: U32::new(self.endian, elf::NT_GNU_PROPERTY_TYPE_0),
46 }));
47 data.extend_from_slice(n_name);
48 // This happens to already be aligned correctly.
49 debug_assert_eq!(util::align(data.len(), align), data.len());
50 data.extend_from_slice(pod::bytes_of(&U32::new(self.endian, property)));
51 // Value size
52 data.extend_from_slice(pod::bytes_of(&U32::new(self.endian, 4)));
53 data.extend_from_slice(pod::bytes_of(&U32::new(self.endian, value)));
54 util::write_align(&mut data, align);
55
56 let section = self.section_id(StandardSection::GnuProperty);
57 self.append_section_data(section, &data, align as u64);
58 }
59 }
60
61 // Private methods.
62 impl<'a> Object<'a> {
63 pub(crate) fn elf_section_info(
64 &self,
65 section: StandardSection,
66 ) -> (&'static [u8], &'static [u8], SectionKind, SectionFlags) {
67 match section {
68 StandardSection::Text => (&[], &b".text"[..], SectionKind::Text, SectionFlags::None),
69 StandardSection::Data => (&[], &b".data"[..], SectionKind::Data, SectionFlags::None),
70 StandardSection::ReadOnlyData | StandardSection::ReadOnlyString => (
71 &[],
72 &b".rodata"[..],
73 SectionKind::ReadOnlyData,
74 SectionFlags::None,
75 ),
76 StandardSection::ReadOnlyDataWithRel => (
77 &[],
78 b".data.rel.ro",
79 SectionKind::ReadOnlyDataWithRel,
80 SectionFlags::None,
81 ),
82 StandardSection::UninitializedData => (
83 &[],
84 &b".bss"[..],
85 SectionKind::UninitializedData,
86 SectionFlags::None,
87 ),
88 StandardSection::Tls => (&[], &b".tdata"[..], SectionKind::Tls, SectionFlags::None),
89 StandardSection::UninitializedTls => (
90 &[],
91 &b".tbss"[..],
92 SectionKind::UninitializedTls,
93 SectionFlags::None,
94 ),
95 StandardSection::TlsVariables => {
96 // Unsupported section.
97 (&[], &[], SectionKind::TlsVariables, SectionFlags::None)
98 }
99 StandardSection::Common => {
100 // Unsupported section.
101 (&[], &[], SectionKind::Common, SectionFlags::None)
102 }
103 StandardSection::GnuProperty => (
104 &[],
105 &b".note.gnu.property"[..],
106 SectionKind::Note,
107 SectionFlags::Elf {
108 sh_flags: u64::from(elf::SHF_ALLOC),
109 },
110 ),
111 }
112 }
113
114 pub(crate) fn elf_subsection_name(&self, section: &[u8], value: &[u8]) -> Vec<u8> {
115 let mut name = section.to_vec();
116 name.push(b'.');
117 name.extend_from_slice(value);
118 name
119 }
120
121 fn elf_has_relocation_addend(&self) -> Result<bool> {
122 Ok(match self.architecture {
123 Architecture::Aarch64 => true,
124 Architecture::Aarch64_Ilp32 => true,
125 Architecture::Arm => false,
126 Architecture::Avr => true,
127 Architecture::Bpf => false,
128 Architecture::Csky => true,
129 Architecture::I386 => false,
130 Architecture::X86_64 => true,
131 Architecture::X86_64_X32 => true,
132 Architecture::Hexagon => true,
133 Architecture::LoongArch64 => true,
134 Architecture::Mips => false,
135 Architecture::Mips64 => true,
136 Architecture::Msp430 => true,
137 Architecture::PowerPc => true,
138 Architecture::PowerPc64 => true,
139 Architecture::Riscv64 => true,
140 Architecture::Riscv32 => true,
141 Architecture::S390x => true,
142 Architecture::Sbf => false,
143 Architecture::Sharc => true,
144 Architecture::Sparc => true,
145 Architecture::Sparc32Plus => true,
146 Architecture::Sparc64 => true,
147 Architecture::Xtensa => true,
148 _ => {
149 return Err(Error(format!(
150 "unimplemented architecture {:?}",
151 self.architecture
152 )));
153 }
154 })
155 }
156
157 pub(crate) fn elf_translate_relocation(&mut self, reloc: &mut Relocation) -> Result<()> {
158 let (kind, encoding, size) = if let RelocationFlags::Generic {
159 kind,
160 encoding,
161 size,
162 } = reloc.flags
163 {
164 (kind, encoding, size)
165 } else {
166 return Ok(());
167 };
168
169 let r_type = match self.architecture {
170 Architecture::Aarch64 => match (kind, encoding, size) {
171 (RelocationKind::Absolute, RelocationEncoding::Generic, 64) => elf::R_AARCH64_ABS64,
172 (RelocationKind::Absolute, RelocationEncoding::Generic, 32) => elf::R_AARCH64_ABS32,
173 (RelocationKind::Absolute, RelocationEncoding::Generic, 16) => elf::R_AARCH64_ABS16,
174 (RelocationKind::Relative, RelocationEncoding::Generic, 64) => {
175 elf::R_AARCH64_PREL64
176 }
177 (RelocationKind::Relative, RelocationEncoding::Generic, 32) => {
178 elf::R_AARCH64_PREL32
179 }
180 (RelocationKind::Relative, RelocationEncoding::Generic, 16) => {
181 elf::R_AARCH64_PREL16
182 }
183 (RelocationKind::Relative, RelocationEncoding::AArch64Call, 26)
184 | (RelocationKind::PltRelative, RelocationEncoding::AArch64Call, 26) => {
185 elf::R_AARCH64_CALL26
186 }
187 _ => {
188 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
189 }
190 },
191 Architecture::Aarch64_Ilp32 => match (kind, encoding, size) {
192 (RelocationKind::Absolute, RelocationEncoding::Generic, 32) => {
193 elf::R_AARCH64_P32_ABS32
194 }
195 _ => {
196 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
197 }
198 },
199 Architecture::Arm => match (kind, encoding, size) {
200 (RelocationKind::Absolute, _, 32) => elf::R_ARM_ABS32,
201 _ => {
202 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
203 }
204 },
205 Architecture::Avr => match (kind, encoding, size) {
206 (RelocationKind::Absolute, _, 32) => elf::R_AVR_32,
207 (RelocationKind::Absolute, _, 16) => elf::R_AVR_16,
208 _ => {
209 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
210 }
211 },
212 Architecture::Bpf => match (kind, encoding, size) {
213 (RelocationKind::Absolute, _, 64) => elf::R_BPF_64_64,
214 (RelocationKind::Absolute, _, 32) => elf::R_BPF_64_32,
215 _ => {
216 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
217 }
218 },
219 Architecture::Csky => match (kind, encoding, size) {
220 (RelocationKind::Absolute, _, 32) => elf::R_CKCORE_ADDR32,
221 (RelocationKind::Relative, RelocationEncoding::Generic, 32) => {
222 elf::R_CKCORE_PCREL32
223 }
224 _ => {
225 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
226 }
227 },
228 Architecture::I386 => match (kind, size) {
229 (RelocationKind::Absolute, 32) => elf::R_386_32,
230 (RelocationKind::Relative, 32) => elf::R_386_PC32,
231 (RelocationKind::Got, 32) => elf::R_386_GOT32,
232 (RelocationKind::PltRelative, 32) => elf::R_386_PLT32,
233 (RelocationKind::GotBaseOffset, 32) => elf::R_386_GOTOFF,
234 (RelocationKind::GotBaseRelative, 32) => elf::R_386_GOTPC,
235 (RelocationKind::Absolute, 16) => elf::R_386_16,
236 (RelocationKind::Relative, 16) => elf::R_386_PC16,
237 (RelocationKind::Absolute, 8) => elf::R_386_8,
238 (RelocationKind::Relative, 8) => elf::R_386_PC8,
239 _ => {
240 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
241 }
242 },
243 Architecture::X86_64 | Architecture::X86_64_X32 => match (kind, encoding, size) {
244 (RelocationKind::Absolute, RelocationEncoding::Generic, 64) => elf::R_X86_64_64,
245 (RelocationKind::Relative, RelocationEncoding::X86Branch, 32) => {
246 elf::R_X86_64_PLT32
247 }
248 (RelocationKind::Relative, _, 32) => elf::R_X86_64_PC32,
249 (RelocationKind::Got, _, 32) => elf::R_X86_64_GOT32,
250 (RelocationKind::PltRelative, _, 32) => elf::R_X86_64_PLT32,
251 (RelocationKind::GotRelative, _, 32) => elf::R_X86_64_GOTPCREL,
252 (RelocationKind::Absolute, RelocationEncoding::Generic, 32) => elf::R_X86_64_32,
253 (RelocationKind::Absolute, RelocationEncoding::X86Signed, 32) => elf::R_X86_64_32S,
254 (RelocationKind::Absolute, _, 16) => elf::R_X86_64_16,
255 (RelocationKind::Relative, _, 16) => elf::R_X86_64_PC16,
256 (RelocationKind::Absolute, _, 8) => elf::R_X86_64_8,
257 (RelocationKind::Relative, _, 8) => elf::R_X86_64_PC8,
258 _ => {
259 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
260 }
261 },
262 Architecture::Hexagon => match (kind, encoding, size) {
263 (RelocationKind::Absolute, _, 32) => elf::R_HEX_32,
264 _ => {
265 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
266 }
267 },
268 Architecture::LoongArch64 => match (kind, encoding, size) {
269 (RelocationKind::Absolute, _, 32) => elf::R_LARCH_32,
270 (RelocationKind::Absolute, _, 64) => elf::R_LARCH_64,
271 (RelocationKind::Relative, _, 32) => elf::R_LARCH_32_PCREL,
272 (RelocationKind::Relative, _, 64) => elf::R_LARCH_64_PCREL,
273 (RelocationKind::Relative, RelocationEncoding::LoongArchBranch, 16)
274 | (RelocationKind::PltRelative, RelocationEncoding::LoongArchBranch, 16) => {
275 elf::R_LARCH_B16
276 }
277 (RelocationKind::Relative, RelocationEncoding::LoongArchBranch, 21)
278 | (RelocationKind::PltRelative, RelocationEncoding::LoongArchBranch, 21) => {
279 elf::R_LARCH_B21
280 }
281 (RelocationKind::Relative, RelocationEncoding::LoongArchBranch, 26)
282 | (RelocationKind::PltRelative, RelocationEncoding::LoongArchBranch, 26) => {
283 elf::R_LARCH_B26
284 }
285 _ => {
286 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
287 }
288 },
289 Architecture::Mips | Architecture::Mips64 => match (kind, encoding, size) {
290 (RelocationKind::Absolute, _, 16) => elf::R_MIPS_16,
291 (RelocationKind::Absolute, _, 32) => elf::R_MIPS_32,
292 (RelocationKind::Absolute, _, 64) => elf::R_MIPS_64,
293 _ => {
294 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
295 }
296 },
297 Architecture::Msp430 => match (kind, encoding, size) {
298 (RelocationKind::Absolute, _, 32) => elf::R_MSP430_32,
299 (RelocationKind::Absolute, _, 16) => elf::R_MSP430_16_BYTE,
300 _ => {
301 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
302 }
303 },
304 Architecture::PowerPc => match (kind, encoding, size) {
305 (RelocationKind::Absolute, _, 32) => elf::R_PPC_ADDR32,
306 _ => {
307 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
308 }
309 },
310 Architecture::PowerPc64 => match (kind, encoding, size) {
311 (RelocationKind::Absolute, _, 32) => elf::R_PPC64_ADDR32,
312 (RelocationKind::Absolute, _, 64) => elf::R_PPC64_ADDR64,
313 _ => {
314 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
315 }
316 },
317 Architecture::Riscv32 | Architecture::Riscv64 => match (kind, encoding, size) {
318 (RelocationKind::Absolute, _, 32) => elf::R_RISCV_32,
319 (RelocationKind::Absolute, _, 64) => elf::R_RISCV_64,
320 (RelocationKind::Relative, RelocationEncoding::Generic, 32) => {
321 elf::R_RISCV_32_PCREL
322 }
323 _ => {
324 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
325 }
326 },
327 Architecture::S390x => match (kind, encoding, size) {
328 (RelocationKind::Absolute, RelocationEncoding::Generic, 8) => elf::R_390_8,
329 (RelocationKind::Absolute, RelocationEncoding::Generic, 16) => elf::R_390_16,
330 (RelocationKind::Absolute, RelocationEncoding::Generic, 32) => elf::R_390_32,
331 (RelocationKind::Absolute, RelocationEncoding::Generic, 64) => elf::R_390_64,
332 (RelocationKind::Relative, RelocationEncoding::Generic, 16) => elf::R_390_PC16,
333 (RelocationKind::Relative, RelocationEncoding::Generic, 32) => elf::R_390_PC32,
334 (RelocationKind::Relative, RelocationEncoding::Generic, 64) => elf::R_390_PC64,
335 (RelocationKind::Relative, RelocationEncoding::S390xDbl, 16) => elf::R_390_PC16DBL,
336 (RelocationKind::Relative, RelocationEncoding::S390xDbl, 32) => elf::R_390_PC32DBL,
337 (RelocationKind::PltRelative, RelocationEncoding::S390xDbl, 16) => {
338 elf::R_390_PLT16DBL
339 }
340 (RelocationKind::PltRelative, RelocationEncoding::S390xDbl, 32) => {
341 elf::R_390_PLT32DBL
342 }
343 (RelocationKind::Got, RelocationEncoding::Generic, 16) => elf::R_390_GOT16,
344 (RelocationKind::Got, RelocationEncoding::Generic, 32) => elf::R_390_GOT32,
345 (RelocationKind::Got, RelocationEncoding::Generic, 64) => elf::R_390_GOT64,
346 (RelocationKind::GotRelative, RelocationEncoding::S390xDbl, 32) => {
347 elf::R_390_GOTENT
348 }
349 (RelocationKind::GotBaseOffset, RelocationEncoding::Generic, 16) => {
350 elf::R_390_GOTOFF16
351 }
352 (RelocationKind::GotBaseOffset, RelocationEncoding::Generic, 32) => {
353 elf::R_390_GOTOFF32
354 }
355 (RelocationKind::GotBaseOffset, RelocationEncoding::Generic, 64) => {
356 elf::R_390_GOTOFF64
357 }
358 (RelocationKind::GotBaseRelative, RelocationEncoding::Generic, 64) => {
359 elf::R_390_GOTPC
360 }
361 (RelocationKind::GotBaseRelative, RelocationEncoding::S390xDbl, 32) => {
362 elf::R_390_GOTPCDBL
363 }
364 _ => {
365 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
366 }
367 },
368 Architecture::Sbf => match (kind, encoding, size) {
369 (RelocationKind::Absolute, _, 64) => elf::R_SBF_64_64,
370 (RelocationKind::Absolute, _, 32) => elf::R_SBF_64_32,
371 _ => {
372 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
373 }
374 },
375 Architecture::Sharc => match (kind, encoding, size) {
376 (RelocationKind::Absolute, RelocationEncoding::SharcTypeA, 32) => {
377 elf::R_SHARC_ADDR32_V3
378 }
379 (RelocationKind::Absolute, RelocationEncoding::Generic, 32) => {
380 elf::R_SHARC_ADDR_VAR_V3
381 }
382 (RelocationKind::Relative, RelocationEncoding::SharcTypeA, 24) => {
383 elf::R_SHARC_PCRLONG_V3
384 }
385 (RelocationKind::Relative, RelocationEncoding::SharcTypeA, 6) => {
386 elf::R_SHARC_PCRSHORT_V3
387 }
388 (RelocationKind::Relative, RelocationEncoding::SharcTypeB, 6) => {
389 elf::R_SHARC_PCRSHORT_V3
390 }
391 (RelocationKind::Absolute, RelocationEncoding::Generic, 16) => {
392 elf::R_SHARC_ADDR_VAR16_V3
393 }
394 (RelocationKind::Absolute, RelocationEncoding::SharcTypeA, 16) => {
395 elf::R_SHARC_DATA16_V3
396 }
397 (RelocationKind::Absolute, RelocationEncoding::SharcTypeB, 16) => {
398 elf::R_SHARC_DATA16_VISA_V3
399 }
400 (RelocationKind::Absolute, RelocationEncoding::SharcTypeA, 24) => {
401 elf::R_SHARC_ADDR24_V3
402 }
403 (RelocationKind::Absolute, RelocationEncoding::SharcTypeA, 6) => {
404 elf::R_SHARC_DATA6_V3
405 }
406 (RelocationKind::Absolute, RelocationEncoding::SharcTypeB, 6) => {
407 elf::R_SHARC_DATA6_VISA_V3
408 }
409 (RelocationKind::Absolute, RelocationEncoding::SharcTypeB, 7) => {
410 elf::R_SHARC_DATA7_VISA_V3
411 }
412 _ => {
413 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
414 }
415 },
416 Architecture::Sparc | Architecture::Sparc32Plus => match (kind, encoding, size) {
417 // TODO: use R_SPARC_32 if aligned.
418 (RelocationKind::Absolute, _, 32) => elf::R_SPARC_UA32,
419 _ => {
420 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
421 }
422 },
423 Architecture::Sparc64 => match (kind, encoding, size) {
424 // TODO: use R_SPARC_32/R_SPARC_64 if aligned.
425 (RelocationKind::Absolute, _, 32) => elf::R_SPARC_UA32,
426 (RelocationKind::Absolute, _, 64) => elf::R_SPARC_UA64,
427 _ => {
428 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
429 }
430 },
431 Architecture::Xtensa => match (kind, encoding, size) {
432 (RelocationKind::Absolute, _, 32) => elf::R_XTENSA_32,
433 (RelocationKind::Relative, RelocationEncoding::Generic, 32) => {
434 elf::R_XTENSA_32_PCREL
435 }
436 _ => {
437 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
438 }
439 },
440 _ => {
441 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
442 }
443 };
444 reloc.flags = RelocationFlags::Elf { r_type };
445 Ok(())
446 }
447
448 pub(crate) fn elf_adjust_addend(&mut self, _relocation: &mut Relocation) -> Result<bool> {
449 // Determine whether the addend is stored in the relocation or the data.
450 let implicit = !self.elf_has_relocation_addend()?;
451 Ok(implicit)
452 }
453
454 pub(crate) fn elf_relocation_size(&self, reloc: &Relocation) -> Result<u8> {
455 let r_type = if let RelocationFlags::Elf { r_type } = reloc.flags {
456 r_type
457 } else {
458 return Err(Error("invalid relocation flags".into()));
459 };
460 // This only needs to support architectures that use implicit addends.
461 let size = match self.architecture {
462 Architecture::Arm => match r_type {
463 elf::R_ARM_ABS16 => Some(16),
464 elf::R_ARM_ABS32 | elf::R_ARM_REL32 => Some(32),
465 _ => None,
466 },
467 Architecture::Bpf => match r_type {
468 elf::R_BPF_64_32 => Some(32),
469 elf::R_BPF_64_64 => Some(64),
470 _ => None,
471 },
472 Architecture::I386 => match r_type {
473 elf::R_386_8 | elf::R_386_PC8 => Some(8),
474 elf::R_386_16 | elf::R_386_PC16 => Some(16),
475 elf::R_386_32
476 | elf::R_386_PC32
477 | elf::R_386_GOT32
478 | elf::R_386_PLT32
479 | elf::R_386_GOTOFF
480 | elf::R_386_GOTPC => Some(32),
481 _ => None,
482 },
483 Architecture::Mips => match r_type {
484 elf::R_MIPS_16 => Some(16),
485 elf::R_MIPS_32 => Some(32),
486 elf::R_MIPS_64 => Some(64),
487 _ => None,
488 },
489 Architecture::Sbf => match r_type {
490 elf::R_SBF_64_32 => Some(32),
491 elf::R_SBF_64_64 => Some(64),
492 _ => None,
493 },
494 _ => {
495 return Err(Error(format!(
496 "unimplemented architecture {:?}",
497 self.architecture
498 )));
499 }
500 };
501 size.ok_or_else(|| Error(format!("unsupported relocation for size {:?}", reloc)))
502 }
503
504 pub(crate) fn elf_is_64(&self) -> bool {
505 match self.architecture.address_size().unwrap() {
506 AddressSize::U8 | AddressSize::U16 | AddressSize::U32 => false,
507 AddressSize::U64 => true,
508 }
509 }
510
511 pub(crate) fn elf_write(&self, buffer: &mut dyn WritableBuffer) -> Result<()> {
512 // Create reloc section header names so we can reference them.
513 let is_rela = self.elf_has_relocation_addend()?;
514 let reloc_names: Vec<_> = self
515 .sections
516 .iter()
517 .map(|section| {
518 let mut reloc_name = Vec::with_capacity(
519 if is_rela { ".rela".len() } else { ".rel".len() } + section.name.len(),
520 );
521 if !section.relocations.is_empty() {
522 reloc_name.extend_from_slice(if is_rela {
523 &b".rela"[..]
524 } else {
525 &b".rel"[..]
526 });
527 reloc_name.extend_from_slice(&section.name);
528 }
529 reloc_name
530 })
531 .collect();
532
533 // Start calculating offsets of everything.
534 let mut writer = Writer::new(self.endian, self.elf_is_64(), buffer);
535 writer.reserve_file_header();
536
537 // Calculate size of section data.
538 let mut comdat_offsets = Vec::with_capacity(self.comdats.len());
539 for comdat in &self.comdats {
540 if comdat.kind != ComdatKind::Any {
541 return Err(Error(format!(
542 "unsupported COMDAT symbol `{}` kind {:?}",
543 self.symbols[comdat.symbol.0].name().unwrap_or(""),
544 comdat.kind
545 )));
546 }
547
548 writer.reserve_section_index();
549 let offset = writer.reserve_comdat(comdat.sections.len());
550 let str_id = writer.add_section_name(b".group");
551 comdat_offsets.push(ComdatOffsets { offset, str_id });
552 }
553 let mut section_offsets = Vec::with_capacity(self.sections.len());
554 for (section, reloc_name) in self.sections.iter().zip(reloc_names.iter()) {
555 let index = writer.reserve_section_index();
556 let offset = writer.reserve(section.data.len(), section.align as usize);
557 let str_id = writer.add_section_name(&section.name);
558 let mut reloc_str_id = None;
559 if !section.relocations.is_empty() {
560 writer.reserve_section_index();
561 reloc_str_id = Some(writer.add_section_name(reloc_name));
562 }
563 section_offsets.push(SectionOffsets {
564 index,
565 offset,
566 str_id,
567 // Relocation data is reserved later.
568 reloc_offset: 0,
569 reloc_str_id,
570 });
571 }
572
573 // Calculate index of symbols and add symbol strings to strtab.
574 let mut symbol_offsets = vec![SymbolOffsets::default(); self.symbols.len()];
575 writer.reserve_null_symbol_index();
576 // Local symbols must come before global.
577 for (index, symbol) in self.symbols.iter().enumerate() {
578 if symbol.is_local() {
579 let section_index = symbol.section.id().map(|s| section_offsets[s.0].index);
580 symbol_offsets[index].index = writer.reserve_symbol_index(section_index);
581 }
582 }
583 let symtab_num_local = writer.symbol_count();
584 for (index, symbol) in self.symbols.iter().enumerate() {
585 if !symbol.is_local() {
586 let section_index = symbol.section.id().map(|s| section_offsets[s.0].index);
587 symbol_offsets[index].index = writer.reserve_symbol_index(section_index);
588 }
589 }
590 for (index, symbol) in self.symbols.iter().enumerate() {
591 if symbol.kind != SymbolKind::Section && !symbol.name.is_empty() {
592 symbol_offsets[index].str_id = Some(writer.add_string(&symbol.name));
593 }
594 }
595
596 // Calculate size of symbols.
597 writer.reserve_symtab_section_index();
598 writer.reserve_symtab();
599 if writer.symtab_shndx_needed() {
600 writer.reserve_symtab_shndx_section_index();
601 }
602 writer.reserve_symtab_shndx();
603 writer.reserve_strtab_section_index();
604 writer.reserve_strtab();
605
606 // Calculate size of relocations.
607 for (index, section) in self.sections.iter().enumerate() {
608 let count = section.relocations.len();
609 if count != 0 {
610 section_offsets[index].reloc_offset = writer.reserve_relocations(count, is_rela);
611 }
612 }
613
614 // Calculate size of section headers.
615 writer.reserve_shstrtab_section_index();
616 writer.reserve_shstrtab();
617 writer.reserve_section_headers();
618
619 // Start writing.
620 let e_type = elf::ET_REL;
621 let e_machine = match (self.architecture, self.sub_architecture) {
622 (Architecture::Aarch64, None) => elf::EM_AARCH64,
623 (Architecture::Aarch64_Ilp32, None) => elf::EM_AARCH64,
624 (Architecture::Arm, None) => elf::EM_ARM,
625 (Architecture::Avr, None) => elf::EM_AVR,
626 (Architecture::Bpf, None) => elf::EM_BPF,
627 (Architecture::Csky, None) => elf::EM_CSKY,
628 (Architecture::I386, None) => elf::EM_386,
629 (Architecture::X86_64, None) => elf::EM_X86_64,
630 (Architecture::X86_64_X32, None) => elf::EM_X86_64,
631 (Architecture::Hexagon, None) => elf::EM_HEXAGON,
632 (Architecture::LoongArch64, None) => elf::EM_LOONGARCH,
633 (Architecture::Mips, None) => elf::EM_MIPS,
634 (Architecture::Mips64, None) => elf::EM_MIPS,
635 (Architecture::Msp430, None) => elf::EM_MSP430,
636 (Architecture::PowerPc, None) => elf::EM_PPC,
637 (Architecture::PowerPc64, None) => elf::EM_PPC64,
638 (Architecture::Riscv32, None) => elf::EM_RISCV,
639 (Architecture::Riscv64, None) => elf::EM_RISCV,
640 (Architecture::S390x, None) => elf::EM_S390,
641 (Architecture::Sbf, None) => elf::EM_SBF,
642 (Architecture::Sharc, None) => elf::EM_SHARC,
643 (Architecture::Sparc, None) => elf::EM_SPARC,
644 (Architecture::Sparc32Plus, None) => elf::EM_SPARC32PLUS,
645 (Architecture::Sparc64, None) => elf::EM_SPARCV9,
646 (Architecture::Xtensa, None) => elf::EM_XTENSA,
647 _ => {
648 return Err(Error(format!(
649 "unimplemented architecture {:?} with sub-architecture {:?}",
650 self.architecture, self.sub_architecture
651 )));
652 }
653 };
654 let (os_abi, abi_version, e_flags) = if let FileFlags::Elf {
655 os_abi,
656 abi_version,
657 e_flags,
658 } = self.flags
659 {
660 (os_abi, abi_version, e_flags)
661 } else {
662 (elf::ELFOSABI_NONE, 0, 0)
663 };
664 writer.write_file_header(&FileHeader {
665 os_abi,
666 abi_version,
667 e_type,
668 e_machine,
669 e_entry: 0,
670 e_flags,
671 })?;
672
673 // Write section data.
674 for comdat in &self.comdats {
675 writer.write_comdat_header();
676 for section in &comdat.sections {
677 writer.write_comdat_entry(section_offsets[section.0].index);
678 }
679 }
680 for (index, section) in self.sections.iter().enumerate() {
681 writer.write_align(section.align as usize);
682 debug_assert_eq!(section_offsets[index].offset, writer.len());
683 writer.write(&section.data);
684 }
685
686 // Write symbols.
687 writer.write_null_symbol();
688 let mut write_symbol = |index: usize, symbol: &Symbol| -> Result<()> {
689 let st_info = if let SymbolFlags::Elf { st_info, .. } = symbol.flags {
690 st_info
691 } else {
692 let st_type = match symbol.kind {
693 SymbolKind::Text => {
694 if symbol.is_undefined() {
695 elf::STT_NOTYPE
696 } else {
697 elf::STT_FUNC
698 }
699 }
700 SymbolKind::Data => {
701 if symbol.is_undefined() {
702 elf::STT_NOTYPE
703 } else if symbol.is_common() {
704 elf::STT_COMMON
705 } else {
706 elf::STT_OBJECT
707 }
708 }
709 SymbolKind::Section => elf::STT_SECTION,
710 SymbolKind::File => elf::STT_FILE,
711 SymbolKind::Tls => elf::STT_TLS,
712 SymbolKind::Label => elf::STT_NOTYPE,
713 SymbolKind::Unknown => {
714 if symbol.is_undefined() {
715 elf::STT_NOTYPE
716 } else {
717 return Err(Error(format!(
718 "unimplemented symbol `{}` kind {:?}",
719 symbol.name().unwrap_or(""),
720 symbol.kind
721 )));
722 }
723 }
724 };
725 let st_bind = if symbol.weak {
726 elf::STB_WEAK
727 } else if symbol.is_undefined() {
728 elf::STB_GLOBAL
729 } else if symbol.is_local() {
730 elf::STB_LOCAL
731 } else {
732 elf::STB_GLOBAL
733 };
734 (st_bind << 4) + st_type
735 };
736 let st_other = if let SymbolFlags::Elf { st_other, .. } = symbol.flags {
737 st_other
738 } else if symbol.scope == SymbolScope::Linkage {
739 elf::STV_HIDDEN
740 } else {
741 elf::STV_DEFAULT
742 };
743 let (st_shndx, section) = match symbol.section {
744 SymbolSection::None => {
745 debug_assert_eq!(symbol.kind, SymbolKind::File);
746 (elf::SHN_ABS, None)
747 }
748 SymbolSection::Undefined => (elf::SHN_UNDEF, None),
749 SymbolSection::Absolute => (elf::SHN_ABS, None),
750 SymbolSection::Common => (elf::SHN_COMMON, None),
751 SymbolSection::Section(id) => (0, Some(section_offsets[id.0].index)),
752 };
753 writer.write_symbol(&Sym {
754 name: symbol_offsets[index].str_id,
755 section,
756 st_info,
757 st_other,
758 st_shndx,
759 st_value: symbol.value,
760 st_size: symbol.size,
761 });
762 Ok(())
763 };
764 for (index, symbol) in self.symbols.iter().enumerate() {
765 if symbol.is_local() {
766 write_symbol(index, symbol)?;
767 }
768 }
769 for (index, symbol) in self.symbols.iter().enumerate() {
770 if !symbol.is_local() {
771 write_symbol(index, symbol)?;
772 }
773 }
774 writer.write_symtab_shndx();
775 writer.write_strtab();
776
777 // Write relocations.
778 for (index, section) in self.sections.iter().enumerate() {
779 if !section.relocations.is_empty() {
780 writer.write_align_relocation();
781 debug_assert_eq!(section_offsets[index].reloc_offset, writer.len());
782 for reloc in &section.relocations {
783 let r_type = if let RelocationFlags::Elf { r_type } = reloc.flags {
784 r_type
785 } else {
786 return Err(Error("invalid relocation flags".into()));
787 };
788 let r_sym = symbol_offsets[reloc.symbol.0].index.0;
789 writer.write_relocation(
790 is_rela,
791 &Rel {
792 r_offset: reloc.offset,
793 r_sym,
794 r_type,
795 r_addend: reloc.addend,
796 },
797 );
798 }
799 }
800 }
801
802 writer.write_shstrtab();
803
804 // Write section headers.
805 writer.write_null_section_header();
806
807 let symtab_index = writer.symtab_index();
808 for (comdat, comdat_offset) in self.comdats.iter().zip(comdat_offsets.iter()) {
809 writer.write_comdat_section_header(
810 comdat_offset.str_id,
811 symtab_index,
812 symbol_offsets[comdat.symbol.0].index,
813 comdat_offset.offset,
814 comdat.sections.len(),
815 );
816 }
817 for (index, section) in self.sections.iter().enumerate() {
818 let sh_type = match section.kind {
819 SectionKind::UninitializedData | SectionKind::UninitializedTls => elf::SHT_NOBITS,
820 SectionKind::Note => elf::SHT_NOTE,
821 SectionKind::Elf(sh_type) => sh_type,
822 _ => elf::SHT_PROGBITS,
823 };
824 let sh_flags = if let SectionFlags::Elf { sh_flags } = section.flags {
825 sh_flags
826 } else {
827 match section.kind {
828 SectionKind::Text => elf::SHF_ALLOC | elf::SHF_EXECINSTR,
829 SectionKind::Data | SectionKind::ReadOnlyDataWithRel => {
830 elf::SHF_ALLOC | elf::SHF_WRITE
831 }
832 SectionKind::Tls => elf::SHF_ALLOC | elf::SHF_WRITE | elf::SHF_TLS,
833 SectionKind::UninitializedData => elf::SHF_ALLOC | elf::SHF_WRITE,
834 SectionKind::UninitializedTls => elf::SHF_ALLOC | elf::SHF_WRITE | elf::SHF_TLS,
835 SectionKind::ReadOnlyData => elf::SHF_ALLOC,
836 SectionKind::ReadOnlyString => {
837 elf::SHF_ALLOC | elf::SHF_STRINGS | elf::SHF_MERGE
838 }
839 SectionKind::OtherString | SectionKind::DebugString => {
840 elf::SHF_STRINGS | elf::SHF_MERGE
841 }
842 SectionKind::Other
843 | SectionKind::Debug
844 | SectionKind::Metadata
845 | SectionKind::Linker
846 | SectionKind::Note
847 | SectionKind::Elf(_) => 0,
848 SectionKind::Unknown | SectionKind::Common | SectionKind::TlsVariables => {
849 return Err(Error(format!(
850 "unimplemented section `{}` kind {:?}",
851 section.name().unwrap_or(""),
852 section.kind
853 )));
854 }
855 }
856 .into()
857 };
858 // TODO: not sure if this is correct, maybe user should determine this
859 let sh_entsize = match section.kind {
860 SectionKind::ReadOnlyString | SectionKind::OtherString => 1,
861 _ => 0,
862 };
863 writer.write_section_header(&SectionHeader {
864 name: Some(section_offsets[index].str_id),
865 sh_type,
866 sh_flags,
867 sh_addr: 0,
868 sh_offset: section_offsets[index].offset as u64,
869 sh_size: section.size,
870 sh_link: 0,
871 sh_info: 0,
872 sh_addralign: section.align,
873 sh_entsize,
874 });
875
876 if !section.relocations.is_empty() {
877 writer.write_relocation_section_header(
878 section_offsets[index].reloc_str_id.unwrap(),
879 section_offsets[index].index,
880 symtab_index,
881 section_offsets[index].reloc_offset,
882 section.relocations.len(),
883 is_rela,
884 );
885 }
886 }
887
888 writer.write_symtab_section_header(symtab_num_local);
889 writer.write_symtab_shndx_section_header();
890 writer.write_strtab_section_header();
891 writer.write_shstrtab_section_header();
892
893 debug_assert_eq!(writer.reserved_len(), writer.len());
894
895 Ok(())
896 }
897 }