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/MCAssembler.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmLayout.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/MCSymbol.h"
21 #include "llvm/MC/MCMachOSymbolFlags.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"
29 using namespace llvm::object;
31 bool MachObjectWriter::
32 doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
33 // Undefined symbols are always extern.
34 if (SD->Symbol->isUndefined())
37 // References to weak definitions require external relocation entries; the
38 // definition may not always be the one in the same object file.
39 if (SD->getFlags() & SF_WeakDefinition)
42 // Otherwise, we can use an internal relocation.
46 bool MachObjectWriter::
47 MachSymbolData::operator<(const MachSymbolData &RHS) const {
48 return SymbolData->getSymbol().getName() <
49 RHS.SymbolData->getSymbol().getName();
52 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
53 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
56 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
59 uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
60 const MCAsmLayout &Layout) const {
61 return getSectionAddress(Fragment->getParent()) +
62 Layout.getFragmentOffset(Fragment);
65 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
66 const MCAsmLayout &Layout) const {
67 const MCSymbol &S = SD->getSymbol();
69 // If this is a variable, then recursively evaluate now.
72 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
73 report_fatal_error("unable to evaluate offset for variable '" +
76 // Verify that any used symbols are defined.
77 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
78 report_fatal_error("unable to evaluate offset to undefined symbol '" +
79 Target.getSymA()->getSymbol().getName() + "'");
80 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
81 report_fatal_error("unable to evaluate offset to undefined symbol '" +
82 Target.getSymB()->getSymbol().getName() + "'");
84 uint64_t Address = Target.getConstant();
86 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
87 Target.getSymA()->getSymbol()), Layout);
89 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
90 Target.getSymB()->getSymbol()), Layout);
94 return getSectionAddress(SD->getFragment()->getParent()) +
95 Layout.getSymbolOffset(SD);
98 uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
99 const MCAsmLayout &Layout) const {
100 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
101 unsigned Next = SD->getLayoutOrder() + 1;
102 if (Next >= Layout.getSectionOrder().size())
105 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
106 if (NextSD.getSection().isVirtualSection())
108 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
111 void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
112 unsigned LoadCommandsSize,
113 bool SubsectionsViaSymbols) {
116 if (SubsectionsViaSymbols)
117 Flags |= macho::HF_SubsectionsViaSymbols;
119 // struct mach_header (28 bytes) or
120 // struct mach_header_64 (32 bytes)
122 uint64_t Start = OS.tell();
125 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
127 Write32(TargetObjectWriter->getCPUType());
128 Write32(TargetObjectWriter->getCPUSubtype());
130 Write32(macho::HFT_Object);
131 Write32(NumLoadCommands);
132 Write32(LoadCommandsSize);
135 Write32(0); // reserved
137 assert(OS.tell() - Start ==
138 (is64Bit() ? macho::Header64Size : macho::Header32Size));
141 /// WriteSegmentLoadCommand - Write a segment load command.
143 /// \arg NumSections - The number of sections in this segment.
144 /// \arg SectionDataSize - The total size of the sections.
145 void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
147 uint64_t SectionDataStartOffset,
148 uint64_t SectionDataSize) {
149 // struct segment_command (56 bytes) or
150 // struct segment_command_64 (72 bytes)
152 uint64_t Start = OS.tell();
155 unsigned SegmentLoadCommandSize =
156 is64Bit() ? macho::SegmentLoadCommand64Size:
157 macho::SegmentLoadCommand32Size;
158 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
159 Write32(SegmentLoadCommandSize +
160 NumSections * (is64Bit() ? macho::Section64Size :
161 macho::Section32Size));
165 Write64(0); // vmaddr
166 Write64(VMSize); // vmsize
167 Write64(SectionDataStartOffset); // file offset
168 Write64(SectionDataSize); // file size
170 Write32(0); // vmaddr
171 Write32(VMSize); // vmsize
172 Write32(SectionDataStartOffset); // file offset
173 Write32(SectionDataSize); // file size
175 Write32(0x7); // maxprot
176 Write32(0x7); // initprot
177 Write32(NumSections);
180 assert(OS.tell() - Start == SegmentLoadCommandSize);
183 void MachObjectWriter::WriteSection(const MCAssembler &Asm,
184 const MCAsmLayout &Layout,
185 const MCSectionData &SD,
187 uint64_t RelocationsStart,
188 unsigned NumRelocations) {
189 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
191 // The offset is unused for virtual sections.
192 if (SD.getSection().isVirtualSection()) {
193 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
197 // struct section (68 bytes) or
198 // struct section_64 (80 bytes)
200 uint64_t Start = OS.tell();
203 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
204 WriteBytes(Section.getSectionName(), 16);
205 WriteBytes(Section.getSegmentName(), 16);
207 Write64(getSectionAddress(&SD)); // address
208 Write64(SectionSize); // size
210 Write32(getSectionAddress(&SD)); // address
211 Write32(SectionSize); // size
215 unsigned Flags = Section.getTypeAndAttributes();
216 if (SD.hasInstructions())
217 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
219 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
220 Write32(Log2_32(SD.getAlignment()));
221 Write32(NumRelocations ? RelocationsStart : 0);
222 Write32(NumRelocations);
224 Write32(IndirectSymBase.lookup(&SD)); // reserved1
225 Write32(Section.getStubSize()); // reserved2
227 Write32(0); // reserved3
229 assert(OS.tell() - Start == (is64Bit() ? macho::Section64Size :
230 macho::Section32Size));
233 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
235 uint32_t StringTableOffset,
236 uint32_t StringTableSize) {
237 // struct symtab_command (24 bytes)
239 uint64_t Start = OS.tell();
242 Write32(macho::LCT_Symtab);
243 Write32(macho::SymtabLoadCommandSize);
244 Write32(SymbolOffset);
246 Write32(StringTableOffset);
247 Write32(StringTableSize);
249 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
252 void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
253 uint32_t NumLocalSymbols,
254 uint32_t FirstExternalSymbol,
255 uint32_t NumExternalSymbols,
256 uint32_t FirstUndefinedSymbol,
257 uint32_t NumUndefinedSymbols,
258 uint32_t IndirectSymbolOffset,
259 uint32_t NumIndirectSymbols) {
260 // struct dysymtab_command (80 bytes)
262 uint64_t Start = OS.tell();
265 Write32(macho::LCT_Dysymtab);
266 Write32(macho::DysymtabLoadCommandSize);
267 Write32(FirstLocalSymbol);
268 Write32(NumLocalSymbols);
269 Write32(FirstExternalSymbol);
270 Write32(NumExternalSymbols);
271 Write32(FirstUndefinedSymbol);
272 Write32(NumUndefinedSymbols);
273 Write32(0); // tocoff
275 Write32(0); // modtaboff
276 Write32(0); // nmodtab
277 Write32(0); // extrefsymoff
278 Write32(0); // nextrefsyms
279 Write32(IndirectSymbolOffset);
280 Write32(NumIndirectSymbols);
281 Write32(0); // extreloff
282 Write32(0); // nextrel
283 Write32(0); // locreloff
284 Write32(0); // nlocrel
286 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
289 void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
290 const MCAsmLayout &Layout) {
291 MCSymbolData &Data = *MSD.SymbolData;
292 const MCSymbol &Symbol = Data.getSymbol();
294 uint16_t Flags = Data.getFlags();
295 uint64_t Address = 0;
297 // Set the N_TYPE bits. See <mach-o/nlist.h>.
299 // FIXME: Are the prebound or indirect fields possible here?
300 if (Symbol.isUndefined())
301 Type = macho::STT_Undefined;
302 else if (Symbol.isAbsolute())
303 Type = macho::STT_Absolute;
305 Type = macho::STT_Section;
307 // FIXME: Set STAB bits.
309 if (Data.isPrivateExtern())
310 Type |= macho::STF_PrivateExtern;
313 if (Data.isExternal() || Symbol.isUndefined())
314 Type |= macho::STF_External;
316 // Compute the symbol address.
317 if (Symbol.isDefined()) {
318 if (Symbol.isAbsolute()) {
319 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
321 Address = getSymbolAddress(&Data, Layout);
323 } else if (Data.isCommon()) {
324 // Common symbols are encoded with the size in the address
325 // field, and their alignment in the flags.
326 Address = Data.getCommonSize();
328 // Common alignment is packed into the 'desc' bits.
329 if (unsigned Align = Data.getCommonAlignment()) {
330 unsigned Log2Size = Log2_32(Align);
331 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
333 report_fatal_error("invalid 'common' alignment '" +
335 // FIXME: Keep this mask with the SymbolFlags enumeration.
336 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
340 // struct nlist (12 bytes)
342 Write32(MSD.StringIndex);
344 Write8(MSD.SectionIndex);
346 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
355 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
358 uint64_t Start = OS.tell();
362 Write32(macho::LinkeditLoadCommandSize);
366 assert(OS.tell() - Start == macho::LinkeditLoadCommandSize);
370 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
371 const MCAsmLayout &Layout,
372 const MCFragment *Fragment,
373 const MCFixup &Fixup,
375 uint64_t &FixedValue) {
376 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
380 void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
381 // This is the point where 'as' creates actual symbols for indirect symbols
382 // (in the following two passes). It would be easier for us to do this sooner
383 // when we see the attribute, but that makes getting the order in the symbol
384 // table much more complicated than it is worth.
386 // FIXME: Revisit this when the dust settles.
388 // Bind non lazy symbol pointers first.
389 unsigned IndirectIndex = 0;
390 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
391 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
392 const MCSectionMachO &Section =
393 cast<MCSectionMachO>(it->SectionData->getSection());
395 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
398 // Initialize the section indirect symbol base, if necessary.
399 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
401 Asm.getOrCreateSymbolData(*it->Symbol);
404 // Then lazy symbol pointers and symbol stubs.
406 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
407 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
408 const MCSectionMachO &Section =
409 cast<MCSectionMachO>(it->SectionData->getSection());
411 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
412 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
415 // Initialize the section indirect symbol base, if necessary.
416 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
418 // Set the symbol type to undefined lazy, but only on construction.
420 // FIXME: Do not hardcode.
422 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
424 Entry.setFlags(Entry.getFlags() | 0x0001);
428 /// ComputeSymbolTable - Compute the symbol table data
430 /// \param StringTable [out] - The string table data.
431 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
433 void MachObjectWriter::
434 ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
435 std::vector<MachSymbolData> &LocalSymbolData,
436 std::vector<MachSymbolData> &ExternalSymbolData,
437 std::vector<MachSymbolData> &UndefinedSymbolData) {
438 // Build section lookup table.
439 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
441 for (MCAssembler::iterator it = Asm.begin(),
442 ie = Asm.end(); it != ie; ++it, ++Index)
443 SectionIndexMap[&it->getSection()] = Index;
444 assert(Index <= 256 && "Too many sections!");
446 // Index 0 is always the empty string.
447 StringMap<uint64_t> StringIndexMap;
448 StringTable += '\x00';
450 // Build the symbol arrays and the string table, but only for non-local
453 // The particular order that we collect the symbols and create the string
454 // table, then sort the symbols is chosen to match 'as'. Even though it
455 // doesn't matter for correctness, this is important for letting us diff .o
457 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
458 ie = Asm.symbol_end(); it != ie; ++it) {
459 const MCSymbol &Symbol = it->getSymbol();
461 // Ignore non-linker visible symbols.
462 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
465 if (!it->isExternal() && !Symbol.isUndefined())
468 uint64_t &Entry = StringIndexMap[Symbol.getName()];
470 Entry = StringTable.size();
471 StringTable += Symbol.getName();
472 StringTable += '\x00';
477 MSD.StringIndex = Entry;
479 if (Symbol.isUndefined()) {
480 MSD.SectionIndex = 0;
481 UndefinedSymbolData.push_back(MSD);
482 } else if (Symbol.isAbsolute()) {
483 MSD.SectionIndex = 0;
484 ExternalSymbolData.push_back(MSD);
486 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
487 assert(MSD.SectionIndex && "Invalid section index!");
488 ExternalSymbolData.push_back(MSD);
492 // Now add the data for local symbols.
493 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
494 ie = Asm.symbol_end(); it != ie; ++it) {
495 const MCSymbol &Symbol = it->getSymbol();
497 // Ignore non-linker visible symbols.
498 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
501 if (it->isExternal() || Symbol.isUndefined())
504 uint64_t &Entry = StringIndexMap[Symbol.getName()];
506 Entry = StringTable.size();
507 StringTable += Symbol.getName();
508 StringTable += '\x00';
513 MSD.StringIndex = Entry;
515 if (Symbol.isAbsolute()) {
516 MSD.SectionIndex = 0;
517 LocalSymbolData.push_back(MSD);
519 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
520 assert(MSD.SectionIndex && "Invalid section index!");
521 LocalSymbolData.push_back(MSD);
525 // External and undefined symbols are required to be in lexicographic order.
526 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
527 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
529 // Set the symbol indices.
531 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
532 LocalSymbolData[i].SymbolData->setIndex(Index++);
533 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
534 ExternalSymbolData[i].SymbolData->setIndex(Index++);
535 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
536 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
538 // The string table is padded to a multiple of 4.
539 while (StringTable.size() % 4)
540 StringTable += '\x00';
543 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
544 const MCAsmLayout &Layout) {
545 uint64_t StartAddress = 0;
546 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
547 for (int i = 0, n = Order.size(); i != n ; ++i) {
548 const MCSectionData *SD = Order[i];
549 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
550 SectionAddress[SD] = StartAddress;
551 StartAddress += Layout.getSectionAddressSize(SD);
553 // Explicitly pad the section to match the alignment requirements of the
554 // following one. This is for 'gas' compatibility, it shouldn't
555 /// strictly be necessary.
556 StartAddress += getPaddingSize(SD, Layout);
560 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
561 const MCAsmLayout &Layout) {
562 computeSectionAddresses(Asm, Layout);
564 // Create symbol data for any indirect symbols.
565 BindIndirectSymbols(Asm);
567 // Compute symbol table information and bind symbol indices.
568 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
569 UndefinedSymbolData);
572 bool MachObjectWriter::
573 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
574 const MCSymbolData &DataA,
575 const MCFragment &FB,
577 bool IsPCRel) const {
581 // The effective address is
582 // addr(atom(A)) + offset(A)
583 // - addr(atom(B)) - offset(B)
584 // and the offsets are not relocatable, so the fixup is fully resolved when
585 // addr(atom(A)) - addr(atom(B)) == 0.
586 const MCSymbolData *A_Base = 0, *B_Base = 0;
588 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
589 const MCSection &SecA = SA.getSection();
590 const MCSection &SecB = FB.getParent()->getSection();
593 // The simple (Darwin, except on x86_64) way of dealing with this was to
594 // assume that any reference to a temporary symbol *must* be a temporary
595 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
596 // relocation to a temporary symbol (in the same section) is fully
597 // resolved. This also works in conjunction with absolutized .set, which
598 // requires the compiler to use .set to absolutize the differences between
599 // symbols which the compiler knows to be assembly time constants, so we
600 // don't need to worry about considering symbol differences fully resolved.
602 // If the file isn't using sub-sections-via-symbols, we can make the
603 // same assumptions about any symbol that we normally make about
606 if (!Asm.getBackend().hasReliableSymbolDifference()) {
607 if (!SA.isInSection() || &SecA != &SecB ||
608 (!SA.isTemporary() &&
609 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
610 Asm.getSubsectionsViaSymbols()))
614 // For Darwin x86_64, there is one special case when the reference IsPCRel.
615 // If the fragment with the reference does not have a base symbol but meets
616 // the simple way of dealing with this, in that it is a temporary symbol in
617 // the same atom then it is assumed to be fully resolved. This is needed so
618 // a relocation entry is not created and so the static linker does not
619 // mess up the reference later.
620 else if(!FB.getAtom() &&
621 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
625 if (!TargetObjectWriter->useAggressiveSymbolFolding())
629 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
631 // Bail if the symbol has no fragment.
635 A_Base = FA->getAtom();
639 B_Base = FB.getAtom();
643 // If the atoms are the same, they are guaranteed to have the same address.
644 if (A_Base == B_Base)
647 // Otherwise, we can't prove this is fully resolved.
651 void MachObjectWriter::WriteObject(MCAssembler &Asm,
652 const MCAsmLayout &Layout) {
653 unsigned NumSections = Asm.size();
655 // The section data starts after the header, the segment load command (and
656 // section headers) and the symbol table.
657 unsigned NumLoadCommands = 1;
658 uint64_t LoadCommandsSize = is64Bit() ?
659 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
660 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
662 // Add the symbol table load command sizes, if used.
663 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
664 UndefinedSymbolData.size();
666 NumLoadCommands += 2;
667 LoadCommandsSize += (macho::SymtabLoadCommandSize +
668 macho::DysymtabLoadCommandSize);
671 // Add the data-in-code load command size, if used.
672 unsigned NumDataRegions = Asm.getDataRegions().size();
673 if (NumDataRegions) {
675 LoadCommandsSize += macho::LinkeditLoadCommandSize;
678 // Compute the total size of the section data, as well as its file size and vm
680 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
681 macho::Header32Size) + LoadCommandsSize;
682 uint64_t SectionDataSize = 0;
683 uint64_t SectionDataFileSize = 0;
685 for (MCAssembler::const_iterator it = Asm.begin(),
686 ie = Asm.end(); it != ie; ++it) {
687 const MCSectionData &SD = *it;
688 uint64_t Address = getSectionAddress(&SD);
689 uint64_t Size = Layout.getSectionAddressSize(&SD);
690 uint64_t FileSize = Layout.getSectionFileSize(&SD);
691 FileSize += getPaddingSize(&SD, Layout);
693 VMSize = std::max(VMSize, Address + Size);
695 if (SD.getSection().isVirtualSection())
698 SectionDataSize = std::max(SectionDataSize, Address + Size);
699 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
702 // The section data is padded to 4 bytes.
704 // FIXME: Is this machine dependent?
705 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
706 SectionDataFileSize += SectionDataPadding;
708 // Write the prolog, starting with the header and load command...
709 WriteHeader(NumLoadCommands, LoadCommandsSize,
710 Asm.getSubsectionsViaSymbols());
711 WriteSegmentLoadCommand(NumSections, VMSize,
712 SectionDataStart, SectionDataSize);
714 // ... and then the section headers.
715 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
716 for (MCAssembler::const_iterator it = Asm.begin(),
717 ie = Asm.end(); it != ie; ++it) {
718 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
719 unsigned NumRelocs = Relocs.size();
720 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
721 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
722 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
725 // Write the data-in-code load command, if used.
726 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
727 if (NumDataRegions) {
728 uint64_t DataRegionsOffset = RelocTableEnd;
729 uint64_t DataRegionsSize = NumDataRegions * 8;
730 WriteLinkeditLoadCommand(macho::LCT_DataInCode, DataRegionsOffset,
734 // Write the symbol table load command, if used.
736 unsigned FirstLocalSymbol = 0;
737 unsigned NumLocalSymbols = LocalSymbolData.size();
738 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
739 unsigned NumExternalSymbols = ExternalSymbolData.size();
740 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
741 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
742 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
743 unsigned NumSymTabSymbols =
744 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
745 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
746 uint64_t IndirectSymbolOffset = 0;
748 // If used, the indirect symbols are written after the section data.
749 if (NumIndirectSymbols)
750 IndirectSymbolOffset = DataInCodeTableEnd;
752 // The symbol table is written after the indirect symbol data.
753 uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
755 // The string table is written after symbol table.
756 uint64_t StringTableOffset =
757 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
759 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
760 StringTableOffset, StringTable.size());
762 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
763 FirstExternalSymbol, NumExternalSymbols,
764 FirstUndefinedSymbol, NumUndefinedSymbols,
765 IndirectSymbolOffset, NumIndirectSymbols);
768 // Write the actual section data.
769 for (MCAssembler::const_iterator it = Asm.begin(),
770 ie = Asm.end(); it != ie; ++it) {
771 Asm.writeSectionData(it, Layout);
773 uint64_t Pad = getPaddingSize(it, Layout);
774 for (unsigned int i = 0; i < Pad; ++i)
778 // Write the extra padding.
779 WriteZeros(SectionDataPadding);
781 // Write the relocation entries.
782 for (MCAssembler::const_iterator it = Asm.begin(),
783 ie = Asm.end(); it != ie; ++it) {
784 // Write the section relocation entries, in reverse order to match 'as'
785 // (approximately, the exact algorithm is more complicated than this).
786 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
787 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
788 Write32(Relocs[e - i - 1].Word0);
789 Write32(Relocs[e - i - 1].Word1);
793 // Write out the data-in-code region payload, if there is one.
794 for (MCAssembler::const_data_region_iterator
795 it = Asm.data_region_begin(), ie = Asm.data_region_end();
797 const DataRegionData *Data = &(*it);
798 uint64_t Start = getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start), Layout);
799 uint64_t End = getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End), Layout);
800 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
801 << " start: " << Start << "(" << Data->Start->getName() << ")"
802 << " end: " << End << "(" << Data->End->getName() << ")"
803 << " size: " << End - Start
806 Write16(End - Start);
810 // Write the symbol table data, if used.
812 // Write the indirect symbol entries.
813 for (MCAssembler::const_indirect_symbol_iterator
814 it = Asm.indirect_symbol_begin(),
815 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
816 // Indirect symbols in the non lazy symbol pointer section have some
818 const MCSectionMachO &Section =
819 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
820 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
821 // If this symbol is defined and internal, mark it as such.
822 if (it->Symbol->isDefined() &&
823 !Asm.getSymbolData(*it->Symbol).isExternal()) {
824 uint32_t Flags = macho::ISF_Local;
825 if (it->Symbol->isAbsolute())
826 Flags |= macho::ISF_Absolute;
832 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
835 // FIXME: Check that offsets match computed ones.
837 // Write the symbol table entries.
838 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
839 WriteNlist(LocalSymbolData[i], Layout);
840 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
841 WriteNlist(ExternalSymbolData[i], Layout);
842 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
843 WriteNlist(UndefinedSymbolData[i], Layout);
845 // Write the string table.
846 OS << StringTable.str();
850 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
852 bool IsLittleEndian) {
853 return new MachObjectWriter(MOTW, OS, IsLittleEndian);