1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCMachObjectWriter.h"
11 #include "llvm/ADT/StringMap.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCFixupKindInfo.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCSymbolMachO.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MachO.h"
25 #include "llvm/Support/raw_ostream.h"
29 #define DEBUG_TYPE "mc"
31 void MachObjectWriter::reset() {
33 IndirectSymBase.clear();
35 LocalSymbolData.clear();
36 ExternalSymbolData.clear();
37 UndefinedSymbolData.clear();
38 MCObjectWriter::reset();
41 bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
42 // Undefined symbols are always extern.
46 // References to weak definitions require external relocation entries; the
47 // definition may not always be the one in the same object file.
48 if (cast<MCSymbolMachO>(S).isWeakDefinition())
51 // Otherwise, we can use an internal relocation.
55 bool MachObjectWriter::
56 MachSymbolData::operator<(const MachSymbolData &RHS) const {
57 return Symbol->getName() < RHS.Symbol->getName();
60 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
61 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
64 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
67 uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
68 const MCAsmLayout &Layout) const {
69 return getSectionAddress(Fragment->getParent()) +
70 Layout.getFragmentOffset(Fragment);
73 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
74 const MCAsmLayout &Layout) const {
75 // If this is a variable, then recursively evaluate now.
77 if (const MCConstantExpr *C =
78 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
83 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
84 report_fatal_error("unable to evaluate offset for variable '" +
87 // Verify that any used symbols are defined.
88 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
89 report_fatal_error("unable to evaluate offset to undefined symbol '" +
90 Target.getSymA()->getSymbol().getName() + "'");
91 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
92 report_fatal_error("unable to evaluate offset to undefined symbol '" +
93 Target.getSymB()->getSymbol().getName() + "'");
95 uint64_t Address = Target.getConstant();
97 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
99 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
103 return getSectionAddress(S.getFragment()->getParent()) +
104 Layout.getSymbolOffset(S);
107 uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
108 const MCAsmLayout &Layout) const {
109 uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
110 unsigned Next = Sec->getLayoutOrder() + 1;
111 if (Next >= Layout.getSectionOrder().size())
114 const MCSection &NextSec = *Layout.getSectionOrder()[Next];
115 if (NextSec.isVirtualSection())
117 return OffsetToAlignment(EndAddr, NextSec.getAlignment());
120 void MachObjectWriter::writeHeader(MachO::HeaderFileType Type,
121 unsigned NumLoadCommands,
122 unsigned LoadCommandsSize,
123 bool SubsectionsViaSymbols) {
126 if (SubsectionsViaSymbols)
127 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
129 // struct mach_header (28 bytes) or
130 // struct mach_header_64 (32 bytes)
132 uint64_t Start = getStream().tell();
135 write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
137 write32(TargetObjectWriter->getCPUType());
138 write32(TargetObjectWriter->getCPUSubtype());
141 write32(NumLoadCommands);
142 write32(LoadCommandsSize);
145 write32(0); // reserved
148 getStream().tell() - Start ==
149 (is64Bit() ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header)));
152 /// writeSegmentLoadCommand - Write a segment load command.
154 /// \param NumSections The number of sections in this segment.
155 /// \param SectionDataSize The total size of the sections.
156 void MachObjectWriter::writeSegmentLoadCommand(
157 StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
158 uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
160 // struct segment_command (56 bytes) or
161 // struct segment_command_64 (72 bytes)
163 uint64_t Start = getStream().tell();
166 unsigned SegmentLoadCommandSize =
167 is64Bit() ? sizeof(MachO::segment_command_64):
168 sizeof(MachO::segment_command);
169 write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
170 write32(SegmentLoadCommandSize +
171 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
172 sizeof(MachO::section)));
174 assert(Name.size() <= 16);
175 writeBytes(Name, 16);
177 write64(VMAddr); // vmaddr
178 write64(VMSize); // vmsize
179 write64(SectionDataStartOffset); // file offset
180 write64(SectionDataSize); // file size
182 write32(VMAddr); // vmaddr
183 write32(VMSize); // vmsize
184 write32(SectionDataStartOffset); // file offset
185 write32(SectionDataSize); // file size
191 write32(NumSections);
194 assert(getStream().tell() - Start == SegmentLoadCommandSize);
197 void MachObjectWriter::writeSection(const MCAsmLayout &Layout,
198 const MCSection &Sec, uint64_t VMAddr,
199 uint64_t FileOffset, unsigned Flags,
200 uint64_t RelocationsStart,
201 unsigned NumRelocations) {
202 uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
203 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
205 // The offset is unused for virtual sections.
206 if (Section.isVirtualSection()) {
207 assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
211 // struct section (68 bytes) or
212 // struct section_64 (80 bytes)
214 uint64_t Start = getStream().tell();
217 writeBytes(Section.getSectionName(), 16);
218 writeBytes(Section.getSegmentName(), 16);
220 write64(VMAddr); // address
221 write64(SectionSize); // size
223 write32(VMAddr); // address
224 write32(SectionSize); // size
228 assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
229 write32(Log2_32(Section.getAlignment()));
230 write32(NumRelocations ? RelocationsStart : 0);
231 write32(NumRelocations);
233 write32(IndirectSymBase.lookup(&Sec)); // reserved1
234 write32(Section.getStubSize()); // reserved2
236 write32(0); // reserved3
238 assert(getStream().tell() - Start ==
239 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
242 void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
244 uint32_t StringTableOffset,
245 uint32_t StringTableSize) {
246 // struct symtab_command (24 bytes)
248 uint64_t Start = getStream().tell();
251 write32(MachO::LC_SYMTAB);
252 write32(sizeof(MachO::symtab_command));
253 write32(SymbolOffset);
255 write32(StringTableOffset);
256 write32(StringTableSize);
258 assert(getStream().tell() - Start == sizeof(MachO::symtab_command));
261 void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
262 uint32_t NumLocalSymbols,
263 uint32_t FirstExternalSymbol,
264 uint32_t NumExternalSymbols,
265 uint32_t FirstUndefinedSymbol,
266 uint32_t NumUndefinedSymbols,
267 uint32_t IndirectSymbolOffset,
268 uint32_t NumIndirectSymbols) {
269 // struct dysymtab_command (80 bytes)
271 uint64_t Start = getStream().tell();
274 write32(MachO::LC_DYSYMTAB);
275 write32(sizeof(MachO::dysymtab_command));
276 write32(FirstLocalSymbol);
277 write32(NumLocalSymbols);
278 write32(FirstExternalSymbol);
279 write32(NumExternalSymbols);
280 write32(FirstUndefinedSymbol);
281 write32(NumUndefinedSymbols);
282 write32(0); // tocoff
284 write32(0); // modtaboff
285 write32(0); // nmodtab
286 write32(0); // extrefsymoff
287 write32(0); // nextrefsyms
288 write32(IndirectSymbolOffset);
289 write32(NumIndirectSymbols);
290 write32(0); // extreloff
291 write32(0); // nextrel
292 write32(0); // locreloff
293 write32(0); // nlocrel
295 assert(getStream().tell() - Start == sizeof(MachO::dysymtab_command));
298 MachObjectWriter::MachSymbolData *
299 MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
300 for (auto *SymbolData :
301 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
302 for (MachSymbolData &Entry : *SymbolData)
303 if (Entry.Symbol == &Sym)
309 const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
310 const MCSymbol *S = &Sym;
311 while (S->isVariable()) {
312 const MCExpr *Value = S->getVariableValue();
313 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
316 S = &Ref->getSymbol();
321 void MachObjectWriter::writeNlist(MachSymbolData &MSD,
322 const MCAsmLayout &Layout) {
323 const MCSymbol *Symbol = MSD.Symbol;
324 const MCSymbol &Data = *Symbol;
325 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
326 uint8_t SectionIndex = MSD.SectionIndex;
328 uint64_t Address = 0;
329 bool IsAlias = Symbol != AliasedSymbol;
331 const MCSymbol &OrigSymbol = *Symbol;
332 MachSymbolData *AliaseeInfo;
334 AliaseeInfo = findSymbolData(*AliasedSymbol);
336 SectionIndex = AliaseeInfo->SectionIndex;
337 Symbol = AliasedSymbol;
338 // FIXME: Should this update Data as well? Do we need OrigSymbol at all?
341 // Set the N_TYPE bits. See <mach-o/nlist.h>.
343 // FIXME: Are the prebound or indirect fields possible here?
344 if (IsAlias && Symbol->isUndefined())
345 Type = MachO::N_INDR;
346 else if (Symbol->isUndefined())
347 Type = MachO::N_UNDF;
348 else if (Symbol->isAbsolute())
351 Type = MachO::N_SECT;
353 // FIXME: Set STAB bits.
355 if (Data.isPrivateExtern())
356 Type |= MachO::N_PEXT;
359 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
360 Type |= MachO::N_EXT;
362 // Compute the symbol address.
363 if (IsAlias && Symbol->isUndefined())
364 Address = AliaseeInfo->StringIndex;
365 else if (Symbol->isDefined())
366 Address = getSymbolAddress(OrigSymbol, Layout);
367 else if (Symbol->isCommon()) {
368 // Common symbols are encoded with the size in the address
369 // field, and their alignment in the flags.
370 Address = Symbol->getCommonSize();
373 // struct nlist (12 bytes)
375 write32(MSD.StringIndex);
377 write8(SectionIndex);
379 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
381 write16(cast<MCSymbolMachO>(Symbol)->getEncodedFlags());
388 void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
391 uint64_t Start = getStream().tell();
395 write32(sizeof(MachO::linkedit_data_command));
399 assert(getStream().tell() - Start == sizeof(MachO::linkedit_data_command));
402 static unsigned ComputeLinkerOptionsLoadCommandSize(
403 const std::vector<std::string> &Options, bool is64Bit)
405 unsigned Size = sizeof(MachO::linker_option_command);
406 for (const std::string &Option : Options)
407 Size += Option.size() + 1;
408 return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
411 void MachObjectWriter::writeLinkerOptionsLoadCommand(
412 const std::vector<std::string> &Options)
414 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
415 uint64_t Start = getStream().tell();
418 write32(MachO::LC_LINKER_OPTION);
420 write32(Options.size());
421 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
422 for (const std::string &Option : Options) {
423 // Write each string, including the null byte.
424 writeBytes(Option.c_str(), Option.size() + 1);
425 BytesWritten += Option.size() + 1;
428 // Pad to a multiple of the pointer size.
429 writeBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
431 assert(getStream().tell() - Start == Size);
434 void MachObjectWriter::recordRelocation(MCAssembler &Asm,
435 const MCAsmLayout &Layout,
436 const MCFragment *Fragment,
437 const MCFixup &Fixup, MCValue Target,
438 bool &IsPCRel, uint64_t &FixedValue) {
439 TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
443 void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
444 // This is the point where 'as' creates actual symbols for indirect symbols
445 // (in the following two passes). It would be easier for us to do this sooner
446 // when we see the attribute, but that makes getting the order in the symbol
447 // table much more complicated than it is worth.
449 // FIXME: Revisit this when the dust settles.
451 // Report errors for use of .indirect_symbol not in a symbol pointer section
453 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
454 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
455 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
457 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
458 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
459 Section.getType() != MachO::S_SYMBOL_STUBS) {
460 MCSymbol &Symbol = *it->Symbol;
461 report_fatal_error("indirect symbol '" + Symbol.getName() +
462 "' not in a symbol pointer or stub section");
466 // Bind non-lazy symbol pointers first.
467 unsigned IndirectIndex = 0;
468 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
469 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
470 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
472 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS)
475 // Initialize the section indirect symbol base, if necessary.
476 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
478 Asm.registerSymbol(*it->Symbol);
481 // Then lazy symbol pointers and symbol stubs.
483 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
484 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
485 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
487 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
488 Section.getType() != MachO::S_SYMBOL_STUBS)
491 // Initialize the section indirect symbol base, if necessary.
492 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
494 // Set the symbol type to undefined lazy, but only on construction.
496 // FIXME: Do not hardcode.
498 Asm.registerSymbol(*it->Symbol, &Created);
500 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
504 /// computeSymbolTable - Compute the symbol table data
505 void MachObjectWriter::computeSymbolTable(
506 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
507 std::vector<MachSymbolData> &ExternalSymbolData,
508 std::vector<MachSymbolData> &UndefinedSymbolData) {
509 // Build section lookup table.
510 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
512 for (MCAssembler::iterator it = Asm.begin(),
513 ie = Asm.end(); it != ie; ++it, ++Index)
514 SectionIndexMap[&*it] = Index;
515 assert(Index <= 256 && "Too many sections!");
517 // Build the string table.
518 for (const MCSymbol &Symbol : Asm.symbols()) {
519 if (!Asm.isSymbolLinkerVisible(Symbol))
522 StringTable.add(Symbol.getName());
524 StringTable.finalize(StringTableBuilder::MachO);
526 // Build the symbol arrays but only for non-local symbols.
528 // The particular order that we collect and then sort the symbols is chosen to
529 // match 'as'. Even though it doesn't matter for correctness, this is
530 // important for letting us diff .o files.
531 for (const MCSymbol &Symbol : Asm.symbols()) {
532 // Ignore non-linker visible symbols.
533 if (!Asm.isSymbolLinkerVisible(Symbol))
536 if (!Symbol.isExternal() && !Symbol.isUndefined())
540 MSD.Symbol = &Symbol;
541 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
543 if (Symbol.isUndefined()) {
544 MSD.SectionIndex = 0;
545 UndefinedSymbolData.push_back(MSD);
546 } else if (Symbol.isAbsolute()) {
547 MSD.SectionIndex = 0;
548 ExternalSymbolData.push_back(MSD);
550 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
551 assert(MSD.SectionIndex && "Invalid section index!");
552 ExternalSymbolData.push_back(MSD);
556 // Now add the data for local symbols.
557 for (const MCSymbol &Symbol : Asm.symbols()) {
558 // Ignore non-linker visible symbols.
559 if (!Asm.isSymbolLinkerVisible(Symbol))
562 if (Symbol.isExternal() || Symbol.isUndefined())
566 MSD.Symbol = &Symbol;
567 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
569 if (Symbol.isAbsolute()) {
570 MSD.SectionIndex = 0;
571 LocalSymbolData.push_back(MSD);
573 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
574 assert(MSD.SectionIndex && "Invalid section index!");
575 LocalSymbolData.push_back(MSD);
579 // External and undefined symbols are required to be in lexicographic order.
580 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
581 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
583 // Set the symbol indices.
585 for (auto *SymbolData :
586 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
587 for (MachSymbolData &Entry : *SymbolData)
588 Entry.Symbol->setIndex(Index++);
590 for (const MCSection &Section : Asm) {
591 for (RelAndSymbol &Rel : Relocations[&Section]) {
595 // Set the Index and the IsExtern bit.
596 unsigned Index = Rel.Sym->getIndex();
597 assert(isInt<24>(Index));
599 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
601 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
606 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
607 const MCAsmLayout &Layout) {
608 uint64_t StartAddress = 0;
609 for (const MCSection *Sec : Layout.getSectionOrder()) {
610 StartAddress = RoundUpToAlignment(StartAddress, Sec->getAlignment());
611 SectionAddress[Sec] = StartAddress;
612 StartAddress += Layout.getSectionAddressSize(Sec);
614 // Explicitly pad the section to match the alignment requirements of the
615 // following one. This is for 'gas' compatibility, it shouldn't
616 /// strictly be necessary.
617 StartAddress += getPaddingSize(Sec, Layout);
621 void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
622 const MCAsmLayout &Layout) {
623 computeSectionAddresses(Asm, Layout);
625 // Create symbol data for any indirect symbols.
626 bindIndirectSymbols(Asm);
629 bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
630 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
631 bool InSet, bool IsPCRel) const {
635 // The effective address is
636 // addr(atom(A)) + offset(A)
637 // - addr(atom(B)) - offset(B)
638 // and the offsets are not relocatable, so the fixup is fully resolved when
639 // addr(atom(A)) - addr(atom(B)) == 0.
640 const MCSymbol &SA = findAliasedSymbol(SymA);
641 const MCSection &SecA = SA.getSection();
642 const MCSection &SecB = *FB.getParent();
645 // The simple (Darwin, except on x86_64) way of dealing with this was to
646 // assume that any reference to a temporary symbol *must* be a temporary
647 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
648 // relocation to a temporary symbol (in the same section) is fully
649 // resolved. This also works in conjunction with absolutized .set, which
650 // requires the compiler to use .set to absolutize the differences between
651 // symbols which the compiler knows to be assembly time constants, so we
652 // don't need to worry about considering symbol differences fully resolved.
654 // If the file isn't using sub-sections-via-symbols, we can make the
655 // same assumptions about any symbol that we normally make about
658 bool hasReliableSymbolDifference = isX86_64();
659 if (!hasReliableSymbolDifference) {
660 if (!SA.isInSection() || &SecA != &SecB ||
661 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
662 Asm.getSubsectionsViaSymbols()))
666 // For Darwin x86_64, there is one special case when the reference IsPCRel.
667 // If the fragment with the reference does not have a base symbol but meets
668 // the simple way of dealing with this, in that it is a temporary symbol in
669 // the same atom then it is assumed to be fully resolved. This is needed so
670 // a relocation entry is not created and so the static linker does not
671 // mess up the reference later.
672 else if(!FB.getAtom() &&
673 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
678 // If they are not in the same section, we can't compute the diff.
682 const MCFragment *FA = SA.getFragment();
684 // Bail if the symbol has no fragment.
688 // If the atoms are the same, they are guaranteed to have the same address.
689 if (FA->getAtom() == FB.getAtom())
692 // Otherwise, we can't prove this is fully resolved.
696 void MachObjectWriter::writeObject(MCAssembler &Asm,
697 const MCAsmLayout &Layout) {
698 // Compute symbol table information and bind symbol indices.
699 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
700 UndefinedSymbolData);
702 unsigned NumSections = Asm.size();
703 const MCAssembler::VersionMinInfoType &VersionInfo =
704 Layout.getAssembler().getVersionMinInfo();
706 // The section data starts after the header, the segment load command (and
707 // section headers) and the symbol table.
708 unsigned NumLoadCommands = 1;
709 uint64_t LoadCommandsSize = is64Bit() ?
710 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
711 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
713 // Add the deployment target version info load command size, if used.
714 if (VersionInfo.Major != 0) {
716 LoadCommandsSize += sizeof(MachO::version_min_command);
719 // Add the data-in-code load command size, if used.
720 unsigned NumDataRegions = Asm.getDataRegions().size();
721 if (NumDataRegions) {
723 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
726 // Add the loh load command size, if used.
727 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
728 uint64_t LOHSize = RoundUpToAlignment(LOHRawSize, is64Bit() ? 8 : 4);
731 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
734 // Add the symbol table load command sizes, if used.
735 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
736 UndefinedSymbolData.size();
738 NumLoadCommands += 2;
739 LoadCommandsSize += (sizeof(MachO::symtab_command) +
740 sizeof(MachO::dysymtab_command));
743 // Add the linker option load commands sizes.
744 for (const auto &Option : Asm.getLinkerOptions()) {
746 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
749 // Compute the total size of the section data, as well as its file size and vm
751 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
752 sizeof(MachO::mach_header)) + LoadCommandsSize;
753 uint64_t SectionDataSize = 0;
754 uint64_t SectionDataFileSize = 0;
756 for (const MCSection &Sec : Asm) {
757 uint64_t Address = getSectionAddress(&Sec);
758 uint64_t Size = Layout.getSectionAddressSize(&Sec);
759 uint64_t FileSize = Layout.getSectionFileSize(&Sec);
760 FileSize += getPaddingSize(&Sec, Layout);
762 VMSize = std::max(VMSize, Address + Size);
764 if (Sec.isVirtualSection())
767 SectionDataSize = std::max(SectionDataSize, Address + Size);
768 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
771 // The section data is padded to 4 bytes.
773 // FIXME: Is this machine dependent?
774 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
775 SectionDataFileSize += SectionDataPadding;
777 // Write the prolog, starting with the header and load command...
778 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
779 Asm.getSubsectionsViaSymbols());
781 MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
782 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
783 SectionDataSize, Prot, Prot);
785 // ... and then the section headers.
786 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
787 for (const MCSection &Section : Asm) {
788 const auto &Sec = cast<MCSectionMachO>(Section);
789 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
790 unsigned NumRelocs = Relocs.size();
791 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
792 unsigned Flags = Sec.getTypeAndAttributes();
793 if (Sec.hasInstructions())
794 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
795 writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
796 RelocTableEnd, NumRelocs);
797 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
800 // Write out the deployment target information, if it's available.
801 if (VersionInfo.Major != 0) {
802 assert(VersionInfo.Update < 256 && "unencodable update target version");
803 assert(VersionInfo.Minor < 256 && "unencodable minor target version");
804 assert(VersionInfo.Major < 65536 && "unencodable major target version");
805 uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
806 (VersionInfo.Major << 16);
807 write32(VersionInfo.Kind == MCVM_OSXVersionMin ? MachO::LC_VERSION_MIN_MACOSX :
808 MachO::LC_VERSION_MIN_IPHONEOS);
809 write32(sizeof(MachO::version_min_command));
810 write32(EncodedVersion);
811 write32(0); // reserved.
814 // Write the data-in-code load command, if used.
815 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
816 if (NumDataRegions) {
817 uint64_t DataRegionsOffset = RelocTableEnd;
818 uint64_t DataRegionsSize = NumDataRegions * 8;
819 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
823 // Write the loh load command, if used.
824 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
826 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
827 DataInCodeTableEnd, LOHSize);
829 // Write the symbol table load command, if used.
831 unsigned FirstLocalSymbol = 0;
832 unsigned NumLocalSymbols = LocalSymbolData.size();
833 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
834 unsigned NumExternalSymbols = ExternalSymbolData.size();
835 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
836 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
837 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
838 unsigned NumSymTabSymbols =
839 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
840 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
841 uint64_t IndirectSymbolOffset = 0;
843 // If used, the indirect symbols are written after the section data.
844 if (NumIndirectSymbols)
845 IndirectSymbolOffset = LOHTableEnd;
847 // The symbol table is written after the indirect symbol data.
848 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
850 // The string table is written after symbol table.
851 uint64_t StringTableOffset =
852 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
853 sizeof(MachO::nlist_64) :
854 sizeof(MachO::nlist));
855 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
856 StringTableOffset, StringTable.data().size());
858 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
859 FirstExternalSymbol, NumExternalSymbols,
860 FirstUndefinedSymbol, NumUndefinedSymbols,
861 IndirectSymbolOffset, NumIndirectSymbols);
864 // Write the linker options load commands.
865 for (const auto &Option : Asm.getLinkerOptions())
866 writeLinkerOptionsLoadCommand(Option);
868 // Write the actual section data.
869 for (const MCSection &Sec : Asm) {
870 Asm.writeSectionData(&Sec, Layout);
872 uint64_t Pad = getPaddingSize(&Sec, Layout);
876 // Write the extra padding.
877 WriteZeros(SectionDataPadding);
879 // Write the relocation entries.
880 for (const MCSection &Sec : Asm) {
881 // Write the section relocation entries, in reverse order to match 'as'
882 // (approximately, the exact algorithm is more complicated than this).
883 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
884 for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
885 write32(Rel.MRE.r_word0);
886 write32(Rel.MRE.r_word1);
890 // Write out the data-in-code region payload, if there is one.
891 for (MCAssembler::const_data_region_iterator
892 it = Asm.data_region_begin(), ie = Asm.data_region_end();
894 const DataRegionData *Data = &(*it);
895 uint64_t Start = getSymbolAddress(*Data->Start, Layout);
896 uint64_t End = getSymbolAddress(*Data->End, Layout);
897 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
898 << " start: " << Start << "(" << Data->Start->getName() << ")"
899 << " end: " << End << "(" << Data->End->getName() << ")"
900 << " size: " << End - Start
903 write16(End - Start);
907 // Write out the loh commands, if there is one.
910 unsigned Start = getStream().tell();
912 Asm.getLOHContainer().emit(*this, Layout);
913 // Pad to a multiple of the pointer size.
914 writeBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
915 assert(getStream().tell() - Start == LOHSize);
918 // Write the symbol table data, if used.
920 // Write the indirect symbol entries.
921 for (MCAssembler::const_indirect_symbol_iterator
922 it = Asm.indirect_symbol_begin(),
923 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
924 // Indirect symbols in the non-lazy symbol pointer section have some
926 const MCSectionMachO &Section =
927 static_cast<const MCSectionMachO &>(*it->Section);
928 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
929 // If this symbol is defined and internal, mark it as such.
930 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
931 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
932 if (it->Symbol->isAbsolute())
933 Flags |= MachO::INDIRECT_SYMBOL_ABS;
939 write32(it->Symbol->getIndex());
942 // FIXME: Check that offsets match computed ones.
944 // Write the symbol table entries.
945 for (auto *SymbolData :
946 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
947 for (MachSymbolData &Entry : *SymbolData)
948 writeNlist(Entry, Layout);
950 // Write the string table.
951 getStream() << StringTable.data();
955 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
956 raw_pwrite_stream &OS,
957 bool IsLittleEndian) {
958 return new MachObjectWriter(MOTW, OS, IsLittleEndian);