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/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Object/MachOFormat.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
28 using namespace llvm::object;
30 void MachObjectWriter::reset() {
32 IndirectSymBase.clear();
34 LocalSymbolData.clear();
35 ExternalSymbolData.clear();
36 UndefinedSymbolData.clear();
37 MCObjectWriter::reset();
40 bool MachObjectWriter::
41 doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
42 // Undefined symbols are always extern.
43 if (SD->Symbol->isUndefined())
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 (SD->getFlags() & SF_WeakDefinition)
51 // Otherwise, we can use an internal relocation.
55 bool MachObjectWriter::
56 MachSymbolData::operator<(const MachSymbolData &RHS) const {
57 return SymbolData->getSymbol().getName() <
58 RHS.SymbolData->getSymbol().getName();
61 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
62 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
65 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
68 uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
69 const MCAsmLayout &Layout) const {
70 return getSectionAddress(Fragment->getParent()) +
71 Layout.getFragmentOffset(Fragment);
74 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
75 const MCAsmLayout &Layout) const {
76 const MCSymbol &S = SD->getSymbol();
78 // If this is a variable, then recursively evaluate now.
80 if (const MCConstantExpr *C =
81 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
86 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
87 report_fatal_error("unable to evaluate offset for variable '" +
90 // Verify that any used symbols are defined.
91 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
92 report_fatal_error("unable to evaluate offset to undefined symbol '" +
93 Target.getSymA()->getSymbol().getName() + "'");
94 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
95 report_fatal_error("unable to evaluate offset to undefined symbol '" +
96 Target.getSymB()->getSymbol().getName() + "'");
98 uint64_t Address = Target.getConstant();
100 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
101 Target.getSymA()->getSymbol()), Layout);
102 if (Target.getSymB())
103 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
104 Target.getSymB()->getSymbol()), Layout);
108 return getSectionAddress(SD->getFragment()->getParent()) +
109 Layout.getSymbolOffset(SD);
112 uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
113 const MCAsmLayout &Layout) const {
114 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
115 unsigned Next = SD->getLayoutOrder() + 1;
116 if (Next >= Layout.getSectionOrder().size())
119 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
120 if (NextSD.getSection().isVirtualSection())
122 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
125 void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
126 unsigned LoadCommandsSize,
127 bool SubsectionsViaSymbols) {
130 if (SubsectionsViaSymbols)
131 Flags |= macho::HF_SubsectionsViaSymbols;
133 // struct mach_header (28 bytes) or
134 // struct mach_header_64 (32 bytes)
136 uint64_t Start = OS.tell();
139 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
141 Write32(TargetObjectWriter->getCPUType());
142 Write32(TargetObjectWriter->getCPUSubtype());
144 Write32(macho::HFT_Object);
145 Write32(NumLoadCommands);
146 Write32(LoadCommandsSize);
149 Write32(0); // reserved
151 assert(OS.tell() - Start ==
152 (is64Bit() ? macho::Header64Size : macho::Header32Size));
155 /// WriteSegmentLoadCommand - Write a segment load command.
157 /// \param NumSections The number of sections in this segment.
158 /// \param SectionDataSize The total size of the sections.
159 void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
161 uint64_t SectionDataStartOffset,
162 uint64_t SectionDataSize) {
163 // struct segment_command (56 bytes) or
164 // struct segment_command_64 (72 bytes)
166 uint64_t Start = OS.tell();
169 unsigned SegmentLoadCommandSize =
170 is64Bit() ? macho::SegmentLoadCommand64Size:
171 macho::SegmentLoadCommand32Size;
172 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
173 Write32(SegmentLoadCommandSize +
174 NumSections * (is64Bit() ? macho::Section64Size :
175 macho::Section32Size));
179 Write64(0); // vmaddr
180 Write64(VMSize); // vmsize
181 Write64(SectionDataStartOffset); // file offset
182 Write64(SectionDataSize); // file size
184 Write32(0); // vmaddr
185 Write32(VMSize); // vmsize
186 Write32(SectionDataStartOffset); // file offset
187 Write32(SectionDataSize); // file size
189 Write32(0x7); // maxprot
190 Write32(0x7); // initprot
191 Write32(NumSections);
194 assert(OS.tell() - Start == SegmentLoadCommandSize);
197 void MachObjectWriter::WriteSection(const MCAssembler &Asm,
198 const MCAsmLayout &Layout,
199 const MCSectionData &SD,
201 uint64_t RelocationsStart,
202 unsigned NumRelocations) {
203 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
205 // The offset is unused for virtual sections.
206 if (SD.getSection().isVirtualSection()) {
207 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
211 // struct section (68 bytes) or
212 // struct section_64 (80 bytes)
214 uint64_t Start = OS.tell();
217 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
218 WriteBytes(Section.getSectionName(), 16);
219 WriteBytes(Section.getSegmentName(), 16);
221 Write64(getSectionAddress(&SD)); // address
222 Write64(SectionSize); // size
224 Write32(getSectionAddress(&SD)); // address
225 Write32(SectionSize); // size
229 unsigned Flags = Section.getTypeAndAttributes();
230 if (SD.hasInstructions())
231 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
233 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
234 Write32(Log2_32(SD.getAlignment()));
235 Write32(NumRelocations ? RelocationsStart : 0);
236 Write32(NumRelocations);
238 Write32(IndirectSymBase.lookup(&SD)); // reserved1
239 Write32(Section.getStubSize()); // reserved2
241 Write32(0); // reserved3
243 assert(OS.tell() - Start == (is64Bit() ? macho::Section64Size :
244 macho::Section32Size));
247 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
249 uint32_t StringTableOffset,
250 uint32_t StringTableSize) {
251 // struct symtab_command (24 bytes)
253 uint64_t Start = OS.tell();
256 Write32(macho::LCT_Symtab);
257 Write32(macho::SymtabLoadCommandSize);
258 Write32(SymbolOffset);
260 Write32(StringTableOffset);
261 Write32(StringTableSize);
263 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
266 void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
267 uint32_t NumLocalSymbols,
268 uint32_t FirstExternalSymbol,
269 uint32_t NumExternalSymbols,
270 uint32_t FirstUndefinedSymbol,
271 uint32_t NumUndefinedSymbols,
272 uint32_t IndirectSymbolOffset,
273 uint32_t NumIndirectSymbols) {
274 // struct dysymtab_command (80 bytes)
276 uint64_t Start = OS.tell();
279 Write32(macho::LCT_Dysymtab);
280 Write32(macho::DysymtabLoadCommandSize);
281 Write32(FirstLocalSymbol);
282 Write32(NumLocalSymbols);
283 Write32(FirstExternalSymbol);
284 Write32(NumExternalSymbols);
285 Write32(FirstUndefinedSymbol);
286 Write32(NumUndefinedSymbols);
287 Write32(0); // tocoff
289 Write32(0); // modtaboff
290 Write32(0); // nmodtab
291 Write32(0); // extrefsymoff
292 Write32(0); // nextrefsyms
293 Write32(IndirectSymbolOffset);
294 Write32(NumIndirectSymbols);
295 Write32(0); // extreloff
296 Write32(0); // nextrel
297 Write32(0); // locreloff
298 Write32(0); // nlocrel
300 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
303 void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
304 const MCAsmLayout &Layout) {
305 MCSymbolData &Data = *MSD.SymbolData;
306 const MCSymbol &Symbol = Data.getSymbol();
308 uint16_t Flags = Data.getFlags();
309 uint64_t Address = 0;
311 // Set the N_TYPE bits. See <mach-o/nlist.h>.
313 // FIXME: Are the prebound or indirect fields possible here?
314 if (Symbol.isUndefined())
315 Type = macho::STT_Undefined;
316 else if (Symbol.isAbsolute())
317 Type = macho::STT_Absolute;
319 Type = macho::STT_Section;
321 // FIXME: Set STAB bits.
323 if (Data.isPrivateExtern())
324 Type |= macho::STF_PrivateExtern;
327 if (Data.isExternal() || Symbol.isUndefined())
328 Type |= macho::STF_External;
330 // Compute the symbol address.
331 if (Symbol.isDefined()) {
332 Address = getSymbolAddress(&Data, Layout);
333 } else if (Data.isCommon()) {
334 // Common symbols are encoded with the size in the address
335 // field, and their alignment in the flags.
336 Address = Data.getCommonSize();
338 // Common alignment is packed into the 'desc' bits.
339 if (unsigned Align = Data.getCommonAlignment()) {
340 unsigned Log2Size = Log2_32(Align);
341 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
343 report_fatal_error("invalid 'common' alignment '" +
345 // FIXME: Keep this mask with the SymbolFlags enumeration.
346 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
350 // struct nlist (12 bytes)
352 Write32(MSD.StringIndex);
354 Write8(MSD.SectionIndex);
356 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
365 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
368 uint64_t Start = OS.tell();
372 Write32(macho::LinkeditLoadCommandSize);
376 assert(OS.tell() - Start == macho::LinkeditLoadCommandSize);
380 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
381 const MCAsmLayout &Layout,
382 const MCFragment *Fragment,
383 const MCFixup &Fixup,
385 uint64_t &FixedValue) {
386 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
390 void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
391 // This is the point where 'as' creates actual symbols for indirect symbols
392 // (in the following two passes). It would be easier for us to do this sooner
393 // when we see the attribute, but that makes getting the order in the symbol
394 // table much more complicated than it is worth.
396 // FIXME: Revisit this when the dust settles.
398 // Bind non lazy symbol pointers first.
399 unsigned IndirectIndex = 0;
400 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
401 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
402 const MCSectionMachO &Section =
403 cast<MCSectionMachO>(it->SectionData->getSection());
405 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
408 // Initialize the section indirect symbol base, if necessary.
409 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
411 Asm.getOrCreateSymbolData(*it->Symbol);
414 // Then lazy symbol pointers and symbol stubs.
416 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
417 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
418 const MCSectionMachO &Section =
419 cast<MCSectionMachO>(it->SectionData->getSection());
421 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
422 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
425 // Initialize the section indirect symbol base, if necessary.
426 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
428 // Set the symbol type to undefined lazy, but only on construction.
430 // FIXME: Do not hardcode.
432 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
434 Entry.setFlags(Entry.getFlags() | 0x0001);
438 /// ComputeSymbolTable - Compute the symbol table data
440 /// \param StringTable [out] - The string table data.
441 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
443 void MachObjectWriter::
444 ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
445 std::vector<MachSymbolData> &LocalSymbolData,
446 std::vector<MachSymbolData> &ExternalSymbolData,
447 std::vector<MachSymbolData> &UndefinedSymbolData) {
448 // Build section lookup table.
449 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
451 for (MCAssembler::iterator it = Asm.begin(),
452 ie = Asm.end(); it != ie; ++it, ++Index)
453 SectionIndexMap[&it->getSection()] = Index;
454 assert(Index <= 256 && "Too many sections!");
456 // Index 0 is always the empty string.
457 StringMap<uint64_t> StringIndexMap;
458 StringTable += '\x00';
460 // Build the symbol arrays and the string table, but only for non-local
463 // The particular order that we collect the symbols and create the string
464 // table, then sort the symbols is chosen to match 'as'. Even though it
465 // doesn't matter for correctness, this is important for letting us diff .o
467 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
468 ie = Asm.symbol_end(); it != ie; ++it) {
469 const MCSymbol &Symbol = it->getSymbol();
471 // Ignore non-linker visible symbols.
472 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
475 if (!it->isExternal() && !Symbol.isUndefined())
478 uint64_t &Entry = StringIndexMap[Symbol.getName()];
480 Entry = StringTable.size();
481 StringTable += Symbol.getName();
482 StringTable += '\x00';
487 MSD.StringIndex = Entry;
489 if (Symbol.isUndefined()) {
490 MSD.SectionIndex = 0;
491 UndefinedSymbolData.push_back(MSD);
492 } else if (Symbol.isAbsolute()) {
493 MSD.SectionIndex = 0;
494 ExternalSymbolData.push_back(MSD);
496 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
497 assert(MSD.SectionIndex && "Invalid section index!");
498 ExternalSymbolData.push_back(MSD);
502 // Now add the data for local symbols.
503 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
504 ie = Asm.symbol_end(); it != ie; ++it) {
505 const MCSymbol &Symbol = it->getSymbol();
507 // Ignore non-linker visible symbols.
508 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
511 if (it->isExternal() || Symbol.isUndefined())
514 uint64_t &Entry = StringIndexMap[Symbol.getName()];
516 Entry = StringTable.size();
517 StringTable += Symbol.getName();
518 StringTable += '\x00';
523 MSD.StringIndex = Entry;
525 if (Symbol.isAbsolute()) {
526 MSD.SectionIndex = 0;
527 LocalSymbolData.push_back(MSD);
529 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
530 assert(MSD.SectionIndex && "Invalid section index!");
531 LocalSymbolData.push_back(MSD);
535 // External and undefined symbols are required to be in lexicographic order.
536 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
537 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
539 // Set the symbol indices.
541 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
542 LocalSymbolData[i].SymbolData->setIndex(Index++);
543 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
544 ExternalSymbolData[i].SymbolData->setIndex(Index++);
545 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
546 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
548 // The string table is padded to a multiple of 4.
549 while (StringTable.size() % 4)
550 StringTable += '\x00';
553 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
554 const MCAsmLayout &Layout) {
555 uint64_t StartAddress = 0;
556 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
557 for (int i = 0, n = Order.size(); i != n ; ++i) {
558 const MCSectionData *SD = Order[i];
559 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
560 SectionAddress[SD] = StartAddress;
561 StartAddress += Layout.getSectionAddressSize(SD);
563 // Explicitly pad the section to match the alignment requirements of the
564 // following one. This is for 'gas' compatibility, it shouldn't
565 /// strictly be necessary.
566 StartAddress += getPaddingSize(SD, Layout);
570 void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
571 const MCAsmLayout &Layout) {
572 for (MCAssembler::symbol_iterator i = Asm.symbol_begin(),
573 e = Asm.symbol_end();
575 MCSymbolData &SD = *i;
576 if (!SD.getSymbol().isVariable())
579 // Is the variable is a symbol difference (SA - SB + C) expression,
580 // and neither symbol is external, mark the variable as absolute.
581 const MCExpr *Expr = SD.getSymbol().getVariableValue();
583 if (Expr->EvaluateAsRelocatable(Value, Layout)) {
584 if (Value.getSymA() && Value.getSymB())
585 const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
590 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
591 const MCAsmLayout &Layout) {
592 computeSectionAddresses(Asm, Layout);
594 // Create symbol data for any indirect symbols.
595 BindIndirectSymbols(Asm);
597 // Mark symbol difference expressions in variables (from .set or = directives)
599 markAbsoluteVariableSymbols(Asm, Layout);
601 // Compute symbol table information and bind symbol indices.
602 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
603 UndefinedSymbolData);
606 bool MachObjectWriter::
607 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
608 const MCSymbolData &DataA,
609 const MCFragment &FB,
611 bool IsPCRel) const {
615 // The effective address is
616 // addr(atom(A)) + offset(A)
617 // - addr(atom(B)) - offset(B)
618 // and the offsets are not relocatable, so the fixup is fully resolved when
619 // addr(atom(A)) - addr(atom(B)) == 0.
620 const MCSymbolData *A_Base = 0, *B_Base = 0;
622 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
623 const MCSection &SecA = SA.getSection();
624 const MCSection &SecB = FB.getParent()->getSection();
627 // The simple (Darwin, except on x86_64) way of dealing with this was to
628 // assume that any reference to a temporary symbol *must* be a temporary
629 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
630 // relocation to a temporary symbol (in the same section) is fully
631 // resolved. This also works in conjunction with absolutized .set, which
632 // requires the compiler to use .set to absolutize the differences between
633 // symbols which the compiler knows to be assembly time constants, so we
634 // don't need to worry about considering symbol differences fully resolved.
636 // If the file isn't using sub-sections-via-symbols, we can make the
637 // same assumptions about any symbol that we normally make about
640 if (!Asm.getBackend().hasReliableSymbolDifference()) {
641 if (!SA.isInSection() || &SecA != &SecB ||
642 (!SA.isTemporary() &&
643 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
644 Asm.getSubsectionsViaSymbols()))
648 // For Darwin x86_64, there is one special case when the reference IsPCRel.
649 // If the fragment with the reference does not have a base symbol but meets
650 // the simple way of dealing with this, in that it is a temporary symbol in
651 // the same atom then it is assumed to be fully resolved. This is needed so
652 // a relocation entry is not created and so the static linker does not
653 // mess up the reference later.
654 else if(!FB.getAtom() &&
655 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
659 if (!TargetObjectWriter->useAggressiveSymbolFolding())
663 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
665 // Bail if the symbol has no fragment.
669 A_Base = FA->getAtom();
673 B_Base = FB.getAtom();
677 // If the atoms are the same, they are guaranteed to have the same address.
678 if (A_Base == B_Base)
681 // Otherwise, we can't prove this is fully resolved.
685 void MachObjectWriter::WriteObject(MCAssembler &Asm,
686 const MCAsmLayout &Layout) {
687 unsigned NumSections = Asm.size();
689 // The section data starts after the header, the segment load command (and
690 // section headers) and the symbol table.
691 unsigned NumLoadCommands = 1;
692 uint64_t LoadCommandsSize = is64Bit() ?
693 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
694 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
696 // Add the symbol table load command sizes, if used.
697 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
698 UndefinedSymbolData.size();
700 NumLoadCommands += 2;
701 LoadCommandsSize += (macho::SymtabLoadCommandSize +
702 macho::DysymtabLoadCommandSize);
705 // Add the data-in-code load command size, if used.
706 unsigned NumDataRegions = Asm.getDataRegions().size();
707 if (NumDataRegions) {
709 LoadCommandsSize += macho::LinkeditLoadCommandSize;
712 // Compute the total size of the section data, as well as its file size and vm
714 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
715 macho::Header32Size) + LoadCommandsSize;
716 uint64_t SectionDataSize = 0;
717 uint64_t SectionDataFileSize = 0;
719 for (MCAssembler::const_iterator it = Asm.begin(),
720 ie = Asm.end(); it != ie; ++it) {
721 const MCSectionData &SD = *it;
722 uint64_t Address = getSectionAddress(&SD);
723 uint64_t Size = Layout.getSectionAddressSize(&SD);
724 uint64_t FileSize = Layout.getSectionFileSize(&SD);
725 FileSize += getPaddingSize(&SD, Layout);
727 VMSize = std::max(VMSize, Address + Size);
729 if (SD.getSection().isVirtualSection())
732 SectionDataSize = std::max(SectionDataSize, Address + Size);
733 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
736 // The section data is padded to 4 bytes.
738 // FIXME: Is this machine dependent?
739 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
740 SectionDataFileSize += SectionDataPadding;
742 // Write the prolog, starting with the header and load command...
743 WriteHeader(NumLoadCommands, LoadCommandsSize,
744 Asm.getSubsectionsViaSymbols());
745 WriteSegmentLoadCommand(NumSections, VMSize,
746 SectionDataStart, SectionDataSize);
748 // ... and then the section headers.
749 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
750 for (MCAssembler::const_iterator it = Asm.begin(),
751 ie = Asm.end(); it != ie; ++it) {
752 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
753 unsigned NumRelocs = Relocs.size();
754 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
755 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
756 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
759 // Write the data-in-code load command, if used.
760 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
761 if (NumDataRegions) {
762 uint64_t DataRegionsOffset = RelocTableEnd;
763 uint64_t DataRegionsSize = NumDataRegions * 8;
764 WriteLinkeditLoadCommand(macho::LCT_DataInCode, DataRegionsOffset,
768 // Write the symbol table load command, if used.
770 unsigned FirstLocalSymbol = 0;
771 unsigned NumLocalSymbols = LocalSymbolData.size();
772 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
773 unsigned NumExternalSymbols = ExternalSymbolData.size();
774 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
775 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
776 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
777 unsigned NumSymTabSymbols =
778 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
779 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
780 uint64_t IndirectSymbolOffset = 0;
782 // If used, the indirect symbols are written after the section data.
783 if (NumIndirectSymbols)
784 IndirectSymbolOffset = DataInCodeTableEnd;
786 // The symbol table is written after the indirect symbol data.
787 uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
789 // The string table is written after symbol table.
790 uint64_t StringTableOffset =
791 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
793 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
794 StringTableOffset, StringTable.size());
796 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
797 FirstExternalSymbol, NumExternalSymbols,
798 FirstUndefinedSymbol, NumUndefinedSymbols,
799 IndirectSymbolOffset, NumIndirectSymbols);
802 // Write the actual section data.
803 for (MCAssembler::const_iterator it = Asm.begin(),
804 ie = Asm.end(); it != ie; ++it) {
805 Asm.writeSectionData(it, Layout);
807 uint64_t Pad = getPaddingSize(it, Layout);
808 for (unsigned int i = 0; i < Pad; ++i)
812 // Write the extra padding.
813 WriteZeros(SectionDataPadding);
815 // Write the relocation entries.
816 for (MCAssembler::const_iterator it = Asm.begin(),
817 ie = Asm.end(); it != ie; ++it) {
818 // Write the section relocation entries, in reverse order to match 'as'
819 // (approximately, the exact algorithm is more complicated than this).
820 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
821 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
822 Write32(Relocs[e - i - 1].Word0);
823 Write32(Relocs[e - i - 1].Word1);
827 // Write out the data-in-code region payload, if there is one.
828 for (MCAssembler::const_data_region_iterator
829 it = Asm.data_region_begin(), ie = Asm.data_region_end();
831 const DataRegionData *Data = &(*it);
833 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
836 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
838 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
839 << " start: " << Start << "(" << Data->Start->getName() << ")"
840 << " end: " << End << "(" << Data->End->getName() << ")"
841 << " size: " << End - Start
844 Write16(End - Start);
848 // Write the symbol table data, if used.
850 // Write the indirect symbol entries.
851 for (MCAssembler::const_indirect_symbol_iterator
852 it = Asm.indirect_symbol_begin(),
853 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
854 // Indirect symbols in the non lazy symbol pointer section have some
856 const MCSectionMachO &Section =
857 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
858 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
859 // If this symbol is defined and internal, mark it as such.
860 if (it->Symbol->isDefined() &&
861 !Asm.getSymbolData(*it->Symbol).isExternal()) {
862 uint32_t Flags = macho::ISF_Local;
863 if (it->Symbol->isAbsolute())
864 Flags |= macho::ISF_Absolute;
870 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
873 // FIXME: Check that offsets match computed ones.
875 // Write the symbol table entries.
876 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
877 WriteNlist(LocalSymbolData[i], Layout);
878 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
879 WriteNlist(ExternalSymbolData[i], Layout);
880 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
881 WriteNlist(UndefinedSymbolData[i], Layout);
883 // Write the string table.
884 OS << StringTable.str();
888 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
890 bool IsLittleEndian) {
891 return new MachObjectWriter(MOTW, OS, IsLittleEndian);