Debian Codegraph @

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

raw
1 use core::mem;
2
3 use crate::endian::*;
4 use crate::macho;
5 use crate::write::string::*;
6 use crate::write::util::*;
7 use crate::write::*;
8
9 #[derive(Default, Clone, Copy)]
10 struct SectionOffsets {
11 index: usize,
12 offset: usize,
13 address: u64,
14 reloc_offset: usize,
15 reloc_count: usize,
16 }
17
18 #[derive(Default, Clone, Copy)]
19 struct SymbolOffsets {
20 index: usize,
21 str_id: Option<StringId>,
22 }
23
24 /// The customizable portion of a [`macho::BuildVersionCommand`].
25 #[derive(Debug, Default, Clone, Copy)]
26 #[non_exhaustive] // May want to add the tool list?
27 pub struct MachOBuildVersion {
28 /// One of the `PLATFORM_` constants (for example,
29 /// [`object::macho::PLATFORM_MACOS`](macho::PLATFORM_MACOS)).
30 pub platform: u32,
31 /// The minimum OS version, where `X.Y.Z` is encoded in nibbles as
32 /// `xxxx.yy.zz`.
33 pub minos: u32,
34 /// The SDK version as `X.Y.Z`, where `X.Y.Z` is encoded in nibbles as
35 /// `xxxx.yy.zz`.
36 pub sdk: u32,
37 }
38
39 impl MachOBuildVersion {
40 fn cmdsize(&self) -> u32 {
41 // Same size for both endianness, and we don't have `ntools`.
42 let sz = mem::size_of::<macho::BuildVersionCommand<Endianness>>();
43 debug_assert!(sz <= u32::MAX as usize);
44 sz as u32
45 }
46 }
47
48 // Public methods.
49 impl<'a> Object<'a> {
50 /// Specify the Mach-O CPU subtype.
51 ///
52 /// Requires `feature = "macho"`.
53 #[inline]
54 pub fn set_macho_cpu_subtype(&mut self, cpu_subtype: u32) {
55 self.macho_cpu_subtype = Some(cpu_subtype);
56 }
57
58 /// Specify information for a Mach-O `LC_BUILD_VERSION` command.
59 ///
60 /// Requires `feature = "macho"`.
61 #[inline]
62 pub fn set_macho_build_version(&mut self, info: MachOBuildVersion) {
63 self.macho_build_version = Some(info);
64 }
65 }
66
67 // Private methods.
68 impl<'a> Object<'a> {
69 pub(crate) fn macho_segment_name(&self, segment: StandardSegment) -> &'static [u8] {
70 match segment {
71 StandardSegment::Text => &b"__TEXT"[..],
72 StandardSegment::Data => &b"__DATA"[..],
73 StandardSegment::Debug => &b"__DWARF"[..],
74 }
75 }
76
77 pub(crate) fn macho_section_info(
78 &self,
79 section: StandardSection,
80 ) -> (&'static [u8], &'static [u8], SectionKind, SectionFlags) {
81 match section {
82 StandardSection::Text => (
83 &b"__TEXT"[..],
84 &b"__text"[..],
85 SectionKind::Text,
86 SectionFlags::None,
87 ),
88 StandardSection::Data => (
89 &b"__DATA"[..],
90 &b"__data"[..],
91 SectionKind::Data,
92 SectionFlags::None,
93 ),
94 StandardSection::ReadOnlyData => (
95 &b"__TEXT"[..],
96 &b"__const"[..],
97 SectionKind::ReadOnlyData,
98 SectionFlags::None,
99 ),
100 StandardSection::ReadOnlyDataWithRel => (
101 &b"__DATA"[..],
102 &b"__const"[..],
103 SectionKind::ReadOnlyDataWithRel,
104 SectionFlags::None,
105 ),
106 StandardSection::ReadOnlyString => (
107 &b"__TEXT"[..],
108 &b"__cstring"[..],
109 SectionKind::ReadOnlyString,
110 SectionFlags::None,
111 ),
112 StandardSection::UninitializedData => (
113 &b"__DATA"[..],
114 &b"__bss"[..],
115 SectionKind::UninitializedData,
116 SectionFlags::None,
117 ),
118 StandardSection::Tls => (
119 &b"__DATA"[..],
120 &b"__thread_data"[..],
121 SectionKind::Tls,
122 SectionFlags::None,
123 ),
124 StandardSection::UninitializedTls => (
125 &b"__DATA"[..],
126 &b"__thread_bss"[..],
127 SectionKind::UninitializedTls,
128 SectionFlags::None,
129 ),
130 StandardSection::TlsVariables => (
131 &b"__DATA"[..],
132 &b"__thread_vars"[..],
133 SectionKind::TlsVariables,
134 SectionFlags::None,
135 ),
136 StandardSection::Common => (
137 &b"__DATA"[..],
138 &b"__common"[..],
139 SectionKind::Common,
140 SectionFlags::None,
141 ),
142 StandardSection::GnuProperty => {
143 // Unsupported section.
144 (&[], &[], SectionKind::Note, SectionFlags::None)
145 }
146 }
147 }
148
149 fn macho_tlv_bootstrap(&mut self) -> SymbolId {
150 match self.tlv_bootstrap {
151 Some(id) => id,
152 None => {
153 let id = self.add_symbol(Symbol {
154 name: b"_tlv_bootstrap".to_vec(),
155 value: 0,
156 size: 0,
157 kind: SymbolKind::Text,
158 scope: SymbolScope::Dynamic,
159 weak: false,
160 section: SymbolSection::Undefined,
161 flags: SymbolFlags::None,
162 });
163 self.tlv_bootstrap = Some(id);
164 id
165 }
166 }
167 }
168
169 /// Create the `__thread_vars` entry for a TLS variable.
170 ///
171 /// The symbol given by `symbol_id` will be updated to point to this entry.
172 ///
173 /// A new `SymbolId` will be returned. The caller must update this symbol
174 /// to point to the initializer.
175 ///
176 /// If `symbol_id` is not for a TLS variable, then it is returned unchanged.
177 pub(crate) fn macho_add_thread_var(&mut self, symbol_id: SymbolId) -> SymbolId {
178 let symbol = self.symbol_mut(symbol_id);
179 if symbol.kind != SymbolKind::Tls {
180 return symbol_id;
181 }
182
183 // Create the initializer symbol.
184 let mut name = symbol.name.clone();
185 name.extend_from_slice(b"$tlv$init");
186 let init_symbol_id = self.add_raw_symbol(Symbol {
187 name,
188 value: 0,
189 size: 0,
190 kind: SymbolKind::Tls,
191 scope: SymbolScope::Compilation,
192 weak: false,
193 section: SymbolSection::Undefined,
194 flags: SymbolFlags::None,
195 });
196
197 // Add the tlv entry.
198 // Three pointers in size:
199 // - __tlv_bootstrap - used to make sure support exists
200 // - spare pointer - used when mapped by the runtime
201 // - pointer to symbol initializer
202 let section = self.section_id(StandardSection::TlsVariables);
203 let address_size = self.architecture.address_size().unwrap().bytes();
204 let size = u64::from(address_size) * 3;
205 let data = vec![0; size as usize];
206 let offset = self.append_section_data(section, &data, u64::from(address_size));
207
208 let tlv_bootstrap = self.macho_tlv_bootstrap();
209 self.add_relocation(
210 section,
211 Relocation {
212 offset,
213 symbol: tlv_bootstrap,
214 addend: 0,
215 flags: RelocationFlags::Generic {
216 kind: RelocationKind::Absolute,
217 encoding: RelocationEncoding::Generic,
218 size: address_size * 8,
219 },
220 },
221 )
222 .unwrap();
223 self.add_relocation(
224 section,
225 Relocation {
226 offset: offset + u64::from(address_size) * 2,
227 symbol: init_symbol_id,
228 addend: 0,
229 flags: RelocationFlags::Generic {
230 kind: RelocationKind::Absolute,
231 encoding: RelocationEncoding::Generic,
232 size: address_size * 8,
233 },
234 },
235 )
236 .unwrap();
237
238 // Update the symbol to point to the tlv.
239 let symbol = self.symbol_mut(symbol_id);
240 symbol.value = offset;
241 symbol.size = size;
242 symbol.section = SymbolSection::Section(section);
243
244 init_symbol_id
245 }
246
247 pub(crate) fn macho_translate_relocation(&mut self, reloc: &mut Relocation) -> Result<()> {
248 let (kind, encoding, mut size) = if let RelocationFlags::Generic {
249 kind,
250 encoding,
251 size,
252 } = reloc.flags
253 {
254 (kind, encoding, size)
255 } else {
256 return Ok(());
257 };
258 // Aarch64 relocs of these sizes act as if they are double-word length
259 if self.architecture == Architecture::Aarch64 && matches!(size, 12 | 21 | 26) {
260 size = 32;
261 }
262 let r_length = match size {
263 8 => 0,
264 16 => 1,
265 32 => 2,
266 64 => 3,
267 _ => return Err(Error(format!("unimplemented reloc size {:?}", reloc))),
268 };
269 let (r_pcrel, r_type) = match self.architecture {
270 Architecture::I386 => match kind {
271 RelocationKind::Absolute => (false, macho::GENERIC_RELOC_VANILLA),
272 _ => {
273 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
274 }
275 },
276 Architecture::X86_64 => match (kind, encoding) {
277 (RelocationKind::Absolute, RelocationEncoding::Generic) => {
278 (false, macho::X86_64_RELOC_UNSIGNED)
279 }
280 (RelocationKind::Relative, RelocationEncoding::Generic) => {
281 (true, macho::X86_64_RELOC_SIGNED)
282 }
283 (RelocationKind::Relative, RelocationEncoding::X86RipRelative) => {
284 (true, macho::X86_64_RELOC_SIGNED)
285 }
286 (RelocationKind::Relative, RelocationEncoding::X86Branch) => {
287 (true, macho::X86_64_RELOC_BRANCH)
288 }
289 (RelocationKind::PltRelative, RelocationEncoding::X86Branch) => {
290 (true, macho::X86_64_RELOC_BRANCH)
291 }
292 (RelocationKind::GotRelative, RelocationEncoding::Generic) => {
293 (true, macho::X86_64_RELOC_GOT)
294 }
295 (RelocationKind::GotRelative, RelocationEncoding::X86RipRelativeMovq) => {
296 (true, macho::X86_64_RELOC_GOT_LOAD)
297 }
298 _ => {
299 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
300 }
301 },
302 Architecture::Aarch64 | Architecture::Aarch64_Ilp32 => match (kind, encoding) {
303 (RelocationKind::Absolute, RelocationEncoding::Generic) => {
304 (false, macho::ARM64_RELOC_UNSIGNED)
305 }
306 (RelocationKind::Relative, RelocationEncoding::AArch64Call) => {
307 (true, macho::ARM64_RELOC_BRANCH26)
308 }
309 _ => {
310 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
311 }
312 },
313 _ => {
314 return Err(Error(format!("unimplemented relocation {:?}", reloc)));
315 }
316 };
317 reloc.flags = RelocationFlags::MachO {
318 r_type,
319 r_pcrel,
320 r_length,
321 };
322 Ok(())
323 }
324
325 pub(crate) fn macho_adjust_addend(&mut self, relocation: &mut Relocation) -> Result<bool> {
326 let (r_type, r_pcrel) = if let RelocationFlags::MachO {
327 r_type, r_pcrel, ..
328 } = relocation.flags
329 {
330 (r_type, r_pcrel)
331 } else {
332 return Err(Error(format!("invalid relocation flags {:?}", relocation)));
333 };
334 if r_pcrel {
335 // For PC relative relocations on some architectures, the
336 // addend does not include the offset required due to the
337 // PC being different from the place of the relocation.
338 // This differs from other file formats, so adjust the
339 // addend here to account for this.
340 let pcrel_offset = match self.architecture {
341 Architecture::I386 => 4,
342 Architecture::X86_64 => match r_type {
343 macho::X86_64_RELOC_SIGNED_1 => 5,
344 macho::X86_64_RELOC_SIGNED_2 => 6,
345 macho::X86_64_RELOC_SIGNED_4 => 8,
346 _ => 4,
347 },
348 // TODO: maybe missing support for some architectures and relocations
349 _ => 0,
350 };
351 relocation.addend += pcrel_offset;
352 }
353 // Determine if addend is implicit.
354 let implicit = if self.architecture == Architecture::Aarch64 {
355 match r_type {
356 macho::ARM64_RELOC_BRANCH26
357 | macho::ARM64_RELOC_PAGE21
358 | macho::ARM64_RELOC_PAGEOFF12 => false,
359 _ => true,
360 }
361 } else {
362 true
363 };
364 Ok(implicit)
365 }
366
367 pub(crate) fn macho_relocation_size(&self, reloc: &Relocation) -> Result<u8> {
368 if let RelocationFlags::MachO { r_length, .. } = reloc.flags {
369 Ok(8 << r_length)
370 } else {
371 Err(Error("invalid relocation flags".into()))
372 }
373 }
374
375 pub(crate) fn macho_write(&self, buffer: &mut dyn WritableBuffer) -> Result<()> {
376 let address_size = self.architecture.address_size().unwrap();
377 let endian = self.endian;
378 let macho32 = MachO32 { endian };
379 let macho64 = MachO64 { endian };
380 let macho: &dyn MachO = match address_size {
381 AddressSize::U8 | AddressSize::U16 | AddressSize::U32 => &macho32,
382 AddressSize::U64 => &macho64,
383 };
384 let pointer_align = address_size.bytes() as usize;
385
386 // Calculate offsets of everything, and build strtab.
387 let mut offset = 0;
388
389 // Calculate size of Mach-O header.
390 offset += macho.mach_header_size();
391
392 // Calculate size of commands.
393 let mut ncmds = 0;
394 let command_offset = offset;
395
396 // Calculate size of segment command and section headers.
397 let segment_command_offset = offset;
398 let segment_command_len =
399 macho.segment_command_size() + self.sections.len() * macho.section_header_size();
400 offset += segment_command_len;
401 ncmds += 1;
402
403 // Calculate size of build version.
404 let build_version_offset = offset;
405 if let Some(version) = &self.macho_build_version {
406 offset += version.cmdsize() as usize;
407 ncmds += 1;
408 }
409
410 // Calculate size of symtab command.
411 let symtab_command_offset = offset;
412 let symtab_command_len = mem::size_of::<macho::SymtabCommand<Endianness>>();
413 offset += symtab_command_len;
414 ncmds += 1;
415
416 // Calculate size of dysymtab command.
417 let dysymtab_command_offset = offset;
418 let dysymtab_command_len = mem::size_of::<macho::DysymtabCommand<Endianness>>();
419 offset += dysymtab_command_len;
420 ncmds += 1;
421
422 let sizeofcmds = offset - command_offset;
423
424 // Calculate size of section data.
425 // Section data can immediately follow the load commands without any alignment padding.
426 let segment_file_offset = offset;
427 let mut section_offsets = vec![SectionOffsets::default(); self.sections.len()];
428 let mut address = 0;
429 for (index, section) in self.sections.iter().enumerate() {
430 section_offsets[index].index = 1 + index;
431 if !section.is_bss() {
432 address = align_u64(address, section.align);
433 section_offsets[index].address = address;
434 section_offsets[index].offset = segment_file_offset + address as usize;
435 address += section.size;
436 }
437 }
438 let segment_file_size = address as usize;
439 offset += address as usize;
440 for (index, section) in self.sections.iter().enumerate() {
441 if section.is_bss() {
442 debug_assert!(section.data.is_empty());
443 address = align_u64(address, section.align);
444 section_offsets[index].address = address;
445 address += section.size;
446 }
447 }
448
449 // Partition symbols and add symbol strings to strtab.
450 let mut strtab = StringTable::default();
451 let mut symbol_offsets = vec![SymbolOffsets::default(); self.symbols.len()];
452 let mut local_symbols = vec![];
453 let mut external_symbols = vec![];
454 let mut undefined_symbols = vec![];
455 for (index, symbol) in self.symbols.iter().enumerate() {
456 // The unified API allows creating symbols that we don't emit, so filter
457 // them out here.
458 //
459 // Since we don't actually emit the symbol kind, we validate it here too.
460 match symbol.kind {
461 SymbolKind::Text | SymbolKind::Data | SymbolKind::Tls | SymbolKind::Unknown => {}
462 SymbolKind::File | SymbolKind::Section => continue,
463 SymbolKind::Label => {
464 return Err(Error(format!(
465 "unimplemented symbol `{}` kind {:?}",
466 symbol.name().unwrap_or(""),
467 symbol.kind
468 )));
469 }
470 }
471 if !symbol.name.is_empty() {
472 symbol_offsets[index].str_id = Some(strtab.add(&symbol.name));
473 }
474 if symbol.is_undefined() {
475 undefined_symbols.push(index);
476 } else if symbol.is_local() {
477 local_symbols.push(index);
478 } else {
479 external_symbols.push(index);
480 }
481 }
482
483 external_symbols.sort_by_key(|index| &*self.symbols[*index].name);
484 undefined_symbols.sort_by_key(|index| &*self.symbols[*index].name);
485
486 // Count symbols.
487 let mut nsyms = 0;
488 for index in local_symbols
489 .iter()
490 .copied()
491 .chain(external_symbols.iter().copied())
492 .chain(undefined_symbols.iter().copied())
493 {
494 symbol_offsets[index].index = nsyms;
495 nsyms += 1;
496 }
497
498 // Calculate size of relocations.
499 for (index, section) in self.sections.iter().enumerate() {
500 let count: usize = section
501 .relocations
502 .iter()
503 .map(|reloc| 1 + usize::from(reloc.addend != 0))
504 .sum();
505 if count != 0 {
506 offset = align(offset, pointer_align);
507 section_offsets[index].reloc_offset = offset;
508 section_offsets[index].reloc_count = count;
509 let len = count * mem::size_of::<macho::Relocation<Endianness>>();
510 offset += len;
511 }
512 }
513
514 // Calculate size of symtab.
515 offset = align(offset, pointer_align);
516 let symtab_offset = offset;
517 let symtab_len = nsyms * macho.nlist_size();
518 offset += symtab_len;
519
520 // Calculate size of strtab.
521 let strtab_offset = offset;
522 // Start with null name.
523 let mut strtab_data = vec![0];
524 strtab.write(1, &mut strtab_data);
525 write_align(&mut strtab_data, pointer_align);
526 offset += strtab_data.len();
527
528 // Start writing.
529 buffer
530 .reserve(offset)
531 .map_err(|_| Error(String::from("Cannot allocate buffer")))?;
532
533 // Write file header.
534 let (cputype, mut cpusubtype) = match (self.architecture, self.sub_architecture) {
535 (Architecture::Arm, None) => (macho::CPU_TYPE_ARM, macho::CPU_SUBTYPE_ARM_ALL),
536 (Architecture::Aarch64, None) => (macho::CPU_TYPE_ARM64, macho::CPU_SUBTYPE_ARM64_ALL),
537 (Architecture::Aarch64, Some(SubArchitecture::Arm64E)) => {
538 (macho::CPU_TYPE_ARM64, macho::CPU_SUBTYPE_ARM64E)
539 }
540 (Architecture::Aarch64_Ilp32, None) => {
541 (macho::CPU_TYPE_ARM64_32, macho::CPU_SUBTYPE_ARM64_32_V8)
542 }
543 (Architecture::I386, None) => (macho::CPU_TYPE_X86, macho::CPU_SUBTYPE_I386_ALL),
544 (Architecture::X86_64, None) => (macho::CPU_TYPE_X86_64, macho::CPU_SUBTYPE_X86_64_ALL),
545 (Architecture::PowerPc, None) => {
546 (macho::CPU_TYPE_POWERPC, macho::CPU_SUBTYPE_POWERPC_ALL)
547 }
548 (Architecture::PowerPc64, None) => {
549 (macho::CPU_TYPE_POWERPC64, macho::CPU_SUBTYPE_POWERPC_ALL)
550 }
551 _ => {
552 return Err(Error(format!(
553 "unimplemented architecture {:?} with sub-architecture {:?}",
554 self.architecture, self.sub_architecture
555 )));
556 }
557 };
558
559 if let Some(cpu_subtype) = self.macho_cpu_subtype {
560 cpusubtype = cpu_subtype;
561 }
562
563 let mut flags = match self.flags {
564 FileFlags::MachO { flags } => flags,
565 _ => 0,
566 };
567 if self.macho_subsections_via_symbols {
568 flags |= macho::MH_SUBSECTIONS_VIA_SYMBOLS;
569 }
570 macho.write_mach_header(
571 buffer,
572 MachHeader {
573 cputype,
574 cpusubtype,
575 filetype: macho::MH_OBJECT,
576 ncmds,
577 sizeofcmds: sizeofcmds as u32,
578 flags,
579 },
580 );
581
582 // Write segment command.
583 debug_assert_eq!(segment_command_offset, buffer.len());
584 macho.write_segment_command(
585 buffer,
586 SegmentCommand {
587 cmdsize: segment_command_len as u32,
588 segname: [0; 16],
589 vmaddr: 0,
590 vmsize: address,
591 fileoff: segment_file_offset as u64,
592 filesize: segment_file_size as u64,
593 maxprot: macho::VM_PROT_READ | macho::VM_PROT_WRITE | macho::VM_PROT_EXECUTE,
594 initprot: macho::VM_PROT_READ | macho::VM_PROT_WRITE | macho::VM_PROT_EXECUTE,
595 nsects: self.sections.len() as u32,
596 flags: 0,
597 },
598 );
599
600 // Write section headers.
601 for (index, section) in self.sections.iter().enumerate() {
602 let mut sectname = [0; 16];
603 sectname
604 .get_mut(..section.name.len())
605 .ok_or_else(|| {
606 Error(format!(
607 "section name `{}` is too long",
608 section.name().unwrap_or(""),
609 ))
610 })?
611 .copy_from_slice(&section.name);
612 let mut segname = [0; 16];
613 segname
614 .get_mut(..section.segment.len())
615 .ok_or_else(|| {
616 Error(format!(
617 "segment name `{}` is too long",
618 section.segment().unwrap_or(""),
619 ))
620 })?
621 .copy_from_slice(&section.segment);
622 let flags = if let SectionFlags::MachO { flags } = section.flags {
623 flags
624 } else {
625 match section.kind {
626 SectionKind::Text => {
627 macho::S_ATTR_PURE_INSTRUCTIONS | macho::S_ATTR_SOME_INSTRUCTIONS
628 }
629 SectionKind::Data => 0,
630 SectionKind::ReadOnlyData | SectionKind::ReadOnlyDataWithRel => 0,
631 SectionKind::ReadOnlyString => macho::S_CSTRING_LITERALS,
632 SectionKind::UninitializedData | SectionKind::Common => macho::S_ZEROFILL,
633 SectionKind::Tls => macho::S_THREAD_LOCAL_REGULAR,
634 SectionKind::UninitializedTls => macho::S_THREAD_LOCAL_ZEROFILL,
635 SectionKind::TlsVariables => macho::S_THREAD_LOCAL_VARIABLES,
636 SectionKind::Debug | SectionKind::DebugString => macho::S_ATTR_DEBUG,
637 SectionKind::OtherString => macho::S_CSTRING_LITERALS,
638 SectionKind::Other | SectionKind::Linker | SectionKind::Metadata => 0,
639 SectionKind::Note | SectionKind::Unknown | SectionKind::Elf(_) => {
640 return Err(Error(format!(
641 "unimplemented section `{}` kind {:?}",
642 section.name().unwrap_or(""),
643 section.kind
644 )));
645 }
646 }
647 };
648 macho.write_section(
649 buffer,
650 SectionHeader {
651 sectname,
652 segname,
653 addr: section_offsets[index].address,
654 size: section.size,
655 offset: section_offsets[index].offset as u32,
656 align: section.align.trailing_zeros(),
657 reloff: section_offsets[index].reloc_offset as u32,
658 nreloc: section_offsets[index].reloc_count as u32,
659 flags,
660 },
661 );
662 }
663
664 // Write build version.
665 if let Some(version) = &self.macho_build_version {
666 debug_assert_eq!(build_version_offset, buffer.len());
667 buffer.write(&macho::BuildVersionCommand {
668 cmd: U32::new(endian, macho::LC_BUILD_VERSION),
669 cmdsize: U32::new(endian, version.cmdsize()),
670 platform: U32::new(endian, version.platform),
671 minos: U32::new(endian, version.minos),
672 sdk: U32::new(endian, version.sdk),
673 ntools: U32::new(endian, 0),
674 });
675 }
676
677 // Write symtab command.
678 debug_assert_eq!(symtab_command_offset, buffer.len());
679 let symtab_command = macho::SymtabCommand {
680 cmd: U32::new(endian, macho::LC_SYMTAB),
681 cmdsize: U32::new(endian, symtab_command_len as u32),
682 symoff: U32::new(endian, symtab_offset as u32),
683 nsyms: U32::new(endian, nsyms as u32),
684 stroff: U32::new(endian, strtab_offset as u32),
685 strsize: U32::new(endian, strtab_data.len() as u32),
686 };
687 buffer.write(&symtab_command);
688
689 // Write dysymtab command.
690 debug_assert_eq!(dysymtab_command_offset, buffer.len());
691 let dysymtab_command = macho::DysymtabCommand {
692 cmd: U32::new(endian, macho::LC_DYSYMTAB),
693 cmdsize: U32::new(endian, dysymtab_command_len as u32),
694 ilocalsym: U32::new(endian, 0),
695 nlocalsym: U32::new(endian, local_symbols.len() as u32),
696 iextdefsym: U32::new(endian, local_symbols.len() as u32),
697 nextdefsym: U32::new(endian, external_symbols.len() as u32),
698 iundefsym: U32::new(
699 endian,
700 local_symbols.len() as u32 + external_symbols.len() as u32,
701 ),
702 nundefsym: U32::new(endian, undefined_symbols.len() as u32),
703 tocoff: U32::default(),
704 ntoc: U32::default(),
705 modtaboff: U32::default(),
706 nmodtab: U32::default(),
707 extrefsymoff: U32::default(),
708 nextrefsyms: U32::default(),
709 indirectsymoff: U32::default(),
710 nindirectsyms: U32::default(),
711 extreloff: U32::default(),
712 nextrel: U32::default(),
713 locreloff: U32::default(),
714 nlocrel: U32::default(),
715 };
716 buffer.write(&dysymtab_command);
717
718 // Write section data.
719 for (index, section) in self.sections.iter().enumerate() {
720 if !section.is_bss() {
721 buffer.resize(section_offsets[index].offset);
722 buffer.write_bytes(&section.data);
723 }
724 }
725 debug_assert_eq!(segment_file_offset + segment_file_size, buffer.len());
726
727 // Write relocations.
728 for (index, section) in self.sections.iter().enumerate() {
729 if !section.relocations.is_empty() {
730 write_align(buffer, pointer_align);
731 debug_assert_eq!(section_offsets[index].reloc_offset, buffer.len());
732
733 let mut write_reloc = |reloc: &Relocation| {
734 let (r_type, r_pcrel, r_length) = if let RelocationFlags::MachO {
735 r_type,
736 r_pcrel,
737 r_length,
738 } = reloc.flags
739 {
740 (r_type, r_pcrel, r_length)
741 } else {
742 return Err(Error("invalid relocation flags".into()));
743 };
744
745 // Write explicit addend.
746 if reloc.addend != 0 {
747 let r_type = match self.architecture {
748 Architecture::Aarch64 | Architecture::Aarch64_Ilp32 => {
749 macho::ARM64_RELOC_ADDEND
750 }
751 _ => {
752 return Err(Error(format!("unimplemented relocation {:?}", reloc)))
753 }
754 };
755
756 let reloc_info = macho::RelocationInfo {
757 r_address: reloc.offset as u32,
758 r_symbolnum: reloc.addend as u32,
759 r_pcrel: false,
760 r_length,
761 r_extern: false,
762 r_type,
763 };
764 buffer.write(&reloc_info.relocation(endian));
765 }
766
767 let r_extern;
768 let r_symbolnum;
769 let symbol = &self.symbols[reloc.symbol.0];
770 if symbol.kind == SymbolKind::Section {
771 r_symbolnum = section_offsets[symbol.section.id().unwrap().0].index as u32;
772 r_extern = false;
773 } else {
774 r_symbolnum = symbol_offsets[reloc.symbol.0].index as u32;
775 r_extern = true;
776 }
777
778 let reloc_info = macho::RelocationInfo {
779 r_address: reloc.offset as u32,
780 r_symbolnum,
781 r_pcrel,
782 r_length,
783 r_extern,
784 r_type,
785 };
786 buffer.write(&reloc_info.relocation(endian));
787 Ok(())
788 };
789
790 // Relocations are emitted in descending order as otherwise Apple's
791 // new linker crashes. This matches LLVM's behavior too:
792 // https://github.com/llvm/llvm-project/blob/e9b8cd0c8/llvm/lib/MC/MachObjectWriter.cpp#L1001-L1002
793 let need_reverse = |relocs: &[Relocation]| {
794 let Some(first) = relocs.first() else {
795 return false;
796 };
797 let Some(last) = relocs.last() else {
798 return false;
799 };
800 first.offset < last.offset
801 };
802 if need_reverse(&section.relocations) {
803 for reloc in section.relocations.iter().rev() {
804 write_reloc(reloc)?;
805 }
806 } else {
807 for reloc in &section.relocations {
808 write_reloc(reloc)?;
809 }
810 }
811 }
812 }
813
814 // Write symtab.
815 write_align(buffer, pointer_align);
816 debug_assert_eq!(symtab_offset, buffer.len());
817 for index in local_symbols
818 .iter()
819 .copied()
820 .chain(external_symbols.iter().copied())
821 .chain(undefined_symbols.iter().copied())
822 {
823 let symbol = &self.symbols[index];
824 // TODO: N_STAB
825 let (mut n_type, n_sect) = match symbol.section {
826 SymbolSection::Undefined => (macho::N_UNDF | macho::N_EXT, 0),
827 SymbolSection::Absolute => (macho::N_ABS, 0),
828 SymbolSection::Section(id) => (macho::N_SECT, id.0 + 1),
829 SymbolSection::None | SymbolSection::Common => {
830 return Err(Error(format!(
831 "unimplemented symbol `{}` section {:?}",
832 symbol.name().unwrap_or(""),
833 symbol.section
834 )));
835 }
836 };
837 match symbol.scope {
838 SymbolScope::Unknown | SymbolScope::Compilation => {}
839 SymbolScope::Linkage => {
840 n_type |= macho::N_EXT | macho::N_PEXT;
841 }
842 SymbolScope::Dynamic => {
843 n_type |= macho::N_EXT;
844 }
845 }
846
847 let n_desc = if let SymbolFlags::MachO { n_desc } = symbol.flags {
848 n_desc
849 } else {
850 let mut n_desc = 0;
851 if symbol.weak {
852 if symbol.is_undefined() {
853 n_desc |= macho::N_WEAK_REF;
854 } else {
855 n_desc |= macho::N_WEAK_DEF;
856 }
857 }
858 n_desc
859 };
860
861 let n_value = match symbol.section.id() {
862 Some(section) => section_offsets[section.0].address + symbol.value,
863 None => symbol.value,
864 };
865
866 let n_strx = symbol_offsets[index]
867 .str_id
868 .map(|id| strtab.get_offset(id))
869 .unwrap_or(0);
870
871 macho.write_nlist(
872 buffer,
873 Nlist {
874 n_strx: n_strx as u32,
875 n_type,
876 n_sect: n_sect as u8,
877 n_desc,
878 n_value,
879 },
880 );
881 }
882
883 // Write strtab.
884 debug_assert_eq!(strtab_offset, buffer.len());
885 buffer.write_bytes(&strtab_data);
886
887 debug_assert_eq!(offset, buffer.len());
888
889 Ok(())
890 }
891 }
892
893 struct MachHeader {
894 cputype: u32,
895 cpusubtype: u32,
896 filetype: u32,
897 ncmds: u32,
898 sizeofcmds: u32,
899 flags: u32,
900 }
901
902 struct SegmentCommand {
903 cmdsize: u32,
904 segname: [u8; 16],
905 vmaddr: u64,
906 vmsize: u64,
907 fileoff: u64,
908 filesize: u64,
909 maxprot: u32,
910 initprot: u32,
911 nsects: u32,
912 flags: u32,
913 }
914
915 pub struct SectionHeader {
916 sectname: [u8; 16],
917 segname: [u8; 16],
918 addr: u64,
919 size: u64,
920 offset: u32,
921 align: u32,
922 reloff: u32,
923 nreloc: u32,
924 flags: u32,
925 }
926
927 struct Nlist {
928 n_strx: u32,
929 n_type: u8,
930 n_sect: u8,
931 n_desc: u16,
932 n_value: u64,
933 }
934
935 trait MachO {
936 fn mach_header_size(&self) -> usize;
937 fn segment_command_size(&self) -> usize;
938 fn section_header_size(&self) -> usize;
939 fn nlist_size(&self) -> usize;
940 fn write_mach_header(&self, buffer: &mut dyn WritableBuffer, section: MachHeader);
941 fn write_segment_command(&self, buffer: &mut dyn WritableBuffer, segment: SegmentCommand);
942 fn write_section(&self, buffer: &mut dyn WritableBuffer, section: SectionHeader);
943 fn write_nlist(&self, buffer: &mut dyn WritableBuffer, nlist: Nlist);
944 }
945
946 struct MachO32<E> {
947 endian: E,
948 }
949
950 impl<E: Endian> MachO for MachO32<E> {
951 fn mach_header_size(&self) -> usize {
952 mem::size_of::<macho::MachHeader32<E>>()
953 }
954
955 fn segment_command_size(&self) -> usize {
956 mem::size_of::<macho::SegmentCommand32<E>>()
957 }
958
959 fn section_header_size(&self) -> usize {
960 mem::size_of::<macho::Section32<E>>()
961 }
962
963 fn nlist_size(&self) -> usize {
964 mem::size_of::<macho::Nlist32<E>>()
965 }
966
967 fn write_mach_header(&self, buffer: &mut dyn WritableBuffer, header: MachHeader) {
968 let endian = self.endian;
969 let magic = if endian.is_big_endian() {
970 macho::MH_MAGIC
971 } else {
972 macho::MH_CIGAM
973 };
974 let header = macho::MachHeader32 {
975 magic: U32::new(BigEndian, magic),
976 cputype: U32::new(endian, header.cputype),
977 cpusubtype: U32::new(endian, header.cpusubtype),
978 filetype: U32::new(endian, header.filetype),
979 ncmds: U32::new(endian, header.ncmds),
980 sizeofcmds: U32::new(endian, header.sizeofcmds),
981 flags: U32::new(endian, header.flags),
982 };
983 buffer.write(&header);
984 }
985
986 fn write_segment_command(&self, buffer: &mut dyn WritableBuffer, segment: SegmentCommand) {
987 let endian = self.endian;
988 let segment = macho::SegmentCommand32 {
989 cmd: U32::new(endian, macho::LC_SEGMENT),
990 cmdsize: U32::new(endian, segment.cmdsize),
991 segname: segment.segname,
992 vmaddr: U32::new(endian, segment.vmaddr as u32),
993 vmsize: U32::new(endian, segment.vmsize as u32),
994 fileoff: U32::new(endian, segment.fileoff as u32),
995 filesize: U32::new(endian, segment.filesize as u32),
996 maxprot: U32::new(endian, segment.maxprot),
997 initprot: U32::new(endian, segment.initprot),
998 nsects: U32::new(endian, segment.nsects),
999 flags: U32::new(endian, segment.flags),
1000 };
1001 buffer.write(&segment);
1002 }
1003
1004 fn write_section(&self, buffer: &mut dyn WritableBuffer, section: SectionHeader) {
1005 let endian = self.endian;
1006 let section = macho::Section32 {
1007 sectname: section.sectname,
1008 segname: section.segname,
1009 addr: U32::new(endian, section.addr as u32),
1010 size: U32::new(endian, section.size as u32),
1011 offset: U32::new(endian, section.offset),
1012 align: U32::new(endian, section.align),
1013 reloff: U32::new(endian, section.reloff),
1014 nreloc: U32::new(endian, section.nreloc),
1015 flags: U32::new(endian, section.flags),
1016 reserved1: U32::default(),
1017 reserved2: U32::default(),
1018 };
1019 buffer.write(&section);
1020 }
1021
1022 fn write_nlist(&self, buffer: &mut dyn WritableBuffer, nlist: Nlist) {
1023 let endian = self.endian;
1024 let nlist = macho::Nlist32 {
1025 n_strx: U32::new(endian, nlist.n_strx),
1026 n_type: nlist.n_type,
1027 n_sect: nlist.n_sect,
1028 n_desc: U16::new(endian, nlist.n_desc),
1029 n_value: U32::new(endian, nlist.n_value as u32),
1030 };
1031 buffer.write(&nlist);
1032 }
1033 }
1034
1035 struct MachO64<E> {
1036 endian: E,
1037 }
1038
1039 impl<E: Endian> MachO for MachO64<E> {
1040 fn mach_header_size(&self) -> usize {
1041 mem::size_of::<macho::MachHeader64<E>>()
1042 }
1043
1044 fn segment_command_size(&self) -> usize {
1045 mem::size_of::<macho::SegmentCommand64<E>>()
1046 }
1047
1048 fn section_header_size(&self) -> usize {
1049 mem::size_of::<macho::Section64<E>>()
1050 }
1051
1052 fn nlist_size(&self) -> usize {
1053 mem::size_of::<macho::Nlist64<E>>()
1054 }
1055
1056 fn write_mach_header(&self, buffer: &mut dyn WritableBuffer, header: MachHeader) {
1057 let endian = self.endian;
1058 let magic = if endian.is_big_endian() {
1059 macho::MH_MAGIC_64
1060 } else {
1061 macho::MH_CIGAM_64
1062 };
1063 let header = macho::MachHeader64 {
1064 magic: U32::new(BigEndian, magic),
1065 cputype: U32::new(endian, header.cputype),
1066 cpusubtype: U32::new(endian, header.cpusubtype),
1067 filetype: U32::new(endian, header.filetype),
1068 ncmds: U32::new(endian, header.ncmds),
1069 sizeofcmds: U32::new(endian, header.sizeofcmds),
1070 flags: U32::new(endian, header.flags),
1071 reserved: U32::default(),
1072 };
1073 buffer.write(&header);
1074 }
1075
1076 fn write_segment_command(&self, buffer: &mut dyn WritableBuffer, segment: SegmentCommand) {
1077 let endian = self.endian;
1078 let segment = macho::SegmentCommand64 {
1079 cmd: U32::new(endian, macho::LC_SEGMENT_64),
1080 cmdsize: U32::new(endian, segment.cmdsize),
1081 segname: segment.segname,
1082 vmaddr: U64::new(endian, segment.vmaddr),
1083 vmsize: U64::new(endian, segment.vmsize),
1084 fileoff: U64::new(endian, segment.fileoff),
1085 filesize: U64::new(endian, segment.filesize),
1086 maxprot: U32::new(endian, segment.maxprot),
1087 initprot: U32::new(endian, segment.initprot),
1088 nsects: U32::new(endian, segment.nsects),
1089 flags: U32::new(endian, segment.flags),
1090 };
1091 buffer.write(&segment);
1092 }
1093
1094 fn write_section(&self, buffer: &mut dyn WritableBuffer, section: SectionHeader) {
1095 let endian = self.endian;
1096 let section = macho::Section64 {
1097 sectname: section.sectname,
1098 segname: section.segname,
1099 addr: U64::new(endian, section.addr),
1100 size: U64::new(endian, section.size),
1101 offset: U32::new(endian, section.offset),
1102 align: U32::new(endian, section.align),
1103 reloff: U32::new(endian, section.reloff),
1104 nreloc: U32::new(endian, section.nreloc),
1105 flags: U32::new(endian, section.flags),
1106 reserved1: U32::default(),
1107 reserved2: U32::default(),
1108 reserved3: U32::default(),
1109 };
1110 buffer.write(&section);
1111 }
1112
1113 fn write_nlist(&self, buffer: &mut dyn WritableBuffer, nlist: Nlist) {
1114 let endian = self.endian;
1115 let nlist = macho::Nlist64 {
1116 n_strx: U32::new(endian, nlist.n_strx),
1117 n_type: nlist.n_type,
1118 n_sect: nlist.n_sect,
1119 n_desc: U16::new(endian, nlist.n_desc),
1120 n_value: U64Bytes::new(endian, nlist.n_value),
1121 };
1122 buffer.write(&nlist);
1123 }
1124 }