LLVM API Documentation

MachObjectWriter.cpp
Go to the documentation of this file.
00001 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/MC/MCMachObjectWriter.h"
00011 #include "llvm/ADT/StringMap.h"
00012 #include "llvm/ADT/Twine.h"
00013 #include "llvm/MC/MCAsmBackend.h"
00014 #include "llvm/MC/MCAsmLayout.h"
00015 #include "llvm/MC/MCAssembler.h"
00016 #include "llvm/MC/MCExpr.h"
00017 #include "llvm/MC/MCFixupKindInfo.h"
00018 #include "llvm/MC/MCMachOSymbolFlags.h"
00019 #include "llvm/MC/MCObjectWriter.h"
00020 #include "llvm/MC/MCSectionMachO.h"
00021 #include "llvm/MC/MCSymbol.h"
00022 #include "llvm/MC/MCValue.h"
00023 #include "llvm/Object/MachOFormat.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 #include <vector>
00027 using namespace llvm;
00028 using namespace llvm::object;
00029 
00030 void MachObjectWriter::reset() {
00031   Relocations.clear();
00032   IndirectSymBase.clear();
00033   StringTable.clear();
00034   LocalSymbolData.clear();
00035   ExternalSymbolData.clear();
00036   UndefinedSymbolData.clear();
00037   MCObjectWriter::reset();
00038 }
00039 
00040 bool MachObjectWriter::
00041 doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
00042   // Undefined symbols are always extern.
00043   if (SD->Symbol->isUndefined())
00044     return true;
00045 
00046   // References to weak definitions require external relocation entries; the
00047   // definition may not always be the one in the same object file.
00048   if (SD->getFlags() & SF_WeakDefinition)
00049     return true;
00050 
00051   // Otherwise, we can use an internal relocation.
00052   return false;
00053 }
00054 
00055 bool MachObjectWriter::
00056 MachSymbolData::operator<(const MachSymbolData &RHS) const {
00057   return SymbolData->getSymbol().getName() <
00058     RHS.SymbolData->getSymbol().getName();
00059 }
00060 
00061 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
00062   const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
00063     (MCFixupKind) Kind);
00064 
00065   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
00066 }
00067 
00068 uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
00069                                               const MCAsmLayout &Layout) const {
00070   return getSectionAddress(Fragment->getParent()) +
00071     Layout.getFragmentOffset(Fragment);
00072 }
00073 
00074 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
00075                                             const MCAsmLayout &Layout) const {
00076   const MCSymbol &S = SD->getSymbol();
00077 
00078   // If this is a variable, then recursively evaluate now.
00079   if (S.isVariable()) {
00080     if (const MCConstantExpr *C =
00081           dyn_cast<const MCConstantExpr>(S.getVariableValue()))
00082       return C->getValue();
00083 
00084 
00085     MCValue Target;
00086     if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
00087       report_fatal_error("unable to evaluate offset for variable '" +
00088                          S.getName() + "'");
00089 
00090     // Verify that any used symbols are defined.
00091     if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
00092       report_fatal_error("unable to evaluate offset to undefined symbol '" +
00093                          Target.getSymA()->getSymbol().getName() + "'");
00094     if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
00095       report_fatal_error("unable to evaluate offset to undefined symbol '" +
00096                          Target.getSymB()->getSymbol().getName() + "'");
00097 
00098     uint64_t Address = Target.getConstant();
00099     if (Target.getSymA())
00100       Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
00101                                     Target.getSymA()->getSymbol()), Layout);
00102     if (Target.getSymB())
00103       Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
00104                                     Target.getSymB()->getSymbol()), Layout);
00105     return Address;
00106   }
00107 
00108   return getSectionAddress(SD->getFragment()->getParent()) +
00109     Layout.getSymbolOffset(SD);
00110 }
00111 
00112 uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
00113                                           const MCAsmLayout &Layout) const {
00114   uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
00115   unsigned Next = SD->getLayoutOrder() + 1;
00116   if (Next >= Layout.getSectionOrder().size())
00117     return 0;
00118 
00119   const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
00120   if (NextSD.getSection().isVirtualSection())
00121     return 0;
00122   return OffsetToAlignment(EndAddr, NextSD.getAlignment());
00123 }
00124 
00125 void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
00126                                    unsigned LoadCommandsSize,
00127                                    bool SubsectionsViaSymbols) {
00128   uint32_t Flags = 0;
00129 
00130   if (SubsectionsViaSymbols)
00131     Flags |= macho::HF_SubsectionsViaSymbols;
00132 
00133   // struct mach_header (28 bytes) or
00134   // struct mach_header_64 (32 bytes)
00135 
00136   uint64_t Start = OS.tell();
00137   (void) Start;
00138 
00139   Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
00140 
00141   Write32(TargetObjectWriter->getCPUType());
00142   Write32(TargetObjectWriter->getCPUSubtype());
00143 
00144   Write32(macho::HFT_Object);
00145   Write32(NumLoadCommands);
00146   Write32(LoadCommandsSize);
00147   Write32(Flags);
00148   if (is64Bit())
00149     Write32(0); // reserved
00150 
00151   assert(OS.tell() - Start ==
00152          (is64Bit() ? macho::Header64Size : macho::Header32Size));
00153 }
00154 
00155 /// WriteSegmentLoadCommand - Write a segment load command.
00156 ///
00157 /// \param NumSections The number of sections in this segment.
00158 /// \param SectionDataSize The total size of the sections.
00159 void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
00160                                                uint64_t VMSize,
00161                                                uint64_t SectionDataStartOffset,
00162                                                uint64_t SectionDataSize) {
00163   // struct segment_command (56 bytes) or
00164   // struct segment_command_64 (72 bytes)
00165 
00166   uint64_t Start = OS.tell();
00167   (void) Start;
00168 
00169   unsigned SegmentLoadCommandSize =
00170     is64Bit() ? macho::SegmentLoadCommand64Size:
00171     macho::SegmentLoadCommand32Size;
00172   Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
00173   Write32(SegmentLoadCommandSize +
00174           NumSections * (is64Bit() ? macho::Section64Size :
00175                          macho::Section32Size));
00176 
00177   WriteBytes("", 16);
00178   if (is64Bit()) {
00179     Write64(0); // vmaddr
00180     Write64(VMSize); // vmsize
00181     Write64(SectionDataStartOffset); // file offset
00182     Write64(SectionDataSize); // file size
00183   } else {
00184     Write32(0); // vmaddr
00185     Write32(VMSize); // vmsize
00186     Write32(SectionDataStartOffset); // file offset
00187     Write32(SectionDataSize); // file size
00188   }
00189   Write32(0x7); // maxprot
00190   Write32(0x7); // initprot
00191   Write32(NumSections);
00192   Write32(0); // flags
00193 
00194   assert(OS.tell() - Start == SegmentLoadCommandSize);
00195 }
00196 
00197 void MachObjectWriter::WriteSection(const MCAssembler &Asm,
00198                                     const MCAsmLayout &Layout,
00199                                     const MCSectionData &SD,
00200                                     uint64_t FileOffset,
00201                                     uint64_t RelocationsStart,
00202                                     unsigned NumRelocations) {
00203   uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
00204 
00205   // The offset is unused for virtual sections.
00206   if (SD.getSection().isVirtualSection()) {
00207     assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
00208     FileOffset = 0;
00209   }
00210 
00211   // struct section (68 bytes) or
00212   // struct section_64 (80 bytes)
00213 
00214   uint64_t Start = OS.tell();
00215   (void) Start;
00216 
00217   const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
00218   WriteBytes(Section.getSectionName(), 16);
00219   WriteBytes(Section.getSegmentName(), 16);
00220   if (is64Bit()) {
00221     Write64(getSectionAddress(&SD)); // address
00222     Write64(SectionSize); // size
00223   } else {
00224     Write32(getSectionAddress(&SD)); // address
00225     Write32(SectionSize); // size
00226   }
00227   Write32(FileOffset);
00228 
00229   unsigned Flags = Section.getTypeAndAttributes();
00230   if (SD.hasInstructions())
00231     Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
00232 
00233   assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
00234   Write32(Log2_32(SD.getAlignment()));
00235   Write32(NumRelocations ? RelocationsStart : 0);
00236   Write32(NumRelocations);
00237   Write32(Flags);
00238   Write32(IndirectSymBase.lookup(&SD)); // reserved1
00239   Write32(Section.getStubSize()); // reserved2
00240   if (is64Bit())
00241     Write32(0); // reserved3
00242 
00243   assert(OS.tell() - Start == (is64Bit() ? macho::Section64Size :
00244                                macho::Section32Size));
00245 }
00246 
00247 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
00248                                               uint32_t NumSymbols,
00249                                               uint32_t StringTableOffset,
00250                                               uint32_t StringTableSize) {
00251   // struct symtab_command (24 bytes)
00252 
00253   uint64_t Start = OS.tell();
00254   (void) Start;
00255 
00256   Write32(macho::LCT_Symtab);
00257   Write32(macho::SymtabLoadCommandSize);
00258   Write32(SymbolOffset);
00259   Write32(NumSymbols);
00260   Write32(StringTableOffset);
00261   Write32(StringTableSize);
00262 
00263   assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
00264 }
00265 
00266 void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
00267                                                 uint32_t NumLocalSymbols,
00268                                                 uint32_t FirstExternalSymbol,
00269                                                 uint32_t NumExternalSymbols,
00270                                                 uint32_t FirstUndefinedSymbol,
00271                                                 uint32_t NumUndefinedSymbols,
00272                                                 uint32_t IndirectSymbolOffset,
00273                                                 uint32_t NumIndirectSymbols) {
00274   // struct dysymtab_command (80 bytes)
00275 
00276   uint64_t Start = OS.tell();
00277   (void) Start;
00278 
00279   Write32(macho::LCT_Dysymtab);
00280   Write32(macho::DysymtabLoadCommandSize);
00281   Write32(FirstLocalSymbol);
00282   Write32(NumLocalSymbols);
00283   Write32(FirstExternalSymbol);
00284   Write32(NumExternalSymbols);
00285   Write32(FirstUndefinedSymbol);
00286   Write32(NumUndefinedSymbols);
00287   Write32(0); // tocoff
00288   Write32(0); // ntoc
00289   Write32(0); // modtaboff
00290   Write32(0); // nmodtab
00291   Write32(0); // extrefsymoff
00292   Write32(0); // nextrefsyms
00293   Write32(IndirectSymbolOffset);
00294   Write32(NumIndirectSymbols);
00295   Write32(0); // extreloff
00296   Write32(0); // nextrel
00297   Write32(0); // locreloff
00298   Write32(0); // nlocrel
00299 
00300   assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
00301 }
00302 
00303 void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
00304                                   const MCAsmLayout &Layout) {
00305   MCSymbolData &Data = *MSD.SymbolData;
00306   const MCSymbol &Symbol = Data.getSymbol();
00307   uint8_t Type = 0;
00308   uint16_t Flags = Data.getFlags();
00309   uint64_t Address = 0;
00310 
00311   // Set the N_TYPE bits. See <mach-o/nlist.h>.
00312   //
00313   // FIXME: Are the prebound or indirect fields possible here?
00314   if (Symbol.isUndefined())
00315     Type = macho::STT_Undefined;
00316   else if (Symbol.isAbsolute())
00317     Type = macho::STT_Absolute;
00318   else
00319     Type = macho::STT_Section;
00320 
00321   // FIXME: Set STAB bits.
00322 
00323   if (Data.isPrivateExtern())
00324     Type |= macho::STF_PrivateExtern;
00325 
00326   // Set external bit.
00327   if (Data.isExternal() || Symbol.isUndefined())
00328     Type |= macho::STF_External;
00329 
00330   // Compute the symbol address.
00331   if (Symbol.isDefined()) {
00332     Address = getSymbolAddress(&Data, Layout);
00333   } else if (Data.isCommon()) {
00334     // Common symbols are encoded with the size in the address
00335     // field, and their alignment in the flags.
00336     Address = Data.getCommonSize();
00337 
00338     // Common alignment is packed into the 'desc' bits.
00339     if (unsigned Align = Data.getCommonAlignment()) {
00340       unsigned Log2Size = Log2_32(Align);
00341       assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
00342       if (Log2Size > 15)
00343         report_fatal_error("invalid 'common' alignment '" +
00344                            Twine(Align) + "'");
00345       // FIXME: Keep this mask with the SymbolFlags enumeration.
00346       Flags = (Flags & 0xF0FF) | (Log2Size << 8);
00347     }
00348   }
00349 
00350   // struct nlist (12 bytes)
00351 
00352   Write32(MSD.StringIndex);
00353   Write8(Type);
00354   Write8(MSD.SectionIndex);
00355 
00356   // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
00357   // value.
00358   Write16(Flags);
00359   if (is64Bit())
00360     Write64(Address);
00361   else
00362     Write32(Address);
00363 }
00364 
00365 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
00366                                                 uint32_t DataOffset,
00367                                                 uint32_t DataSize) {
00368   uint64_t Start = OS.tell();
00369   (void) Start;
00370 
00371   Write32(Type);
00372   Write32(macho::LinkeditLoadCommandSize);
00373   Write32(DataOffset);
00374   Write32(DataSize);
00375 
00376   assert(OS.tell() - Start == macho::LinkeditLoadCommandSize);
00377 }
00378 
00379 static unsigned ComputeLinkerOptionsLoadCommandSize(
00380   const std::vector<std::string> &Options, bool is64Bit)
00381 {
00382   unsigned Size = sizeof(macho::LinkerOptionsLoadCommand);
00383   for (unsigned i = 0, e = Options.size(); i != e; ++i)
00384     Size += Options[i].size() + 1;
00385   return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
00386 }
00387 
00388 void MachObjectWriter::WriteLinkerOptionsLoadCommand(
00389   const std::vector<std::string> &Options)
00390 {
00391   unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
00392   uint64_t Start = OS.tell();
00393   (void) Start;
00394 
00395   Write32(macho::LCT_LinkerOptions);
00396   Write32(Size);
00397   Write32(Options.size());
00398   uint64_t BytesWritten = sizeof(macho::LinkerOptionsLoadCommand);
00399   for (unsigned i = 0, e = Options.size(); i != e; ++i) {
00400     // Write each string, including the null byte.
00401     const std::string &Option = Options[i];
00402     WriteBytes(Option.c_str(), Option.size() + 1);
00403     BytesWritten += Option.size() + 1;
00404   }
00405 
00406   // Pad to a multiple of the pointer size.
00407   WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
00408 
00409   assert(OS.tell() - Start == Size);
00410 }
00411 
00412 
00413 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
00414                                         const MCAsmLayout &Layout,
00415                                         const MCFragment *Fragment,
00416                                         const MCFixup &Fixup,
00417                                         MCValue Target,
00418                                         uint64_t &FixedValue) {
00419   TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
00420                                        Target, FixedValue);
00421 }
00422 
00423 void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
00424   // This is the point where 'as' creates actual symbols for indirect symbols
00425   // (in the following two passes). It would be easier for us to do this sooner
00426   // when we see the attribute, but that makes getting the order in the symbol
00427   // table much more complicated than it is worth.
00428   //
00429   // FIXME: Revisit this when the dust settles.
00430 
00431   // Bind non lazy symbol pointers first.
00432   unsigned IndirectIndex = 0;
00433   for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
00434          ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
00435     const MCSectionMachO &Section =
00436       cast<MCSectionMachO>(it->SectionData->getSection());
00437 
00438     if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
00439       continue;
00440 
00441     // Initialize the section indirect symbol base, if necessary.
00442     IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
00443 
00444     Asm.getOrCreateSymbolData(*it->Symbol);
00445   }
00446 
00447   // Then lazy symbol pointers and symbol stubs.
00448   IndirectIndex = 0;
00449   for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
00450          ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
00451     const MCSectionMachO &Section =
00452       cast<MCSectionMachO>(it->SectionData->getSection());
00453 
00454     if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
00455         Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
00456       continue;
00457 
00458     // Initialize the section indirect symbol base, if necessary.
00459     IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
00460 
00461     // Set the symbol type to undefined lazy, but only on construction.
00462     //
00463     // FIXME: Do not hardcode.
00464     bool Created;
00465     MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
00466     if (Created)
00467       Entry.setFlags(Entry.getFlags() | 0x0001);
00468   }
00469 }
00470 
00471 /// ComputeSymbolTable - Compute the symbol table data
00472 ///
00473 /// \param StringTable [out] - The string table data.
00474 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
00475 /// string table.
00476 void MachObjectWriter::
00477 ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
00478                    std::vector<MachSymbolData> &LocalSymbolData,
00479                    std::vector<MachSymbolData> &ExternalSymbolData,
00480                    std::vector<MachSymbolData> &UndefinedSymbolData) {
00481   // Build section lookup table.
00482   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
00483   unsigned Index = 1;
00484   for (MCAssembler::iterator it = Asm.begin(),
00485          ie = Asm.end(); it != ie; ++it, ++Index)
00486     SectionIndexMap[&it->getSection()] = Index;
00487   assert(Index <= 256 && "Too many sections!");
00488 
00489   // Index 0 is always the empty string.
00490   StringMap<uint64_t> StringIndexMap;
00491   StringTable += '\x00';
00492 
00493   // Build the symbol arrays and the string table, but only for non-local
00494   // symbols.
00495   //
00496   // The particular order that we collect the symbols and create the string
00497   // table, then sort the symbols is chosen to match 'as'. Even though it
00498   // doesn't matter for correctness, this is important for letting us diff .o
00499   // files.
00500   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
00501          ie = Asm.symbol_end(); it != ie; ++it) {
00502     const MCSymbol &Symbol = it->getSymbol();
00503 
00504     // Ignore non-linker visible symbols.
00505     if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
00506       continue;
00507 
00508     if (!it->isExternal() && !Symbol.isUndefined())
00509       continue;
00510 
00511     uint64_t &Entry = StringIndexMap[Symbol.getName()];
00512     if (!Entry) {
00513       Entry = StringTable.size();
00514       StringTable += Symbol.getName();
00515       StringTable += '\x00';
00516     }
00517 
00518     MachSymbolData MSD;
00519     MSD.SymbolData = it;
00520     MSD.StringIndex = Entry;
00521 
00522     if (Symbol.isUndefined()) {
00523       MSD.SectionIndex = 0;
00524       UndefinedSymbolData.push_back(MSD);
00525     } else if (Symbol.isAbsolute()) {
00526       MSD.SectionIndex = 0;
00527       ExternalSymbolData.push_back(MSD);
00528     } else {
00529       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
00530       assert(MSD.SectionIndex && "Invalid section index!");
00531       ExternalSymbolData.push_back(MSD);
00532     }
00533   }
00534 
00535   // Now add the data for local symbols.
00536   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
00537          ie = Asm.symbol_end(); it != ie; ++it) {
00538     const MCSymbol &Symbol = it->getSymbol();
00539 
00540     // Ignore non-linker visible symbols.
00541     if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
00542       continue;
00543 
00544     if (it->isExternal() || Symbol.isUndefined())
00545       continue;
00546 
00547     uint64_t &Entry = StringIndexMap[Symbol.getName()];
00548     if (!Entry) {
00549       Entry = StringTable.size();
00550       StringTable += Symbol.getName();
00551       StringTable += '\x00';
00552     }
00553 
00554     MachSymbolData MSD;
00555     MSD.SymbolData = it;
00556     MSD.StringIndex = Entry;
00557 
00558     if (Symbol.isAbsolute()) {
00559       MSD.SectionIndex = 0;
00560       LocalSymbolData.push_back(MSD);
00561     } else {
00562       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
00563       assert(MSD.SectionIndex && "Invalid section index!");
00564       LocalSymbolData.push_back(MSD);
00565     }
00566   }
00567 
00568   // External and undefined symbols are required to be in lexicographic order.
00569   std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
00570   std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
00571 
00572   // Set the symbol indices.
00573   Index = 0;
00574   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
00575     LocalSymbolData[i].SymbolData->setIndex(Index++);
00576   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
00577     ExternalSymbolData[i].SymbolData->setIndex(Index++);
00578   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
00579     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
00580 
00581   // The string table is padded to a multiple of 4.
00582   while (StringTable.size() % 4)
00583     StringTable += '\x00';
00584 }
00585 
00586 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
00587                                                const MCAsmLayout &Layout) {
00588   uint64_t StartAddress = 0;
00589   const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
00590   for (int i = 0, n = Order.size(); i != n ; ++i) {
00591     const MCSectionData *SD = Order[i];
00592     StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
00593     SectionAddress[SD] = StartAddress;
00594     StartAddress += Layout.getSectionAddressSize(SD);
00595 
00596     // Explicitly pad the section to match the alignment requirements of the
00597     // following one. This is for 'gas' compatibility, it shouldn't
00598     /// strictly be necessary.
00599     StartAddress += getPaddingSize(SD, Layout);
00600   }
00601 }
00602 
00603 void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
00604                                                    const MCAsmLayout &Layout) {
00605   for (MCAssembler::symbol_iterator i = Asm.symbol_begin(),
00606                                     e = Asm.symbol_end();
00607       i != e; ++i) {
00608     MCSymbolData &SD = *i;
00609     if (!SD.getSymbol().isVariable())
00610       continue;
00611 
00612     // Is the variable is a symbol difference (SA - SB + C) expression,
00613     // and neither symbol is external, mark the variable as absolute.
00614     const MCExpr *Expr = SD.getSymbol().getVariableValue();
00615     MCValue Value;
00616     if (Expr->EvaluateAsRelocatable(Value, Layout)) {
00617       if (Value.getSymA() && Value.getSymB())
00618         const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
00619     }
00620   }
00621 }
00622 
00623 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
00624                                                 const MCAsmLayout &Layout) {
00625   computeSectionAddresses(Asm, Layout);
00626 
00627   // Create symbol data for any indirect symbols.
00628   BindIndirectSymbols(Asm);
00629 
00630   // Mark symbol difference expressions in variables (from .set or = directives)
00631   // as absolute.
00632   markAbsoluteVariableSymbols(Asm, Layout);
00633 
00634   // Compute symbol table information and bind symbol indices.
00635   ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
00636                      UndefinedSymbolData);
00637 }
00638 
00639 bool MachObjectWriter::
00640 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
00641                                        const MCSymbolData &DataA,
00642                                        const MCFragment &FB,
00643                                        bool InSet,
00644                                        bool IsPCRel) const {
00645   if (InSet)
00646     return true;
00647 
00648   // The effective address is
00649   //     addr(atom(A)) + offset(A)
00650   //   - addr(atom(B)) - offset(B)
00651   // and the offsets are not relocatable, so the fixup is fully resolved when
00652   //  addr(atom(A)) - addr(atom(B)) == 0.
00653   const MCSymbolData *A_Base = 0, *B_Base = 0;
00654 
00655   const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
00656   const MCSection &SecA = SA.getSection();
00657   const MCSection &SecB = FB.getParent()->getSection();
00658 
00659   if (IsPCRel) {
00660     // The simple (Darwin, except on x86_64) way of dealing with this was to
00661     // assume that any reference to a temporary symbol *must* be a temporary
00662     // symbol in the same atom, unless the sections differ. Therefore, any PCrel
00663     // relocation to a temporary symbol (in the same section) is fully
00664     // resolved. This also works in conjunction with absolutized .set, which
00665     // requires the compiler to use .set to absolutize the differences between
00666     // symbols which the compiler knows to be assembly time constants, so we
00667     // don't need to worry about considering symbol differences fully resolved.
00668     //
00669     // If the file isn't using sub-sections-via-symbols, we can make the
00670     // same assumptions about any symbol that we normally make about
00671     // assembler locals.
00672 
00673     if (!Asm.getBackend().hasReliableSymbolDifference()) {
00674       if (!SA.isInSection() || &SecA != &SecB ||
00675           (!SA.isTemporary() &&
00676            FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
00677            Asm.getSubsectionsViaSymbols()))
00678         return false;
00679       return true;
00680     }
00681     // For Darwin x86_64, there is one special case when the reference IsPCRel.
00682     // If the fragment with the reference does not have a base symbol but meets
00683     // the simple way of dealing with this, in that it is a temporary symbol in
00684     // the same atom then it is assumed to be fully resolved.  This is needed so
00685     // a relocation entry is not created and so the static linker does not
00686     // mess up the reference later.
00687     else if(!FB.getAtom() &&
00688             SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
00689       return true;
00690     }
00691   } else {
00692     if (!TargetObjectWriter->useAggressiveSymbolFolding())
00693       return false;
00694   }
00695 
00696   const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
00697 
00698   // Bail if the symbol has no fragment.
00699   if (!FA)
00700     return false;
00701 
00702   A_Base = FA->getAtom();
00703   if (!A_Base)
00704     return false;
00705 
00706   B_Base = FB.getAtom();
00707   if (!B_Base)
00708     return false;
00709 
00710   // If the atoms are the same, they are guaranteed to have the same address.
00711   if (A_Base == B_Base)
00712     return true;
00713 
00714   // Otherwise, we can't prove this is fully resolved.
00715   return false;
00716 }
00717 
00718 void MachObjectWriter::WriteObject(MCAssembler &Asm,
00719                                    const MCAsmLayout &Layout) {
00720   unsigned NumSections = Asm.size();
00721 
00722   // The section data starts after the header, the segment load command (and
00723   // section headers) and the symbol table.
00724   unsigned NumLoadCommands = 1;
00725   uint64_t LoadCommandsSize = is64Bit() ?
00726     macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
00727     macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
00728 
00729   // Add the data-in-code load command size, if used.
00730   unsigned NumDataRegions = Asm.getDataRegions().size();
00731   if (NumDataRegions) {
00732     ++NumLoadCommands;
00733     LoadCommandsSize += macho::LinkeditLoadCommandSize;
00734   }
00735 
00736   // Add the symbol table load command sizes, if used.
00737   unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
00738     UndefinedSymbolData.size();
00739   if (NumSymbols) {
00740     NumLoadCommands += 2;
00741     LoadCommandsSize += (macho::SymtabLoadCommandSize +
00742                          macho::DysymtabLoadCommandSize);
00743   }
00744 
00745   // Add the linker option load commands sizes.
00746   const std::vector<std::vector<std::string> > &LinkerOptions =
00747     Asm.getLinkerOptions();
00748   for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
00749     ++NumLoadCommands;
00750     LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
00751                                                             is64Bit());
00752   }
00753   
00754   // Compute the total size of the section data, as well as its file size and vm
00755   // size.
00756   uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
00757                                macho::Header32Size) + LoadCommandsSize;
00758   uint64_t SectionDataSize = 0;
00759   uint64_t SectionDataFileSize = 0;
00760   uint64_t VMSize = 0;
00761   for (MCAssembler::const_iterator it = Asm.begin(),
00762          ie = Asm.end(); it != ie; ++it) {
00763     const MCSectionData &SD = *it;
00764     uint64_t Address = getSectionAddress(&SD);
00765     uint64_t Size = Layout.getSectionAddressSize(&SD);
00766     uint64_t FileSize = Layout.getSectionFileSize(&SD);
00767     FileSize += getPaddingSize(&SD, Layout);
00768 
00769     VMSize = std::max(VMSize, Address + Size);
00770 
00771     if (SD.getSection().isVirtualSection())
00772       continue;
00773 
00774     SectionDataSize = std::max(SectionDataSize, Address + Size);
00775     SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
00776   }
00777 
00778   // The section data is padded to 4 bytes.
00779   //
00780   // FIXME: Is this machine dependent?
00781   unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
00782   SectionDataFileSize += SectionDataPadding;
00783 
00784   // Write the prolog, starting with the header and load command...
00785   WriteHeader(NumLoadCommands, LoadCommandsSize,
00786               Asm.getSubsectionsViaSymbols());
00787   WriteSegmentLoadCommand(NumSections, VMSize,
00788                           SectionDataStart, SectionDataSize);
00789 
00790   // ... and then the section headers.
00791   uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
00792   for (MCAssembler::const_iterator it = Asm.begin(),
00793          ie = Asm.end(); it != ie; ++it) {
00794     std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
00795     unsigned NumRelocs = Relocs.size();
00796     uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
00797     WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
00798     RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
00799   }
00800 
00801   // Write the data-in-code load command, if used.
00802   uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
00803   if (NumDataRegions) {
00804     uint64_t DataRegionsOffset = RelocTableEnd;
00805     uint64_t DataRegionsSize = NumDataRegions * 8;
00806     WriteLinkeditLoadCommand(macho::LCT_DataInCode, DataRegionsOffset,
00807                              DataRegionsSize);
00808   }
00809 
00810   // Write the symbol table load command, if used.
00811   if (NumSymbols) {
00812     unsigned FirstLocalSymbol = 0;
00813     unsigned NumLocalSymbols = LocalSymbolData.size();
00814     unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
00815     unsigned NumExternalSymbols = ExternalSymbolData.size();
00816     unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
00817     unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
00818     unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
00819     unsigned NumSymTabSymbols =
00820       NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
00821     uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
00822     uint64_t IndirectSymbolOffset = 0;
00823 
00824     // If used, the indirect symbols are written after the section data.
00825     if (NumIndirectSymbols)
00826       IndirectSymbolOffset = DataInCodeTableEnd;
00827 
00828     // The symbol table is written after the indirect symbol data.
00829     uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
00830 
00831     // The string table is written after symbol table.
00832     uint64_t StringTableOffset =
00833       SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
00834                                               macho::Nlist32Size);
00835     WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
00836                            StringTableOffset, StringTable.size());
00837 
00838     WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
00839                              FirstExternalSymbol, NumExternalSymbols,
00840                              FirstUndefinedSymbol, NumUndefinedSymbols,
00841                              IndirectSymbolOffset, NumIndirectSymbols);
00842   }
00843 
00844   // Write the linker options load commands.
00845   for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
00846     WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
00847   }
00848 
00849   // Write the actual section data.
00850   for (MCAssembler::const_iterator it = Asm.begin(),
00851          ie = Asm.end(); it != ie; ++it) {
00852     Asm.writeSectionData(it, Layout);
00853 
00854     uint64_t Pad = getPaddingSize(it, Layout);
00855     for (unsigned int i = 0; i < Pad; ++i)
00856       Write8(0);
00857   }
00858 
00859   // Write the extra padding.
00860   WriteZeros(SectionDataPadding);
00861 
00862   // Write the relocation entries.
00863   for (MCAssembler::const_iterator it = Asm.begin(),
00864          ie = Asm.end(); it != ie; ++it) {
00865     // Write the section relocation entries, in reverse order to match 'as'
00866     // (approximately, the exact algorithm is more complicated than this).
00867     std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
00868     for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
00869       Write32(Relocs[e - i - 1].Word0);
00870       Write32(Relocs[e - i - 1].Word1);
00871     }
00872   }
00873 
00874   // Write out the data-in-code region payload, if there is one.
00875   for (MCAssembler::const_data_region_iterator
00876          it = Asm.data_region_begin(), ie = Asm.data_region_end();
00877          it != ie; ++it) {
00878     const DataRegionData *Data = &(*it);
00879     uint64_t Start =
00880       getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
00881                        Layout);
00882     uint64_t End =
00883       getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
00884                        Layout);
00885     DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
00886                  << "  start: " << Start << "(" << Data->Start->getName() << ")"
00887                  << "  end: " << End << "(" << Data->End->getName() << ")"
00888                  << "  size: " << End - Start
00889                  << "\n");
00890     Write32(Start);
00891     Write16(End - Start);
00892     Write16(Data->Kind);
00893   }
00894 
00895   // Write the symbol table data, if used.
00896   if (NumSymbols) {
00897     // Write the indirect symbol entries.
00898     for (MCAssembler::const_indirect_symbol_iterator
00899            it = Asm.indirect_symbol_begin(),
00900            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
00901       // Indirect symbols in the non lazy symbol pointer section have some
00902       // special handling.
00903       const MCSectionMachO &Section =
00904         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
00905       if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
00906         // If this symbol is defined and internal, mark it as such.
00907         if (it->Symbol->isDefined() &&
00908             !Asm.getSymbolData(*it->Symbol).isExternal()) {
00909           uint32_t Flags = macho::ISF_Local;
00910           if (it->Symbol->isAbsolute())
00911             Flags |= macho::ISF_Absolute;
00912           Write32(Flags);
00913           continue;
00914         }
00915       }
00916 
00917       Write32(Asm.getSymbolData(*it->Symbol).getIndex());
00918     }
00919 
00920     // FIXME: Check that offsets match computed ones.
00921 
00922     // Write the symbol table entries.
00923     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
00924       WriteNlist(LocalSymbolData[i], Layout);
00925     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
00926       WriteNlist(ExternalSymbolData[i], Layout);
00927     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
00928       WriteNlist(UndefinedSymbolData[i], Layout);
00929 
00930     // Write the string table.
00931     OS << StringTable.str();
00932   }
00933 }
00934 
00935 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
00936                                              raw_ostream &OS,
00937                                              bool IsLittleEndian) {
00938   return new MachObjectWriter(MOTW, OS, IsLittleEndian);
00939 }