Debian Codegraph @

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

raw
1 //! Interface for writing object files.
2 //!
3 //! This module provides a unified write API for relocatable object files
4 //! using [`Object`]. This does not support writing executable files.
5 //! This supports the following file formats: COFF, ELF, Mach-O, and XCOFF.
6 //!
7 //! The submodules define helpers for writing the raw structs. These support
8 //! writing both relocatable and executable files. There are writers for
9 //! the following file formats: [COFF](coff::Writer), [ELF](elf::Writer),
10 //! and [PE](pe::Writer).
11
12 use alloc::borrow::Cow;
13 use alloc::string::String;
14 use alloc::vec::Vec;
15 use core::{fmt, result, str};
16 #[cfg(not(feature = "std"))]
17 use hashbrown::HashMap;
18 #[cfg(feature = "std")]
19 use std::{boxed::Box, collections::HashMap, error, io};
20
21 use crate::endian::{Endianness, U32, U64};
22
23 pub use crate::common::*;
24
25 #[cfg(feature = "coff")]
26 pub mod coff;
27 #[cfg(feature = "coff")]
28 pub use coff::CoffExportStyle;
29
30 #[cfg(feature = "elf")]
31 pub mod elf;
32
33 #[cfg(feature = "macho")]
34 mod macho;
35 #[cfg(feature = "macho")]
36 pub use macho::MachOBuildVersion;
37
38 #[cfg(feature = "pe")]
39 pub mod pe;
40
41 #[cfg(feature = "xcoff")]
42 mod xcoff;
43
44 pub(crate) mod string;
45 pub use string::StringId;
46
47 mod util;
48 pub use util::*;
49
50 /// The error type used within the write module.
51 #[derive(Debug, Clone, PartialEq, Eq)]
52 pub struct Error(pub(crate) String);
53
54 impl fmt::Display for Error {
55 #[inline]
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 f.write_str(&self.0)
58 }
59 }
60
61 #[cfg(feature = "std")]
62 impl error::Error for Error {}
63
64 /// The result type used within the write module.
65 pub type Result<T> = result::Result<T, Error>;
66
67 /// A writable relocatable object file.
68 #[derive(Debug)]
69 pub struct Object<'a> {
70 format: BinaryFormat,
71 architecture: Architecture,
72 sub_architecture: Option<SubArchitecture>,
73 endian: Endianness,
74 sections: Vec<Section<'a>>,
75 standard_sections: HashMap<StandardSection, SectionId>,
76 symbols: Vec<Symbol>,
77 symbol_map: HashMap<Vec<u8>, SymbolId>,
78 comdats: Vec<Comdat>,
79 /// File flags that are specific to each file format.
80 pub flags: FileFlags,
81 /// The symbol name mangling scheme.
82 pub mangling: Mangling,
83 #[cfg(feature = "coff")]
84 stub_symbols: HashMap<SymbolId, SymbolId>,
85 /// Mach-O "_tlv_bootstrap" symbol.
86 #[cfg(feature = "macho")]
87 tlv_bootstrap: Option<SymbolId>,
88 /// Mach-O CPU subtype.
89 #[cfg(feature = "macho")]
90 macho_cpu_subtype: Option<u32>,
91 #[cfg(feature = "macho")]
92 macho_build_version: Option<MachOBuildVersion>,
93 /// Mach-O MH_SUBSECTIONS_VIA_SYMBOLS flag. Only ever set if format is Mach-O.
94 #[cfg(feature = "macho")]
95 macho_subsections_via_symbols: bool,
96 }
97
98 impl<'a> Object<'a> {
99 /// Create an empty object file.
100 pub fn new(format: BinaryFormat, architecture: Architecture, endian: Endianness) -> Object<'a> {
101 Object {
102 format,
103 architecture,
104 sub_architecture: None,
105 endian,
106 sections: Vec::new(),
107 standard_sections: HashMap::new(),
108 symbols: Vec::new(),
109 symbol_map: HashMap::new(),
110 comdats: Vec::new(),
111 flags: FileFlags::None,
112 mangling: Mangling::default(format, architecture),
113 #[cfg(feature = "coff")]
114 stub_symbols: HashMap::new(),
115 #[cfg(feature = "macho")]
116 tlv_bootstrap: None,
117 #[cfg(feature = "macho")]
118 macho_cpu_subtype: None,
119 #[cfg(feature = "macho")]
120 macho_build_version: None,
121 #[cfg(feature = "macho")]
122 macho_subsections_via_symbols: false,
123 }
124 }
125
126 /// Return the file format.
127 #[inline]
128 pub fn format(&self) -> BinaryFormat {
129 self.format
130 }
131
132 /// Return the architecture.
133 #[inline]
134 pub fn architecture(&self) -> Architecture {
135 self.architecture
136 }
137
138 /// Return the sub-architecture.
139 #[inline]
140 pub fn sub_architecture(&self) -> Option<SubArchitecture> {
141 self.sub_architecture
142 }
143
144 /// Specify the sub-architecture.
145 pub fn set_sub_architecture(&mut self, sub_architecture: Option<SubArchitecture>) {
146 self.sub_architecture = sub_architecture;
147 }
148
149 /// Return the current mangling setting.
150 #[inline]
151 pub fn mangling(&self) -> Mangling {
152 self.mangling
153 }
154
155 /// Specify the mangling setting.
156 #[inline]
157 pub fn set_mangling(&mut self, mangling: Mangling) {
158 self.mangling = mangling;
159 }
160
161 /// Return the name for a standard segment.
162 ///
163 /// This will vary based on the file format.
164 #[allow(unused_variables)]
165 pub fn segment_name(&self, segment: StandardSegment) -> &'static [u8] {
166 match self.format {
167 #[cfg(feature = "coff")]
168 BinaryFormat::Coff => &[],
169 #[cfg(feature = "elf")]
170 BinaryFormat::Elf => &[],
171 #[cfg(feature = "macho")]
172 BinaryFormat::MachO => self.macho_segment_name(segment),
173 _ => unimplemented!(),
174 }
175 }
176
177 /// Get the section with the given `SectionId`.
178 #[inline]
179 pub fn section(&self, section: SectionId) -> &Section<'a> {
180 &self.sections[section.0]
181 }
182
183 /// Mutably get the section with the given `SectionId`.
184 #[inline]
185 pub fn section_mut(&mut self, section: SectionId) -> &mut Section<'a> {
186 &mut self.sections[section.0]
187 }
188
189 /// Set the data for an existing section.
190 ///
191 /// Must not be called for sections that already have data, or that contain uninitialized data.
192 /// `align` must be a power of two.
193 pub fn set_section_data<T>(&mut self, section: SectionId, data: T, align: u64)
194 where
195 T: Into<Cow<'a, [u8]>>,
196 {
197 self.sections[section.0].set_data(data, align)
198 }
199
200 /// Append data to an existing section. Returns the section offset of the data.
201 ///
202 /// Must not be called for sections that contain uninitialized data.
203 /// `align` must be a power of two.
204 pub fn append_section_data(&mut self, section: SectionId, data: &[u8], align: u64) -> u64 {
205 self.sections[section.0].append_data(data, align)
206 }
207
208 /// Append zero-initialized data to an existing section. Returns the section offset of the data.
209 ///
210 /// Must not be called for sections that contain initialized data.
211 /// `align` must be a power of two.
212 pub fn append_section_bss(&mut self, section: SectionId, size: u64, align: u64) -> u64 {
213 self.sections[section.0].append_bss(size, align)
214 }
215
216 /// Return the `SectionId` of a standard section.
217 ///
218 /// If the section doesn't already exist then it is created.
219 pub fn section_id(&mut self, section: StandardSection) -> SectionId {
220 self.standard_sections
221 .get(&section)
222 .cloned()
223 .unwrap_or_else(|| {
224 let (segment, name, kind, flags) = self.section_info(section);
225 let id = self.add_section(segment.to_vec(), name.to_vec(), kind);
226 self.section_mut(id).flags = flags;
227 id
228 })
229 }
230
231 /// Add a new section and return its `SectionId`.
232 ///
233 /// This also creates a section symbol.
234 pub fn add_section(&mut self, segment: Vec<u8>, name: Vec<u8>, kind: SectionKind) -> SectionId {
235 let id = SectionId(self.sections.len());
236 self.sections.push(Section {
237 segment,
238 name,
239 kind,
240 size: 0,
241 align: 1,
242 data: Cow::Borrowed(&[]),
243 relocations: Vec::new(),
244 symbol: None,
245 flags: SectionFlags::None,
246 });
247
248 // Add to self.standard_sections if required. This may match multiple standard sections.
249 let section = &self.sections[id.0];
250 for standard_section in StandardSection::all() {
251 if !self.standard_sections.contains_key(standard_section) {
252 let (segment, name, kind, _flags) = self.section_info(*standard_section);
253 if segment == &*section.segment && name == &*section.name && kind == section.kind {
254 self.standard_sections.insert(*standard_section, id);
255 }
256 }
257 }
258
259 id
260 }
261
262 fn section_info(
263 &self,
264 section: StandardSection,
265 ) -> (&'static [u8], &'static [u8], SectionKind, SectionFlags) {
266 match self.format {
267 #[cfg(feature = "coff")]
268 BinaryFormat::Coff => self.coff_section_info(section),
269 #[cfg(feature = "elf")]
270 BinaryFormat::Elf => self.elf_section_info(section),
271 #[cfg(feature = "macho")]
272 BinaryFormat::MachO => self.macho_section_info(section),
273 #[cfg(feature = "xcoff")]
274 BinaryFormat::Xcoff => self.xcoff_section_info(section),
275 _ => unimplemented!(),
276 }
277 }
278
279 /// Add a subsection. Returns the `SectionId` and section offset of the data.
280 ///
281 /// For Mach-O, this does not create a subsection, and instead uses the
282 /// section from [`Self::section_id`]. Use [`Self::set_subsections_via_symbols`]
283 /// to enable subsections via symbols.
284 pub fn add_subsection(&mut self, section: StandardSection, name: &[u8]) -> SectionId {
285 if self.has_subsections_via_symbols() {
286 self.section_id(section)
287 } else {
288 let (segment, name, kind, flags) = self.subsection_info(section, name);
289 let id = self.add_section(segment.to_vec(), name, kind);
290 self.section_mut(id).flags = flags;
291 id
292 }
293 }
294
295 fn has_subsections_via_symbols(&self) -> bool {
296 self.format == BinaryFormat::MachO
297 }
298
299 /// Enable subsections via symbols if supported.
300 ///
301 /// This should be called before adding any subsections or symbols.
302 ///
303 /// For Mach-O, this sets the `MH_SUBSECTIONS_VIA_SYMBOLS` flag.
304 /// For other formats, this does nothing.
305 pub fn set_subsections_via_symbols(&mut self) {
306 #[cfg(feature = "macho")]
307 if self.format == BinaryFormat::MachO {
308 self.macho_subsections_via_symbols = true;
309 }
310 }
311
312 fn subsection_info(
313 &self,
314 section: StandardSection,
315 value: &[u8],
316 ) -> (&'static [u8], Vec<u8>, SectionKind, SectionFlags) {
317 let (segment, section, kind, flags) = self.section_info(section);
318 let name = self.subsection_name(section, value);
319 (segment, name, kind, flags)
320 }
321
322 #[allow(unused_variables)]
323 fn subsection_name(&self, section: &[u8], value: &[u8]) -> Vec<u8> {
324 debug_assert!(!self.has_subsections_via_symbols());
325 match self.format {
326 #[cfg(feature = "coff")]
327 BinaryFormat::Coff => self.coff_subsection_name(section, value),
328 #[cfg(feature = "elf")]
329 BinaryFormat::Elf => self.elf_subsection_name(section, value),
330 _ => unimplemented!(),
331 }
332 }
333
334 /// Get the COMDAT section group with the given `ComdatId`.
335 #[inline]
336 pub fn comdat(&self, comdat: ComdatId) -> &Comdat {
337 &self.comdats[comdat.0]
338 }
339
340 /// Mutably get the COMDAT section group with the given `ComdatId`.
341 #[inline]
342 pub fn comdat_mut(&mut self, comdat: ComdatId) -> &mut Comdat {
343 &mut self.comdats[comdat.0]
344 }
345
346 /// Add a new COMDAT section group and return its `ComdatId`.
347 pub fn add_comdat(&mut self, comdat: Comdat) -> ComdatId {
348 let comdat_id = ComdatId(self.comdats.len());
349 self.comdats.push(comdat);
350 comdat_id
351 }
352
353 /// Get the `SymbolId` of the symbol with the given name.
354 pub fn symbol_id(&self, name: &[u8]) -> Option<SymbolId> {
355 self.symbol_map.get(name).cloned()
356 }
357
358 /// Get the symbol with the given `SymbolId`.
359 #[inline]
360 pub fn symbol(&self, symbol: SymbolId) -> &Symbol {
361 &self.symbols[symbol.0]
362 }
363
364 /// Mutably get the symbol with the given `SymbolId`.
365 #[inline]
366 pub fn symbol_mut(&mut self, symbol: SymbolId) -> &mut Symbol {
367 &mut self.symbols[symbol.0]
368 }
369
370 /// Add a new symbol and return its `SymbolId`.
371 pub fn add_symbol(&mut self, mut symbol: Symbol) -> SymbolId {
372 // Defined symbols must have a scope.
373 debug_assert!(symbol.is_undefined() || symbol.scope != SymbolScope::Unknown);
374 if symbol.kind == SymbolKind::Section {
375 // There can only be one section symbol, but update its flags, since
376 // the automatically generated section symbol will have none.
377 let symbol_id = self.section_symbol(symbol.section.id().unwrap());
378 if symbol.flags != SymbolFlags::None {
379 self.symbol_mut(symbol_id).flags = symbol.flags;
380 }
381 return symbol_id;
382 }
383 if !symbol.name.is_empty()
384 && (symbol.kind == SymbolKind::Text
385 || symbol.kind == SymbolKind::Data
386 || symbol.kind == SymbolKind::Tls)
387 {
388 let unmangled_name = symbol.name.clone();
389 if let Some(prefix) = self.mangling.global_prefix() {
390 symbol.name.insert(0, prefix);
391 }
392 let symbol_id = self.add_raw_symbol(symbol);
393 self.symbol_map.insert(unmangled_name, symbol_id);
394 symbol_id
395 } else {
396 self.add_raw_symbol(symbol)
397 }
398 }
399
400 fn add_raw_symbol(&mut self, symbol: Symbol) -> SymbolId {
401 let symbol_id = SymbolId(self.symbols.len());
402 self.symbols.push(symbol);
403 symbol_id
404 }
405
406 /// Return true if the file format supports `StandardSection::UninitializedTls`.
407 #[inline]
408 pub fn has_uninitialized_tls(&self) -> bool {
409 self.format != BinaryFormat::Coff
410 }
411
412 /// Return true if the file format supports `StandardSection::Common`.
413 #[inline]
414 pub fn has_common(&self) -> bool {
415 self.format == BinaryFormat::MachO
416 }
417
418 /// Add a new common symbol and return its `SymbolId`.
419 ///
420 /// For Mach-O, this appends the symbol to the `__common` section.
421 ///
422 /// `align` must be a power of two.
423 pub fn add_common_symbol(&mut self, mut symbol: Symbol, size: u64, align: u64) -> SymbolId {
424 if self.has_common() {
425 let symbol_id = self.add_symbol(symbol);
426 let section = self.section_id(StandardSection::Common);
427 self.add_symbol_bss(symbol_id, section, size, align);
428 symbol_id
429 } else {
430 symbol.section = SymbolSection::Common;
431 symbol.size = size;
432 self.add_symbol(symbol)
433 }
434 }
435
436 /// Add a new file symbol and return its `SymbolId`.
437 pub fn add_file_symbol(&mut self, name: Vec<u8>) -> SymbolId {
438 self.add_raw_symbol(Symbol {
439 name,
440 value: 0,
441 size: 0,
442 kind: SymbolKind::File,
443 scope: SymbolScope::Compilation,
444 weak: false,
445 section: SymbolSection::None,
446 flags: SymbolFlags::None,
447 })
448 }
449
450 /// Get the symbol for a section.
451 pub fn section_symbol(&mut self, section_id: SectionId) -> SymbolId {
452 let section = &mut self.sections[section_id.0];
453 if let Some(symbol) = section.symbol {
454 return symbol;
455 }
456 let name = if self.format == BinaryFormat::Coff {
457 section.name.clone()
458 } else {
459 Vec::new()
460 };
461 let symbol_id = SymbolId(self.symbols.len());
462 self.symbols.push(Symbol {
463 name,
464 value: 0,
465 size: 0,
466 kind: SymbolKind::Section,
467 scope: SymbolScope::Compilation,
468 weak: false,
469 section: SymbolSection::Section(section_id),
470 flags: SymbolFlags::None,
471 });
472 section.symbol = Some(symbol_id);
473 symbol_id
474 }
475
476 /// Append data to an existing section, and update a symbol to refer to it.
477 ///
478 /// For Mach-O, this also creates a `__thread_vars` entry for TLS symbols, and the
479 /// symbol will indirectly point to the added data via the `__thread_vars` entry.
480 ///
481 /// For Mach-O, if [`Self::set_subsections_via_symbols`] is enabled, this will
482 /// automatically ensure the data size is at least 1.
483 ///
484 /// Returns the section offset of the data.
485 ///
486 /// Must not be called for sections that contain uninitialized data.
487 /// `align` must be a power of two.
488 pub fn add_symbol_data(
489 &mut self,
490 symbol_id: SymbolId,
491 section: SectionId,
492 #[cfg_attr(not(feature = "macho"), allow(unused_mut))] mut data: &[u8],
493 align: u64,
494 ) -> u64 {
495 #[cfg(feature = "macho")]
496 if data.is_empty() && self.macho_subsections_via_symbols {
497 data = &[0];
498 }
499 let offset = self.append_section_data(section, data, align);
500 self.set_symbol_data(symbol_id, section, offset, data.len() as u64);
501 offset
502 }
503
504 /// Append zero-initialized data to an existing section, and update a symbol to refer to it.
505 ///
506 /// For Mach-O, this also creates a `__thread_vars` entry for TLS symbols, and the
507 /// symbol will indirectly point to the added data via the `__thread_vars` entry.
508 ///
509 /// For Mach-O, if [`Self::set_subsections_via_symbols`] is enabled, this will
510 /// automatically ensure the data size is at least 1.
511 ///
512 /// Returns the section offset of the data.
513 ///
514 /// Must not be called for sections that contain initialized data.
515 /// `align` must be a power of two.
516 pub fn add_symbol_bss(
517 &mut self,
518 symbol_id: SymbolId,
519 section: SectionId,
520 #[cfg_attr(not(feature = "macho"), allow(unused_mut))] mut size: u64,
521 align: u64,
522 ) -> u64 {
523 #[cfg(feature = "macho")]
524 if size == 0 && self.macho_subsections_via_symbols {
525 size = 1;
526 }
527 let offset = self.append_section_bss(section, size, align);
528 self.set_symbol_data(symbol_id, section, offset, size);
529 offset
530 }
531
532 /// Update a symbol to refer to the given data within a section.
533 ///
534 /// For Mach-O, this also creates a `__thread_vars` entry for TLS symbols, and the
535 /// symbol will indirectly point to the data via the `__thread_vars` entry.
536 #[allow(unused_mut)]
537 pub fn set_symbol_data(
538 &mut self,
539 mut symbol_id: SymbolId,
540 section: SectionId,
541 offset: u64,
542 size: u64,
543 ) {
544 // Defined symbols must have a scope.
545 debug_assert!(self.symbol(symbol_id).scope != SymbolScope::Unknown);
546 match self.format {
547 #[cfg(feature = "macho")]
548 BinaryFormat::MachO => symbol_id = self.macho_add_thread_var(symbol_id),
549 _ => {}
550 }
551 let symbol = self.symbol_mut(symbol_id);
552 symbol.value = offset;
553 symbol.size = size;
554 symbol.section = SymbolSection::Section(section);
555 }
556
557 /// Convert a symbol to a section symbol and offset.
558 ///
559 /// Returns `None` if the symbol does not have a section.
560 pub fn symbol_section_and_offset(&mut self, symbol_id: SymbolId) -> Option<(SymbolId, u64)> {
561 let symbol = self.symbol(symbol_id);
562 if symbol.kind == SymbolKind::Section {
563 return Some((symbol_id, 0));
564 }
565 let symbol_offset = symbol.value;
566 let section = symbol.section.id()?;
567 let section_symbol = self.section_symbol(section);
568 Some((section_symbol, symbol_offset))
569 }
570
571 /// Add a relocation to a section.
572 ///
573 /// Relocations must only be added after the referenced symbols have been added
574 /// and defined (if applicable).
575 pub fn add_relocation(&mut self, section: SectionId, mut relocation: Relocation) -> Result<()> {
576 match self.format {
577 #[cfg(feature = "coff")]
578 BinaryFormat::Coff => self.coff_translate_relocation(&mut relocation)?,
579 #[cfg(feature = "elf")]
580 BinaryFormat::Elf => self.elf_translate_relocation(&mut relocation)?,
581 #[cfg(feature = "macho")]
582 BinaryFormat::MachO => self.macho_translate_relocation(&mut relocation)?,
583 #[cfg(feature = "xcoff")]
584 BinaryFormat::Xcoff => self.xcoff_translate_relocation(&mut relocation)?,
585 _ => unimplemented!(),
586 }
587 let implicit = match self.format {
588 #[cfg(feature = "coff")]
589 BinaryFormat::Coff => self.coff_adjust_addend(&mut relocation)?,
590 #[cfg(feature = "elf")]
591 BinaryFormat::Elf => self.elf_adjust_addend(&mut relocation)?,
592 #[cfg(feature = "macho")]
593 BinaryFormat::MachO => self.macho_adjust_addend(&mut relocation)?,
594 #[cfg(feature = "xcoff")]
595 BinaryFormat::Xcoff => self.xcoff_adjust_addend(&mut relocation)?,
596 _ => unimplemented!(),
597 };
598 if implicit && relocation.addend != 0 {
599 self.write_relocation_addend(section, &relocation)?;
600 relocation.addend = 0;
601 }
602 self.sections[section.0].relocations.push(relocation);
603 Ok(())
604 }
605
606 fn write_relocation_addend(
607 &mut self,
608 section: SectionId,
609 relocation: &Relocation,
610 ) -> Result<()> {
611 let size = match self.format {
612 #[cfg(feature = "coff")]
613 BinaryFormat::Coff => self.coff_relocation_size(relocation)?,
614 #[cfg(feature = "elf")]
615 BinaryFormat::Elf => self.elf_relocation_size(relocation)?,
616 #[cfg(feature = "macho")]
617 BinaryFormat::MachO => self.macho_relocation_size(relocation)?,
618 #[cfg(feature = "xcoff")]
619 BinaryFormat::Xcoff => self.xcoff_relocation_size(relocation)?,
620 _ => unimplemented!(),
621 };
622 let data = self.sections[section.0].data_mut();
623 let offset = relocation.offset as usize;
624 match size {
625 32 => data.write_at(offset, &U32::new(self.endian, relocation.addend as u32)),
626 64 => data.write_at(offset, &U64::new(self.endian, relocation.addend as u64)),
627 _ => {
628 return Err(Error(format!(
629 "unimplemented relocation addend {:?}",
630 relocation
631 )));
632 }
633 }
634 .map_err(|_| {
635 Error(format!(
636 "invalid relocation offset {}+{} (max {})",
637 relocation.offset,
638 size,
639 data.len()
640 ))
641 })
642 }
643
644 /// Write the object to a `Vec`.
645 pub fn write(&self) -> Result<Vec<u8>> {
646 let mut buffer = Vec::new();
647 self.emit(&mut buffer)?;
648 Ok(buffer)
649 }
650
651 /// Write the object to a `Write` implementation.
652 ///
653 /// Also flushes the writer.
654 ///
655 /// It is advisable to use a buffered writer like [`BufWriter`](std::io::BufWriter)
656 /// instead of an unbuffered writer like [`File`](std::fs::File).
657 #[cfg(feature = "std")]
658 pub fn write_stream<W: io::Write>(&self, w: W) -> result::Result<(), Box<dyn error::Error>> {
659 let mut stream = StreamingBuffer::new(w);
660 self.emit(&mut stream)?;
661 stream.result()?;
662 stream.into_inner().flush()?;
663 Ok(())
664 }
665
666 /// Write the object to a `WritableBuffer`.
667 pub fn emit(&self, buffer: &mut dyn WritableBuffer) -> Result<()> {
668 match self.format {
669 #[cfg(feature = "coff")]
670 BinaryFormat::Coff => self.coff_write(buffer),
671 #[cfg(feature = "elf")]
672 BinaryFormat::Elf => self.elf_write(buffer),
673 #[cfg(feature = "macho")]
674 BinaryFormat::MachO => self.macho_write(buffer),
675 #[cfg(feature = "xcoff")]
676 BinaryFormat::Xcoff => self.xcoff_write(buffer),
677 _ => unimplemented!(),
678 }
679 }
680 }
681
682 /// A standard segment kind.
683 #[allow(missing_docs)]
684 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
685 #[non_exhaustive]
686 pub enum StandardSegment {
687 Text,
688 Data,
689 Debug,
690 }
691
692 /// A standard section kind.
693 #[allow(missing_docs)]
694 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
695 #[non_exhaustive]
696 pub enum StandardSection {
697 Text,
698 Data,
699 ReadOnlyData,
700 ReadOnlyDataWithRel,
701 ReadOnlyString,
702 UninitializedData,
703 Tls,
704 /// Zero-fill TLS initializers. Unsupported for COFF.
705 UninitializedTls,
706 /// TLS variable structures. Only supported for Mach-O.
707 TlsVariables,
708 /// Common data. Only supported for Mach-O.
709 Common,
710 /// Notes for GNU properties. Only supported for ELF.
711 GnuProperty,
712 }
713
714 impl StandardSection {
715 /// Return the section kind of a standard section.
716 pub fn kind(self) -> SectionKind {
717 match self {
718 StandardSection::Text => SectionKind::Text,
719 StandardSection::Data => SectionKind::Data,
720 StandardSection::ReadOnlyData => SectionKind::ReadOnlyData,
721 StandardSection::ReadOnlyDataWithRel => SectionKind::ReadOnlyDataWithRel,
722 StandardSection::ReadOnlyString => SectionKind::ReadOnlyString,
723 StandardSection::UninitializedData => SectionKind::UninitializedData,
724 StandardSection::Tls => SectionKind::Tls,
725 StandardSection::UninitializedTls => SectionKind::UninitializedTls,
726 StandardSection::TlsVariables => SectionKind::TlsVariables,
727 StandardSection::Common => SectionKind::Common,
728 StandardSection::GnuProperty => SectionKind::Note,
729 }
730 }
731
732 // TODO: remembering to update this is error-prone, can we do better?
733 fn all() -> &'static [StandardSection] {
734 &[
735 StandardSection::Text,
736 StandardSection::Data,
737 StandardSection::ReadOnlyData,
738 StandardSection::ReadOnlyDataWithRel,
739 StandardSection::ReadOnlyString,
740 StandardSection::UninitializedData,
741 StandardSection::Tls,
742 StandardSection::UninitializedTls,
743 StandardSection::TlsVariables,
744 StandardSection::Common,
745 StandardSection::GnuProperty,
746 ]
747 }
748 }
749
750 /// An identifier used to reference a section.
751 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
752 pub struct SectionId(usize);
753
754 /// A section in an object file.
755 #[derive(Debug)]
756 pub struct Section<'a> {
757 segment: Vec<u8>,
758 name: Vec<u8>,
759 kind: SectionKind,
760 size: u64,
761 align: u64,
762 data: Cow<'a, [u8]>,
763 relocations: Vec<Relocation>,
764 symbol: Option<SymbolId>,
765 /// Section flags that are specific to each file format.
766 pub flags: SectionFlags,
767 }
768
769 impl<'a> Section<'a> {
770 /// Try to convert the name to a utf8 string.
771 #[inline]
772 pub fn name(&self) -> Option<&str> {
773 str::from_utf8(&self.name).ok()
774 }
775
776 /// Try to convert the segment to a utf8 string.
777 #[inline]
778 pub fn segment(&self) -> Option<&str> {
779 str::from_utf8(&self.segment).ok()
780 }
781
782 /// Return true if this section contains zerofill data.
783 #[inline]
784 pub fn is_bss(&self) -> bool {
785 self.kind.is_bss()
786 }
787
788 /// Set the data for a section.
789 ///
790 /// Must not be called for sections that already have data, or that contain uninitialized data.
791 /// `align` must be a power of two.
792 pub fn set_data<T>(&mut self, data: T, align: u64)
793 where
794 T: Into<Cow<'a, [u8]>>,
795 {
796 debug_assert!(!self.is_bss());
797 debug_assert_eq!(align & (align - 1), 0);
798 debug_assert!(self.data.is_empty());
799 self.data = data.into();
800 self.size = self.data.len() as u64;
801 self.align = align;
802 }
803
804 /// Append data to a section.
805 ///
806 /// Must not be called for sections that contain uninitialized data.
807 /// `align` must be a power of two.
808 pub fn append_data(&mut self, append_data: &[u8], align: u64) -> u64 {
809 debug_assert!(!self.is_bss());
810 debug_assert_eq!(align & (align - 1), 0);
811 if self.align < align {
812 self.align = align;
813 }
814 let align = align as usize;
815 let data = self.data.to_mut();
816 let mut offset = data.len();
817 if offset & (align - 1) != 0 {
818 offset += align - (offset & (align - 1));
819 data.resize(offset, 0);
820 }
821 data.extend_from_slice(append_data);
822 self.size = data.len() as u64;
823 offset as u64
824 }
825
826 /// Append uninitialized data to a section.
827 ///
828 /// Must not be called for sections that contain initialized data.
829 /// `align` must be a power of two.
830 pub fn append_bss(&mut self, size: u64, align: u64) -> u64 {
831 debug_assert!(self.is_bss());
832 debug_assert_eq!(align & (align - 1), 0);
833 if self.align < align {
834 self.align = align;
835 }
836 let mut offset = self.size;
837 if offset & (align - 1) != 0 {
838 offset += align - (offset & (align - 1));
839 self.size = offset;
840 }
841 self.size += size;
842 offset
843 }
844
845 /// Returns the section as-built so far.
846 ///
847 /// This requires that the section is not a bss section.
848 pub fn data(&self) -> &[u8] {
849 debug_assert!(!self.is_bss());
850 &self.data
851 }
852
853 /// Returns the section as-built so far.
854 ///
855 /// This requires that the section is not a bss section.
856 pub fn data_mut(&mut self) -> &mut [u8] {
857 debug_assert!(!self.is_bss());
858 self.data.to_mut()
859 }
860 }
861
862 /// The section where a symbol is defined.
863 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
864 #[non_exhaustive]
865 pub enum SymbolSection {
866 /// The section is not applicable for this symbol (such as file symbols).
867 None,
868 /// The symbol is undefined.
869 Undefined,
870 /// The symbol has an absolute value.
871 Absolute,
872 /// The symbol is a zero-initialized symbol that will be combined with duplicate definitions.
873 Common,
874 /// The symbol is defined in the given section.
875 Section(SectionId),
876 }
877
878 impl SymbolSection {
879 /// Returns the section id for the section where the symbol is defined.
880 ///
881 /// May return `None` if the symbol is not defined in a section.
882 #[inline]
883 pub fn id(self) -> Option<SectionId> {
884 if let SymbolSection::Section(id) = self {
885 Some(id)
886 } else {
887 None
888 }
889 }
890 }
891
892 /// An identifier used to reference a symbol.
893 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
894 pub struct SymbolId(usize);
895
896 /// A symbol in an object file.
897 #[derive(Debug)]
898 pub struct Symbol {
899 /// The name of the symbol.
900 pub name: Vec<u8>,
901 /// The value of the symbol.
902 ///
903 /// If the symbol defined in a section, then this is the section offset of the symbol.
904 pub value: u64,
905 /// The size of the symbol.
906 pub size: u64,
907 /// The kind of the symbol.
908 pub kind: SymbolKind,
909 /// The scope of the symbol.
910 pub scope: SymbolScope,
911 /// Whether the symbol has weak binding.
912 pub weak: bool,
913 /// The section containing the symbol.
914 pub section: SymbolSection,
915 /// Symbol flags that are specific to each file format.
916 pub flags: SymbolFlags<SectionId, SymbolId>,
917 }
918
919 impl Symbol {
920 /// Try to convert the name to a utf8 string.
921 #[inline]
922 pub fn name(&self) -> Option<&str> {
923 str::from_utf8(&self.name).ok()
924 }
925
926 /// Return true if the symbol is undefined.
927 #[inline]
928 pub fn is_undefined(&self) -> bool {
929 self.section == SymbolSection::Undefined
930 }
931
932 /// Return true if the symbol is common data.
933 ///
934 /// Note: does not check for `SymbolSection::Section` with `SectionKind::Common`.
935 #[inline]
936 pub fn is_common(&self) -> bool {
937 self.section == SymbolSection::Common
938 }
939
940 /// Return true if the symbol scope is local.
941 #[inline]
942 pub fn is_local(&self) -> bool {
943 self.scope == SymbolScope::Compilation
944 }
945 }
946
947 /// A relocation in an object file.
948 #[derive(Debug)]
949 pub struct Relocation {
950 /// The section offset of the place of the relocation.
951 pub offset: u64,
952 /// The symbol referred to by the relocation.
953 ///
954 /// This may be a section symbol.
955 pub symbol: SymbolId,
956 /// The addend to use in the relocation calculation.
957 ///
958 /// This may be in addition to an implicit addend stored at the place of the relocation.
959 pub addend: i64,
960 /// The fields that define the relocation type.
961 pub flags: RelocationFlags,
962 }
963
964 /// An identifier used to reference a COMDAT section group.
965 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
966 pub struct ComdatId(usize);
967
968 /// A COMDAT section group.
969 #[derive(Debug)]
970 pub struct Comdat {
971 /// The COMDAT selection kind.
972 ///
973 /// This determines the way in which the linker resolves multiple definitions of the COMDAT
974 /// sections.
975 pub kind: ComdatKind,
976 /// The COMDAT symbol.
977 ///
978 /// If this symbol is referenced, then all sections in the group will be included by the
979 /// linker.
980 pub symbol: SymbolId,
981 /// The sections in the group.
982 pub sections: Vec<SectionId>,
983 }
984
985 /// The symbol name mangling scheme.
986 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
987 #[non_exhaustive]
988 pub enum Mangling {
989 /// No symbol mangling.
990 None,
991 /// Windows COFF symbol mangling.
992 Coff,
993 /// Windows COFF i386 symbol mangling.
994 CoffI386,
995 /// ELF symbol mangling.
996 Elf,
997 /// Mach-O symbol mangling.
998 MachO,
999 /// Xcoff symbol mangling.
1000 Xcoff,
1001 }
1002
1003 impl Mangling {
1004 /// Return the default symboling mangling for the given format and architecture.
1005 pub fn default(format: BinaryFormat, architecture: Architecture) -> Self {
1006 match (format, architecture) {
1007 (BinaryFormat::Coff, Architecture::I386) => Mangling::CoffI386,
1008 (BinaryFormat::Coff, _) => Mangling::Coff,
1009 (BinaryFormat::Elf, _) => Mangling::Elf,
1010 (BinaryFormat::MachO, _) => Mangling::MachO,
1011 (BinaryFormat::Xcoff, _) => Mangling::Xcoff,
1012 _ => Mangling::None,
1013 }
1014 }
1015
1016 /// Return the prefix to use for global symbols.
1017 pub fn global_prefix(self) -> Option<u8> {
1018 match self {
1019 Mangling::None | Mangling::Elf | Mangling::Coff | Mangling::Xcoff => None,
1020 Mangling::CoffI386 | Mangling::MachO => Some(b'_'),
1021 }
1022 }
1023 }