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/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MachO.h"
29 void MachObjectWriter::reset() {
31 IndirectSymBase.clear();
33 LocalSymbolData.clear();
34 ExternalSymbolData.clear();
35 UndefinedSymbolData.clear();
36 MCObjectWriter::reset();
39 bool MachObjectWriter::
40 doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
41 // Undefined symbols are always extern.
42 if (SD->Symbol->isUndefined())
45 // References to weak definitions require external relocation entries; the
46 // definition may not always be the one in the same object file.
47 if (SD->getFlags() & SF_WeakDefinition)
50 // Otherwise, we can use an internal relocation.
54 bool MachObjectWriter::
55 MachSymbolData::operator<(const MachSymbolData &RHS) const {
56 return SymbolData->getSymbol().getName() <
57 RHS.SymbolData->getSymbol().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 MCSymbolData* SD,
74 const MCAsmLayout &Layout) const {
75 const MCSymbol &S = SD->getSymbol();
77 // If this is a variable, then recursively evaluate now.
79 if (const MCConstantExpr *C =
80 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
85 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
86 report_fatal_error("unable to evaluate offset for variable '" +
89 // Verify that any used symbols are defined.
90 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
91 report_fatal_error("unable to evaluate offset to undefined symbol '" +
92 Target.getSymA()->getSymbol().getName() + "'");
93 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
94 report_fatal_error("unable to evaluate offset to undefined symbol '" +
95 Target.getSymB()->getSymbol().getName() + "'");
97 uint64_t Address = Target.getConstant();
99 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
100 Target.getSymA()->getSymbol()), Layout);
101 if (Target.getSymB())
102 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
103 Target.getSymB()->getSymbol()), Layout);
107 return getSectionAddress(SD->getFragment()->getParent()) +
108 Layout.getSymbolOffset(SD);
111 uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
112 const MCAsmLayout &Layout) const {
113 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
114 unsigned Next = SD->getLayoutOrder() + 1;
115 if (Next >= Layout.getSectionOrder().size())
118 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
119 if (NextSD.getSection().isVirtualSection())
121 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
124 void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
125 unsigned LoadCommandsSize,
126 bool SubsectionsViaSymbols) {
129 if (SubsectionsViaSymbols)
130 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
132 // struct mach_header (28 bytes) or
133 // struct mach_header_64 (32 bytes)
135 uint64_t Start = OS.tell();
138 Write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
140 Write32(TargetObjectWriter->getCPUType());
141 Write32(TargetObjectWriter->getCPUSubtype());
143 Write32(MachO::MH_OBJECT);
144 Write32(NumLoadCommands);
145 Write32(LoadCommandsSize);
148 Write32(0); // reserved
150 assert(OS.tell() - Start ==
151 (is64Bit()?sizeof(MachO::mach_header_64): sizeof(MachO::mach_header)));
154 /// WriteSegmentLoadCommand - Write a segment load command.
156 /// \param NumSections The number of sections in this segment.
157 /// \param SectionDataSize The total size of the sections.
158 void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
160 uint64_t SectionDataStartOffset,
161 uint64_t SectionDataSize) {
162 // struct segment_command (56 bytes) or
163 // struct segment_command_64 (72 bytes)
165 uint64_t Start = OS.tell();
168 unsigned SegmentLoadCommandSize =
169 is64Bit() ? sizeof(MachO::segment_command_64):
170 sizeof(MachO::segment_command);
171 Write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
172 Write32(SegmentLoadCommandSize +
173 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
174 sizeof(MachO::section)));
178 Write64(0); // vmaddr
179 Write64(VMSize); // vmsize
180 Write64(SectionDataStartOffset); // file offset
181 Write64(SectionDataSize); // file size
183 Write32(0); // vmaddr
184 Write32(VMSize); // vmsize
185 Write32(SectionDataStartOffset); // file offset
186 Write32(SectionDataSize); // file size
188 Write32(0x7); // maxprot
189 Write32(0x7); // initprot
190 Write32(NumSections);
193 assert(OS.tell() - Start == SegmentLoadCommandSize);
196 void MachObjectWriter::WriteSection(const MCAssembler &Asm,
197 const MCAsmLayout &Layout,
198 const MCSectionData &SD,
200 uint64_t RelocationsStart,
201 unsigned NumRelocations) {
202 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
204 // The offset is unused for virtual sections.
205 if (SD.getSection().isVirtualSection()) {
206 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
210 // struct section (68 bytes) or
211 // struct section_64 (80 bytes)
213 uint64_t Start = OS.tell();
216 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
217 WriteBytes(Section.getSectionName(), 16);
218 WriteBytes(Section.getSegmentName(), 16);
220 Write64(getSectionAddress(&SD)); // address
221 Write64(SectionSize); // size
223 Write32(getSectionAddress(&SD)); // address
224 Write32(SectionSize); // size
228 unsigned Flags = Section.getTypeAndAttributes();
229 if (SD.hasInstructions())
230 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
232 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
233 Write32(Log2_32(SD.getAlignment()));
234 Write32(NumRelocations ? RelocationsStart : 0);
235 Write32(NumRelocations);
237 Write32(IndirectSymBase.lookup(&SD)); // reserved1
238 Write32(Section.getStubSize()); // reserved2
240 Write32(0); // reserved3
242 assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
243 sizeof(MachO::section)));
246 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
248 uint32_t StringTableOffset,
249 uint32_t StringTableSize) {
250 // struct symtab_command (24 bytes)
252 uint64_t Start = OS.tell();
255 Write32(MachO::LC_SYMTAB);
256 Write32(sizeof(MachO::symtab_command));
257 Write32(SymbolOffset);
259 Write32(StringTableOffset);
260 Write32(StringTableSize);
262 assert(OS.tell() - Start == sizeof(MachO::symtab_command));
265 void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
266 uint32_t NumLocalSymbols,
267 uint32_t FirstExternalSymbol,
268 uint32_t NumExternalSymbols,
269 uint32_t FirstUndefinedSymbol,
270 uint32_t NumUndefinedSymbols,
271 uint32_t IndirectSymbolOffset,
272 uint32_t NumIndirectSymbols) {
273 // struct dysymtab_command (80 bytes)
275 uint64_t Start = OS.tell();
278 Write32(MachO::LC_DYSYMTAB);
279 Write32(sizeof(MachO::dysymtab_command));
280 Write32(FirstLocalSymbol);
281 Write32(NumLocalSymbols);
282 Write32(FirstExternalSymbol);
283 Write32(NumExternalSymbols);
284 Write32(FirstUndefinedSymbol);
285 Write32(NumUndefinedSymbols);
286 Write32(0); // tocoff
288 Write32(0); // modtaboff
289 Write32(0); // nmodtab
290 Write32(0); // extrefsymoff
291 Write32(0); // nextrefsyms
292 Write32(IndirectSymbolOffset);
293 Write32(NumIndirectSymbols);
294 Write32(0); // extreloff
295 Write32(0); // nextrel
296 Write32(0); // locreloff
297 Write32(0); // nlocrel
299 assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
302 void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
303 const MCAsmLayout &Layout) {
304 MCSymbolData &Data = *MSD.SymbolData;
305 const MCSymbol &Symbol = Data.getSymbol();
307 uint16_t Flags = Data.getFlags();
308 uint64_t Address = 0;
310 // Set the N_TYPE bits. See <mach-o/nlist.h>.
312 // FIXME: Are the prebound or indirect fields possible here?
313 if (Symbol.isUndefined())
314 Type = MachO::N_UNDF;
315 else if (Symbol.isAbsolute())
318 Type = MachO::N_SECT;
320 // FIXME: Set STAB bits.
322 if (Data.isPrivateExtern())
323 Type |= MachO::N_PEXT;
326 if (Data.isExternal() || Symbol.isUndefined())
327 Type |= MachO::N_EXT;
329 // Compute the symbol address.
330 if (Symbol.isDefined()) {
331 Address = getSymbolAddress(&Data, Layout);
332 } else if (Data.isCommon()) {
333 // Common symbols are encoded with the size in the address
334 // field, and their alignment in the flags.
335 Address = Data.getCommonSize();
337 // Common alignment is packed into the 'desc' bits.
338 if (unsigned Align = Data.getCommonAlignment()) {
339 unsigned Log2Size = Log2_32(Align);
340 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
342 report_fatal_error("invalid 'common' alignment '" +
344 // FIXME: Keep this mask with the SymbolFlags enumeration.
345 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
349 // struct nlist (12 bytes)
351 Write32(MSD.StringIndex);
353 Write8(MSD.SectionIndex);
355 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
364 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
367 uint64_t Start = OS.tell();
371 Write32(sizeof(MachO::linkedit_data_command));
375 assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
378 static unsigned ComputeLinkerOptionsLoadCommandSize(
379 const std::vector<std::string> &Options, bool is64Bit)
381 unsigned Size = sizeof(MachO::linker_options_command);
382 for (unsigned i = 0, e = Options.size(); i != e; ++i)
383 Size += Options[i].size() + 1;
384 return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
387 void MachObjectWriter::WriteLinkerOptionsLoadCommand(
388 const std::vector<std::string> &Options)
390 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
391 uint64_t Start = OS.tell();
394 Write32(MachO::LC_LINKER_OPTIONS);
396 Write32(Options.size());
397 uint64_t BytesWritten = sizeof(MachO::linker_options_command);
398 for (unsigned i = 0, e = Options.size(); i != e; ++i) {
399 // Write each string, including the null byte.
400 const std::string &Option = Options[i];
401 WriteBytes(Option.c_str(), Option.size() + 1);
402 BytesWritten += Option.size() + 1;
405 // Pad to a multiple of the pointer size.
406 WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
408 assert(OS.tell() - Start == Size);
412 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
413 const MCAsmLayout &Layout,
414 const MCFragment *Fragment,
415 const MCFixup &Fixup,
417 uint64_t &FixedValue) {
418 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
422 void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
423 // This is the point where 'as' creates actual symbols for indirect symbols
424 // (in the following two passes). It would be easier for us to do this sooner
425 // when we see the attribute, but that makes getting the order in the symbol
426 // table much more complicated than it is worth.
428 // FIXME: Revisit this when the dust settles.
430 // Report errors for use of .indirect_symbol not in a symbol pointer section
432 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
433 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
434 const MCSectionMachO &Section =
435 cast<MCSectionMachO>(it->SectionData->getSection());
437 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS &&
438 Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
439 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS) {
440 MCSymbol &Symbol = *it->Symbol;
441 report_fatal_error("indirect symbol '" + Symbol.getName() +
442 "' not in a symbol pointer or stub section");
446 // Bind non lazy symbol pointers first.
447 unsigned IndirectIndex = 0;
448 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
449 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
450 const MCSectionMachO &Section =
451 cast<MCSectionMachO>(it->SectionData->getSection());
453 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
456 // Initialize the section indirect symbol base, if necessary.
457 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
459 Asm.getOrCreateSymbolData(*it->Symbol);
462 // Then lazy symbol pointers and symbol stubs.
464 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
465 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
466 const MCSectionMachO &Section =
467 cast<MCSectionMachO>(it->SectionData->getSection());
469 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
470 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
473 // Initialize the section indirect symbol base, if necessary.
474 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
476 // Set the symbol type to undefined lazy, but only on construction.
478 // FIXME: Do not hardcode.
480 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
482 Entry.setFlags(Entry.getFlags() | 0x0001);
486 /// ComputeSymbolTable - Compute the symbol table data
488 /// \param StringTable [out] - The string table data.
489 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
491 void MachObjectWriter::
492 ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
493 std::vector<MachSymbolData> &LocalSymbolData,
494 std::vector<MachSymbolData> &ExternalSymbolData,
495 std::vector<MachSymbolData> &UndefinedSymbolData) {
496 // Build section lookup table.
497 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
499 for (MCAssembler::iterator it = Asm.begin(),
500 ie = Asm.end(); it != ie; ++it, ++Index)
501 SectionIndexMap[&it->getSection()] = Index;
502 assert(Index <= 256 && "Too many sections!");
504 // Index 0 is always the empty string.
505 StringMap<uint64_t> StringIndexMap;
506 StringTable += '\x00';
508 // Build the symbol arrays and the string table, but only for non-local
511 // The particular order that we collect the symbols and create the string
512 // table, then sort the symbols is chosen to match 'as'. Even though it
513 // doesn't matter for correctness, this is important for letting us diff .o
515 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
516 ie = Asm.symbol_end(); it != ie; ++it) {
517 const MCSymbol &Symbol = it->getSymbol();
519 // Ignore non-linker visible symbols.
520 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
523 if (!it->isExternal() && !Symbol.isUndefined())
526 uint64_t &Entry = StringIndexMap[Symbol.getName()];
528 Entry = StringTable.size();
529 StringTable += Symbol.getName();
530 StringTable += '\x00';
535 MSD.StringIndex = Entry;
537 if (Symbol.isUndefined()) {
538 MSD.SectionIndex = 0;
539 UndefinedSymbolData.push_back(MSD);
540 } else if (Symbol.isAbsolute()) {
541 MSD.SectionIndex = 0;
542 ExternalSymbolData.push_back(MSD);
544 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
545 assert(MSD.SectionIndex && "Invalid section index!");
546 ExternalSymbolData.push_back(MSD);
550 // Now add the data for local symbols.
551 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
552 ie = Asm.symbol_end(); it != ie; ++it) {
553 const MCSymbol &Symbol = it->getSymbol();
555 // Ignore non-linker visible symbols.
556 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
559 if (it->isExternal() || Symbol.isUndefined())
562 uint64_t &Entry = StringIndexMap[Symbol.getName()];
564 Entry = StringTable.size();
565 StringTable += Symbol.getName();
566 StringTable += '\x00';
571 MSD.StringIndex = Entry;
573 if (Symbol.isAbsolute()) {
574 MSD.SectionIndex = 0;
575 LocalSymbolData.push_back(MSD);
577 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
578 assert(MSD.SectionIndex && "Invalid section index!");
579 LocalSymbolData.push_back(MSD);
583 // External and undefined symbols are required to be in lexicographic order.
584 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
585 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
587 // Set the symbol indices.
589 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
590 LocalSymbolData[i].SymbolData->setIndex(Index++);
591 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
592 ExternalSymbolData[i].SymbolData->setIndex(Index++);
593 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
594 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
596 // The string table is padded to a multiple of 4.
597 while (StringTable.size() % 4)
598 StringTable += '\x00';
601 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
602 const MCAsmLayout &Layout) {
603 uint64_t StartAddress = 0;
604 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
605 for (int i = 0, n = Order.size(); i != n ; ++i) {
606 const MCSectionData *SD = Order[i];
607 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
608 SectionAddress[SD] = StartAddress;
609 StartAddress += Layout.getSectionAddressSize(SD);
611 // Explicitly pad the section to match the alignment requirements of the
612 // following one. This is for 'gas' compatibility, it shouldn't
613 /// strictly be necessary.
614 StartAddress += getPaddingSize(SD, Layout);
618 void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
619 const MCAsmLayout &Layout) {
620 for (MCAssembler::symbol_iterator i = Asm.symbol_begin(),
621 e = Asm.symbol_end();
623 MCSymbolData &SD = *i;
624 if (!SD.getSymbol().isVariable())
627 // Is the variable is a symbol difference (SA - SB + C) expression,
628 // and neither symbol is external, mark the variable as absolute.
629 const MCExpr *Expr = SD.getSymbol().getVariableValue();
631 if (Expr->EvaluateAsRelocatable(Value, Layout)) {
632 if (Value.getSymA() && Value.getSymB())
633 const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
638 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
639 const MCAsmLayout &Layout) {
640 computeSectionAddresses(Asm, Layout);
642 // Create symbol data for any indirect symbols.
643 BindIndirectSymbols(Asm);
645 // Mark symbol difference expressions in variables (from .set or = directives)
647 markAbsoluteVariableSymbols(Asm, Layout);
649 // Compute symbol table information and bind symbol indices.
650 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
651 UndefinedSymbolData);
654 bool MachObjectWriter::
655 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
656 const MCSymbolData &DataA,
657 const MCFragment &FB,
659 bool IsPCRel) const {
663 // The effective address is
664 // addr(atom(A)) + offset(A)
665 // - addr(atom(B)) - offset(B)
666 // and the offsets are not relocatable, so the fixup is fully resolved when
667 // addr(atom(A)) - addr(atom(B)) == 0.
668 const MCSymbolData *A_Base = 0, *B_Base = 0;
670 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
671 const MCSection &SecA = SA.getSection();
672 const MCSection &SecB = FB.getParent()->getSection();
675 // The simple (Darwin, except on x86_64) way of dealing with this was to
676 // assume that any reference to a temporary symbol *must* be a temporary
677 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
678 // relocation to a temporary symbol (in the same section) is fully
679 // resolved. This also works in conjunction with absolutized .set, which
680 // requires the compiler to use .set to absolutize the differences between
681 // symbols which the compiler knows to be assembly time constants, so we
682 // don't need to worry about considering symbol differences fully resolved.
684 // If the file isn't using sub-sections-via-symbols, we can make the
685 // same assumptions about any symbol that we normally make about
688 if (!Asm.getBackend().hasReliableSymbolDifference()) {
689 if (!SA.isInSection() || &SecA != &SecB ||
690 (!SA.isTemporary() &&
691 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
692 Asm.getSubsectionsViaSymbols()))
696 // For Darwin x86_64, there is one special case when the reference IsPCRel.
697 // If the fragment with the reference does not have a base symbol but meets
698 // the simple way of dealing with this, in that it is a temporary symbol in
699 // the same atom then it is assumed to be fully resolved. This is needed so
700 // a relocation entry is not created and so the static linker does not
701 // mess up the reference later.
702 else if(!FB.getAtom() &&
703 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
707 if (!TargetObjectWriter->useAggressiveSymbolFolding())
711 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
713 // Bail if the symbol has no fragment.
717 A_Base = FA->getAtom();
721 B_Base = FB.getAtom();
725 // If the atoms are the same, they are guaranteed to have the same address.
726 if (A_Base == B_Base)
729 // Otherwise, we can't prove this is fully resolved.
733 void MachObjectWriter::WriteObject(MCAssembler &Asm,
734 const MCAsmLayout &Layout) {
735 unsigned NumSections = Asm.size();
737 // The section data starts after the header, the segment load command (and
738 // section headers) and the symbol table.
739 unsigned NumLoadCommands = 1;
740 uint64_t LoadCommandsSize = is64Bit() ?
741 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
742 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
744 // Add the data-in-code load command size, if used.
745 unsigned NumDataRegions = Asm.getDataRegions().size();
746 if (NumDataRegions) {
748 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
751 // Add the symbol table load command sizes, if used.
752 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
753 UndefinedSymbolData.size();
755 NumLoadCommands += 2;
756 LoadCommandsSize += (sizeof(MachO::symtab_command) +
757 sizeof(MachO::dysymtab_command));
760 // Add the linker option load commands sizes.
761 const std::vector<std::vector<std::string> > &LinkerOptions =
762 Asm.getLinkerOptions();
763 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
765 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
769 // Compute the total size of the section data, as well as its file size and vm
771 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
772 sizeof(MachO::mach_header)) + LoadCommandsSize;
773 uint64_t SectionDataSize = 0;
774 uint64_t SectionDataFileSize = 0;
776 for (MCAssembler::const_iterator it = Asm.begin(),
777 ie = Asm.end(); it != ie; ++it) {
778 const MCSectionData &SD = *it;
779 uint64_t Address = getSectionAddress(&SD);
780 uint64_t Size = Layout.getSectionAddressSize(&SD);
781 uint64_t FileSize = Layout.getSectionFileSize(&SD);
782 FileSize += getPaddingSize(&SD, Layout);
784 VMSize = std::max(VMSize, Address + Size);
786 if (SD.getSection().isVirtualSection())
789 SectionDataSize = std::max(SectionDataSize, Address + Size);
790 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
793 // The section data is padded to 4 bytes.
795 // FIXME: Is this machine dependent?
796 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
797 SectionDataFileSize += SectionDataPadding;
799 // Write the prolog, starting with the header and load command...
800 WriteHeader(NumLoadCommands, LoadCommandsSize,
801 Asm.getSubsectionsViaSymbols());
802 WriteSegmentLoadCommand(NumSections, VMSize,
803 SectionDataStart, SectionDataSize);
805 // ... and then the section headers.
806 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
807 for (MCAssembler::const_iterator it = Asm.begin(),
808 ie = Asm.end(); it != ie; ++it) {
809 std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
810 unsigned NumRelocs = Relocs.size();
811 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
812 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
813 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
816 // Write the data-in-code load command, if used.
817 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
818 if (NumDataRegions) {
819 uint64_t DataRegionsOffset = RelocTableEnd;
820 uint64_t DataRegionsSize = NumDataRegions * 8;
821 WriteLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
825 // Write the symbol table load command, if used.
827 unsigned FirstLocalSymbol = 0;
828 unsigned NumLocalSymbols = LocalSymbolData.size();
829 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
830 unsigned NumExternalSymbols = ExternalSymbolData.size();
831 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
832 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
833 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
834 unsigned NumSymTabSymbols =
835 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
836 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
837 uint64_t IndirectSymbolOffset = 0;
839 // If used, the indirect symbols are written after the section data.
840 if (NumIndirectSymbols)
841 IndirectSymbolOffset = DataInCodeTableEnd;
843 // The symbol table is written after the indirect symbol data.
844 uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
846 // The string table is written after symbol table.
847 uint64_t StringTableOffset =
848 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
849 sizeof(MachO::nlist_64) :
850 sizeof(MachO::nlist));
851 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
852 StringTableOffset, StringTable.size());
854 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
855 FirstExternalSymbol, NumExternalSymbols,
856 FirstUndefinedSymbol, NumUndefinedSymbols,
857 IndirectSymbolOffset, NumIndirectSymbols);
860 // Write the linker options load commands.
861 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
862 WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
865 // Write the actual section data.
866 for (MCAssembler::const_iterator it = Asm.begin(),
867 ie = Asm.end(); it != ie; ++it) {
868 Asm.writeSectionData(it, Layout);
870 uint64_t Pad = getPaddingSize(it, Layout);
871 for (unsigned int i = 0; i < Pad; ++i)
875 // Write the extra padding.
876 WriteZeros(SectionDataPadding);
878 // Write the relocation entries.
879 for (MCAssembler::const_iterator it = Asm.begin(),
880 ie = Asm.end(); it != ie; ++it) {
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<MachO::any_relocation_info> &Relocs = Relocations[it];
884 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
885 Write32(Relocs[e - i - 1].r_word0);
886 Write32(Relocs[e - i - 1].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);
896 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
899 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
901 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
902 << " start: " << Start << "(" << Data->Start->getName() << ")"
903 << " end: " << End << "(" << Data->End->getName() << ")"
904 << " size: " << End - Start
907 Write16(End - Start);
911 // Write the symbol table data, if used.
913 // Write the indirect symbol entries.
914 for (MCAssembler::const_indirect_symbol_iterator
915 it = Asm.indirect_symbol_begin(),
916 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
917 // Indirect symbols in the non lazy symbol pointer section have some
919 const MCSectionMachO &Section =
920 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
921 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
922 // If this symbol is defined and internal, mark it as such.
923 if (it->Symbol->isDefined() &&
924 !Asm.getSymbolData(*it->Symbol).isExternal()) {
925 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
926 if (it->Symbol->isAbsolute())
927 Flags |= MachO::INDIRECT_SYMBOL_ABS;
933 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
936 // FIXME: Check that offsets match computed ones.
938 // Write the symbol table entries.
939 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
940 WriteNlist(LocalSymbolData[i], Layout);
941 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
942 WriteNlist(ExternalSymbolData[i], Layout);
943 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
944 WriteNlist(UndefinedSymbolData[i], Layout);
946 // Write the string table.
947 OS << StringTable.str();
951 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
953 bool IsLittleEndian) {
954 return new MachObjectWriter(MOTW, OS, IsLittleEndian);